text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
# Inference and Validation Now that you have a trained network, you can use it for making predictions. This is typically called **inference**, a term borrowed from statistics. However, neural networks have a tendency to perform *too well* on the training data and aren't able to generalize to data that hasn't been seen before. This is called **overfitting** and it impairs inference performance. To test for overfitting while training, we measure the performance on data not in the training set called the **validation** set. We avoid overfitting through regularization such as dropout while monitoring the validation performance during training. In this notebook, I'll show you how to do this in PyTorch. As usual, let's start by loading the dataset through torchvision. You'll learn more about torchvision and loading data in a later part. This time we'll be taking advantage of the test set which you can get by setting `train=False` here: ```python testset = datasets.FashionMNIST('~/.pytorch/F_MNIST_data/', download=True, train=False, transform=transform) ``` The test set contains images just like the training set. Typically you'll see 10-20% of the original dataset held out for testing and validation with the rest being used for training. ``` import torch from torchvision import datasets, transforms # Define a transform to normalize the data transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))]) # Download and load the training data trainset = datasets.FashionMNIST('~/.pytorch/F_MNIST_data/', download=True, train=True, transform=transform) trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True) # Download and load the test data testset = datasets.FashionMNIST('~/.pytorch/F_MNIST_data/', download=True, train=False, transform=transform) testloader = torch.utils.data.DataLoader(testset, batch_size=64, shuffle=True) ``` Here I'll create a model like normal, using the same one from my solution for part 4. ``` from torch import nn, optim import torch.nn.functional as F class Classifier(nn.Module): def __init__(self): super().__init__() self.fc1 = nn.Linear(784, 256) self.fc2 = nn.Linear(256, 128) self.fc3 = nn.Linear(128, 64) self.fc4 = nn.Linear(64, 10) def forward(self, x): # make sure input tensor is flattened x = x.view(x.shape[0], -1) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = F.relu(self.fc3(x)) x = F.log_softmax(self.fc4(x), dim=1) return x ``` The goal of validation is to measure the model's performance on data that isn't part of the training set. Performance here is up to the developer to define though. Typically this is just accuracy, the percentage of classes the network predicted correctly. Other options are [precision and recall](https://en.wikipedia.org/wiki/Precision_and_recall#Definition_(classification_context)) and top-5 error rate. We'll focus on accuracy here. First I'll do a forward pass with one batch from the test set. ``` model = Classifier() images, labels = next(iter(testloader)) # Get the class probabilities ps = torch.exp(model(images)) # Make sure the shape is appropriate, we should get 10 class probabilities for 64 examples print(ps.shape) ``` With the probabilities, we can get the most likely class using the `ps.topk` method. This returns the $k$ highest values. Since we just want the most likely class, we can use `ps.topk(1)`. This returns a tuple of the top-$k$ values and the top-$k$ indices. If the highest value is the fifth element, we'll get back 4 as the index. ``` top_p, top_class = ps.topk(1, dim=1) # Look at the most likely classes for the first 10 examples print(top_class[:10,:]) ``` Now we can check if the predicted classes match the labels. This is simple to do by equating `top_class` and `labels`, but we have to be careful of the shapes. Here `top_class` is a 2D tensor with shape `(64, 1)` while `labels` is 1D with shape `(64)`. To get the equality to work out the way we want, `top_class` and `labels` must have the same shape. If we do ```python equals = top_class == labels ``` `equals` will have shape `(64, 64)`, try it yourself. What it's doing is comparing the one element in each row of `top_class` with each element in `labels` which returns 64 True/False boolean values for each row. ``` equals = top_class == labels.view(*top_class.shape) ``` Now we need to calculate the percentage of correct predictions. `equals` has binary values, either 0 or 1. This means that if we just sum up all the values and divide by the number of values, we get the percentage of correct predictions. This is the same operation as taking the mean, so we can get the accuracy with a call to `torch.mean`. If only it was that simple. If you try `torch.mean(equals)`, you'll get an error ``` RuntimeError: mean is not implemented for type torch.ByteTensor ``` This happens because `equals` has type `torch.ByteTensor` but `torch.mean` isn't implemented for tensors with that type. So we'll need to convert `equals` to a float tensor. Note that when we take `torch.mean` it returns a scalar tensor, to get the actual value as a float we'll need to do `accuracy.item()`. ``` accuracy = torch.mean(equals.type(torch.FloatTensor)) print(f'Accuracy: {accuracy.item()*100}%') ``` The network is untrained so it's making random guesses and we should see an accuracy around 10%. Now let's train our network and include our validation pass so we can measure how well the network is performing on the test set. Since we're not updating our parameters in the validation pass, we can speed up our code by turning off gradients using `torch.no_grad()`: ```python # turn off gradients with torch.no_grad(): # validation pass here for images, labels in testloader: ... ``` >**Exercise:** Implement the validation loop below and print out the total accuracy after the loop. You can largely copy and paste the code from above, but I suggest typing it in because writing it out yourself is essential for building the skill. In general you'll always learn more by typing it rather than copy-pasting. You should be able to get an accuracy above 80%. ``` model = Classifier() criterion = nn.NLLLoss() optimizer = optim.Adam(model.parameters(), lr=0.003) epochs = 30 steps = 0 train_losses, test_losses = [], [] for e in range(epochs): train_total_loss = 0 for images, labels in trainloader: optimizer.zero_grad() log_ps = model(images) loss = criterion(log_ps, labels) loss.backward() optimizer.step() train_total_loss += loss.item() else: ## TODO: Implement the validation pass and print out the validation accuracy test_total_loss = 0 test_true = 0 with torch.no_grad(): for images, labels in testloader: log_ps = model(images) loss = criterion(log_ps, labels) test_total_loss += loss.item() ps = torch.exp(log_ps) top_p, top_class = ps.topk(1, dim=1) equals = top_class == labels.view(*top_class.shape) test_true += equals.sum().item() train_loss = train_total_loss / len(trainloader.dataset) test_loss = test_total_loss / len(testloader.dataset) train_losses.append(train_loss) test_losses.append(test_loss) print("Epoch: {}/{}.. ".format(e+1, epochs), "Training Loss: {:.3f}.. ".format(train_loss), "Test Loss: {:.3f}.. ".format(test_loss), "Test Accuracy: {:.3f}".format(test_true / len(testloader.dataset))) import matplotlib.pyplot as plt plt.plot(train_losses, label="Training loss") plt.plot(test_losses, label="Testing loss") plt.show() ``` ## Overfitting If we look at the training and validation losses as we train the network, we can see a phenomenon known as overfitting. <img src='assets/overfitting.png' width=450px> The network learns the training set better and better, resulting in lower training losses. However, it starts having problems generalizing to data outside the training set leading to the validation loss increasing. The ultimate goal of any deep learning model is to make predictions on new data, so we should strive to get the lowest validation loss possible. One option is to use the version of the model with the lowest validation loss, here the one around 8-10 training epochs. This strategy is called *early-stopping*. In practice, you'd save the model frequently as you're training then later choose the model with the lowest validation loss. The most common method to reduce overfitting (outside of early-stopping) is *dropout*, where we randomly drop input units. This forces the network to share information between weights, increasing it's ability to generalize to new data. Adding dropout in PyTorch is straightforward using the [`nn.Dropout`](https://pytorch.org/docs/stable/nn.html#torch.nn.Dropout) module. ```python class Classifier(nn.Module): def __init__(self): super().__init__() self.fc1 = nn.Linear(784, 256) self.fc2 = nn.Linear(256, 128) self.fc3 = nn.Linear(128, 64) self.fc4 = nn.Linear(64, 10) # Dropout module with 0.2 drop probability self.dropout = nn.Dropout(p=0.2) def forward(self, x): # make sure input tensor is flattened x = x.view(x.shape[0], -1) # Now with dropout x = self.dropout(F.relu(self.fc1(x))) x = self.dropout(F.relu(self.fc2(x))) x = self.dropout(F.relu(self.fc3(x))) # output so no dropout here x = F.log_softmax(self.fc4(x), dim=1) return x ``` During training we want to use dropout to prevent overfitting, but during inference we want to use the entire network. So, we need to turn off dropout during validation, testing, and whenever we're using the network to make predictions. To do this, you use `model.eval()`. This sets the model to evaluation mode where the dropout probability is 0. You can turn dropout back on by setting the model to train mode with `model.train()`. In general, the pattern for the validation loop will look like this, where you turn off gradients, set the model to evaluation mode, calculate the validation loss and metric, then set the model back to train mode. ```python # turn off gradients with torch.no_grad(): # set model to evaluation mode model.eval() # validation pass here for images, labels in testloader: ... # set model back to train mode model.train() ``` > **Exercise:** Add dropout to your model and train it on Fashion-MNIST again. See if you can get a lower validation loss or higher accuracy. ``` ## TODO: Define your model with dropout added from torch import nn, optim import torch.nn.functional as F class Classifier(nn.Module): def __init__(self): super().__init__() self.fc1 = nn.Linear(784, 256) self.fc2 = nn.Linear(256, 128) self.fc3 = nn.Linear(128, 64) self.fc4 = nn.Linear(64, 10) self.dropout = nn.Dropout(p=0.2) def forward(self, x): # make sure input tensor is flattened x = x.view(x.shape[0], -1) x = self.dropout(F.relu(self.fc1(x))) x = self.dropout(F.relu(self.fc2(x))) x = self.dropout(F.relu(self.fc3(x))) x = F.log_softmax(self.fc4(x), dim=1) return x ## TODO: Train your model with dropout, and monitor the training progress with the validation loss and accuracy model = Classifier() criterion = nn.NLLLoss() optimizer = optim.Adam(model.parameters(), lr=0.003) epochs = 30 steps = 0 train_losses, test_losses = [], [] for e in range(epochs): train_total_loss = 0 for images, labels in trainloader: optimizer.zero_grad() log_ps = model(images) loss = criterion(log_ps, labels) loss.backward() optimizer.step() train_total_loss += loss.item() else: ## TODO: Implement the validation pass and print out the validation accuracy test_total_loss = 0 test_true = 0 with torch.no_grad(): model.eval() for images, labels in testloader: log_ps = model(images) loss = criterion(log_ps, labels) test_total_loss += loss.item() ps = torch.exp(log_ps) top_p, top_class = ps.topk(1, dim=1) equals = top_class == labels.view(*top_class.shape) test_true += equals.sum().item() model.train() train_loss = train_total_loss / len(trainloader.dataset) test_loss = test_total_loss / len(testloader.dataset) train_losses.append(train_loss) test_losses.append(test_loss) print("Epoch: {}/{}.. ".format(e+1, epochs), "Training Loss: {:.5f}.. ".format(train_loss), "Test Loss: {:.5f}.. ".format(test_loss), "Test Accuracy: {:.5f}".format(test_true / len(testloader.dataset))) %matplotlib inline import matplotlib.pyplot as plt plt.plot(train_losses, label="Training loss") plt.plot(test_losses, label="Testing loss") plt.show() ``` ## Inference Now that the model is trained, we can use it for inference. We've done this before, but now we need to remember to set the model in inference mode with `model.eval()`. You'll also want to turn off autograd with the `torch.no_grad()` context. ``` # Import helper module (should be in the repo) import helper # Test out your network! model.eval() dataiter = iter(testloader) images, labels = dataiter.next() img = images[0] # Convert 2D image to 1D vector img = img.view(1, 784) # Calculate the class probabilities (softmax) for img with torch.no_grad(): output = model.forward(img) ps = torch.exp(output) # Plot the image and probabilities helper.view_classify(img.view(1, 28, 28), ps, version='Fashion') ``` ## Next Up! In the next part, I'll show you how to save your trained models. In general, you won't want to train a model everytime you need it. Instead, you'll train once, save it, then load the model when you want to train more or use if for inference.
github_jupyter
# Calibrate dark images Dark images, like any other images, need to be calibrated. Depending on the data you have and the choices you have made in reducing your data, the steps to reducing your images may include: 1. Subtracting overscan (only if you decide to subtract overscan from all images). 2. Trim the image (if it has overscan, whether you are using the overscan or not). 3. Subtract bias (if you need to scale the calibrated dark frames to a different exposure time). ``` from pathlib import Path from astropy.nddata import CCDData from ccdproc import ImageFileCollection import ccdproc as ccdp ``` ## Example 1: Overscan subtracted, bias not removed ### Take a look at what images you have First we gather up some information about the raw images and the reduced images up to this point. These examples have darks stored in a subdirectory of the folder with the rest of the images, so we create an `ImageFileCollection` for each. ``` ex1_path_raw = Path('example-cryo-LFC') ex1_images_raw = ImageFileCollection(ex1_path_raw) ex1_darks_raw = ImageFileCollection(ex1_path_raw / 'darks') ex1_path_reduced = Path('example1-reduced') ex1_images_reduced = ImageFileCollection(ex1_path_reduced) ``` #### Raw images, everything except the darks ``` ex1_images_raw.summary['file', 'imagetyp', 'exptime', 'filter'] ``` #### Raw dark frames ``` ex1_darks_raw.summary['file', 'imagetyp', 'exptime', 'filter'] ``` ### Decide which calibration steps to take This example is, again, one of the chips of the LFC camera at Palomar. In earlier notebooks we have seen that the chip has a [useful overscan region](01.08-Overscan.ipynb#Case-1:-Cryogenically-cooled-Large-Format-Camera-(LFC)-at-Palomar), has little dark current except for some hot pixels, and sensor glow in one corner of the chip. Looking at the list of non-dark images (i.e., the flat and light images) shows that for each exposure time in the non-dark images there is a set of dark exposures that has a matching, or very close to matching, exposure time. To be more explicit, there are flats with exposure times of 7.0 sec and 70.011 sec and darks with exposure time of 7.0 and 70.0 sec. The dark and flat exposure times are close enough that there is no need to scale them. The two images of an object are each roughly 300 sec, matching the darks with exposure time 300 sec. The very small difference in exposure time, under 0.1 sec, does not need to be compensated for. Given this, we will: 1. Subtract overscan from each of the darks. The useful overscan region is XXX (see LINK). 2. Trim the overscan out of the dark images. We will *not* subtract bias from these images because we will *not* need to rescale them to a different exposure time. ### Calibrate the individual dark frames ``` for ccd, file_name in ex1_darks_raw.ccds(imagetyp='DARK', # Just get the dark frames ccd_kwargs={'unit': 'adu'}, # CCDData requires a unit for the image if # it is not in the header return_fname=True # Provide the file name too. ): # Subtract the overscan ccd = ccdp.subtract_overscan(ccd, overscan=ccd[:, 2055:], median=True) # Trim the overscan ccd = ccdp.trim_image(ccd[:, :2048]) # Save the result ccd.write(ex1_path_reduced / file_name) ``` #### Reduced images (so far) ``` ex1_images_reduced.refresh() ex1_images_reduced.summary['file', 'imagetyp', 'exptime', 'filter', 'combined'] ``` ## Example 2: Overscan not subtracted, bias is removed ``` ex2_path_raw = Path('example-thermo-electric') ex2_images_raw = ImageFileCollection(ex2_path_raw) ex2_path_reduced = Path('example2-reduced') ex2_images_reduced = ImageFileCollection(ex2_path_reduced) ``` We begin by looking at what exposure times we have in this data. ``` ex2_images_raw.summary['file', 'imagetyp', 'exposure'].show_in_notebook() ``` ### Decide what steps to take next In this case the only dark frames have exposure time 90 sec. Though that matches the exposure time of the science images, the flat field images are much shorter exposure time, ranging from 1 sec to 1.21 sec. This type of range of exposure is typical when twilight flats are taken. Since these are a much different exposure time than the darks, the dark frames will need to be scaled. Recall that for this camera the overscan is not useful and should be trimmed off. Given this, we will: 1. Trim the overscan from each of the dark frames. 2. Subtract calibration bias from the dark frames so that we can scale the darks to a different exposure time. ### Calibration the individual dark frames First, we read the combined bias image created in the previous notebook. Though we could do this based on the file name, using a systematic set of header keywords to keep track of which images have been combined is less likely to lead to errors. ``` combined_bias = CCDData.read(ex2_images_reduced.files_filtered(imagetyp='bias', combined=True, include_path=True)[0]) for ccd, file_name in ex2_images_raw.ccds(imagetyp='DARK', # Just get the bias frames return_fname=True # Provide the file name too. ): # Trim the overscan ccd = ccdp.trim_image(ccd[:, :4096]) # Subtract bias ccd = ccdp.subtract_bias(ccd, combined_bias) # Save the result ccd.write(ex2_path_reduced / file_name) ```
github_jupyter
# Lecture 8 - CME 193 - Python scripts So far, we've been working in Jupyter notebooks, which are nice and interactive. However, they can be clunky if you have lots of code. It can be annoying to have to run one cell at a time. For large codebases, most people work with Python scripts. The code in the cells below are meant to be run in Python scripts, not Jupyter notebooks. That means that they are saved in files that end in `.py` and run via the command line. As a first example, save the following code in a file called `main.py`. ``` # main.py import numpy as np print(np.pi) ``` To run this script, open a terminal, change into the directory with `main.py`, and run python main.py If all goes well, then you should see $\pi$ printed! Running Python scripts is very similar to running a cell in a notebook, where Python executes each line in the file in a sequence. One difference is that anything you want to output needs to be explicitly `print`ed. Otherwise, you won't see any output. One difference is that with Python scripts, it's sometimes useful to accept command line arguments. For example, if your script saves its output to a file, it might be useful to accept a filename, like: python main.py output.txt To access the command line arguments from a Python script, you can use `sys.argv`, which is a list, in this case `['main.py', 'output.txt']`. We can access `output.txt` using the standard indexing notation, like `sys.argv[1]`. ``` # main.py import sys print(sys.argv) print(sys.argv[1]) ``` Reading elements of this list works fine if you only have one or two arguments. For anything more complicated, Python comes with a built-in library called `argparse`. This is beyond the scope of this class, but here is an example that accepts a command line argument called `num_iters`, which defaults to `100` if nothing is passed. You can pass a different value like this: python main.py --num_iters 10000 ``` # main.py import argparse parser = argparse.ArgumentParser() parser.add_argument('--num_iters', default=100, type=int, help='number of iterations') args = parser.parse_args() print(args.num_iters) ``` One thing that is easy in Jupyter notebooks but tricky in Python scripts is plotting. If you're lucky, the plot will still pop up, but one thing you can always do is save the plot to a file, as below. ``` # main.py import pandas as pd # The following two lines might be necessary, depending on your operating system. If you get # an error message initially, you can uncomment these lines to see if it works. # import matplotlib # matplotlib.use('Agg') import matplotlib.pyplot as plt # Load the abalone dataset from lecture 7. df = pd.read_csv('http://archive.ics.uci.edu/ml/machine-learning-databases/abalone/abalone.data', header=None, names=['sex', 'length', 'diameter', 'height', 'weight', 'shucked_weight', 'viscera_weight', 'shell_weight', 'rings']) df.plot('weight', 'rings', kind='scatter') # This line might pop open a plot, but it might not on some computers. plt.show() # An alternative to showing the plot is to save it as an image. plt.savefig('figure.png') ``` Sometimes it's useful to save things to disk, after we've done a long calculation for example. Here are several ways to do so: ``` # Save a Pandas dataframe. df.to_csv('data.csv') # Save a NumPy array. np.save(arr, 'data.npy') # Write text to a file. Warning: the 'w' means overwrite, which deletes anything already # existing in that file! To append to the file instead, use 'a' instead of 'w'. f = open('test.txt', 'w') f.write('hello world') f.close() # This is how to read a file (you can treat f as a list of lines that we can iterate over). f = open('test.txt', 'r') for line in f: print(line) f.close() # Closing a file when we're done saves memory. This is alternate syntax that automatically # closes the file after executing all the indented code inside the if block. with open('test.txt', 'r') as f: for line in f: print(line) ``` Often it makes sense to split Python scripts into multiple files. For example, suppose we have another file called `other.py`, where we define useful functions. ``` # other.py import numpy as np def compute_pi(): return np.pi ``` You can access the function using the `import` command, just like other libraries. ``` # main.py import other print(other.compute_pi()) # Alternatively: import other.compute_pi as compute_pi print(compute_pi()) # To import a file in a subdirectory, for example, computations/other.py, we would use: import computations.other as other print(other.compute_pi()) ``` You might encounter this weird block of code, `if __name__ == '__main__':`, in other people's Python code. It denotes code that is executed only if the file is run directly (`python other.py`), and not if it is merely imported. That way, `other.py` operates as both a standalone script that can be run or as a library file that can be imported. ``` # other.py import numpy as np def compute_pi(): return np.pi # Note that this will get executed even if this file is imported. print('Computing pi...') if __name__ == '__main__': # This only gets executed if this file is run with `python other.py`. print('Computing pi...') ```
github_jupyter
# Language Model analysis ``` import pandas as pd import time import matplotlib.pyplot as plt import numpy as np from gensim.models import Word2Vec from gensim import logging logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) # embedding models, base model model_path = "/Users/khosseini/myJobs/ATI/Projects/2019/Living-with-Machines-code/language-lab-mro/lexicon_expansion/interactive_expansion/models/all_books/w2v_005/w2v_words.model" w2v = Word2Vec.load(model_path) # OCR model, quality 1, 2 model_path = "/Users/khosseini/myJobs/ATI/Projects/2019/lwm_ocr_assessment/LMs/w2v_005_EM_ocr_qual_1_2.model" w2v_em_ocr_qual_1_2 = Word2Vec.load(model_path) # corrected model, quality 1, 2 model_path = "/Users/khosseini/myJobs/ATI/Projects/2019/lwm_ocr_assessment/LMs/w2v_005_EM_corr_qual_1_2.model" w2v_em_corr_qual_1_2 = Word2Vec.load(model_path) # OCR model, quality 3, 4 model_path = "/Users/khosseini/myJobs/ATI/Projects/2019/lwm_ocr_assessment/LMs/w2v_005_EM_ocr_qual_3_4.model" w2v_em_ocr_qual_3_4 = Word2Vec.load(model_path) # corrected model, quality 3, 4 model_path = "/Users/khosseini/myJobs/ATI/Projects/2019/lwm_ocr_assessment/LMs/w2v_005_EM_corr_qual_3_4.model" w2v_em_corr_qual_3_4 = Word2Vec.load(model_path) def found_neighbors(myrow, embedding, colname='vocab', topn=1): try: vocab_neigh = embedding.wv.most_similar([myrow['vocab']], topn=topn) return list(np.array(vocab_neigh)[:, 0]) except KeyError: return [] def jaccard_similarity_df(myrow, colname_1, colname_2, make_lowercase=True): """ Jaccard similarity between two documents (e.g., OCR and Human) on flattened list of words """ list1 = myrow[colname_1] list2 = myrow[colname_2] if make_lowercase: list1 = [x.lower() for x in list1] list2 = [x.lower() for x in list2] intersection = len(list(set(list1).intersection(list2))) union = (len(list1) + len(list2)) - intersection return float(intersection) / union ``` # Quality bands 3, 4 ## Create list of words and their frequencies in the corrected set ``` words_corrected = [] for item in w2v_em_corr_qual_3_4.wv.vocab: words_corrected.append([item, int(w2v_em_corr_qual_3_4.wv.vocab[item].count)]) pd_words = pd.DataFrame(words_corrected, columns=['vocab', 'count']) pd_words = pd_words.sort_values(by=['count'], ascending=False) print("size: {}".format(len(pd_words))) pd_words.head() pd2search = pd_words[0:5000] pd2search neigh_jaccard_bands_3_4 = [] for topn in [1, 2, 5, 10, 50, 100, 500, 1000, 5000, 10000, 50000]: print("topn: {}".format(topn)) t1 = time.time() pd2search = pd_words[0:1000] pd2search['w2v_em_corr_qual_3_4'] = pd2search.apply(found_neighbors, args=[w2v_em_corr_qual_3_4, 'vocab', topn], axis=1) print("corr: {}".format(time.time() - t1)) pd2search['w2v_em_ocr_qual_3_4'] = pd2search.apply(found_neighbors, args=[w2v_em_ocr_qual_3_4, 'vocab', topn], axis=1) pd2search['jaccard_qual_3_4'] = \ pd2search.apply(jaccard_similarity_df, args=['w2v_em_corr_qual_3_4', "w2v_em_ocr_qual_3_4", True], axis=1) neigh_jaccard_bands_3_4.append( [topn, pd2search['jaccard_qual_3_4'].mean(), pd2search['jaccard_qual_3_4'].std()]) print("total: {}".format(time.time() - t1)) neigh_jaccard_bands_3_4 = np.array(neigh_jaccard_bands_3_4) ``` # Quality bands 1, 2 ## Create list of words and their frequencies in the corrected set ``` words_corrected = [] for item in w2v_em_corr_qual_1_2.wv.vocab: words_corrected.append([item, int(w2v_em_corr_qual_1_2.wv.vocab[item].count)]) pd_words = pd.DataFrame(words_corrected, columns=['vocab', 'count']) pd_words = pd_words.sort_values(by=['count'], ascending=False) print("size: {}".format(len(pd_words))) pd_words.head() pd2search = pd_words[0:5000] pd2search neigh_jaccard_bands_1_2 = [] for topn in [1, 2, 5, 10, 50, 100, 500, 1000, 5000, 10000, 50000]: print("topn: {}".format(topn)) t1 = time.time() pd2search = pd_words[0:1000] pd2search['w2v_em_corr_qual_1_2'] = pd2search.apply(found_neighbors, args=[w2v_em_corr_qual_1_2, 'vocab', topn], axis=1) print("corr: {}".format(time.time() - t1)) pd2search['w2v_em_ocr_qual_1_2'] = pd2search.apply(found_neighbors, args=[w2v_em_ocr_qual_1_2, 'vocab', topn], axis=1) pd2search['jaccard_qual_1_2'] = \ pd2search.apply(jaccard_similarity_df, args=['w2v_em_corr_qual_1_2', "w2v_em_ocr_qual_1_2", True], axis=1) neigh_jaccard_bands_1_2.append( [topn, pd2search['jaccard_qual_1_2'].mean(), pd2search['jaccard_qual_1_2'].std()]) print("total: {}".format(time.time() - t1)) neigh_jaccard_bands_1_2 = np.array(neigh_jaccard_bands_1_2) np.save("neigh_jaccard_bands_1_2.npy", neigh_jaccard_bands_1_2) plt.figure(figsize=(10, 5)) plt.plot(neigh_jaccard_bands_1_2[:, 0], neigh_jaccard_bands_1_2[:, 1], 'k-o', alpha=1.0, lw=4, label='Quality bands=1,2') plt.plot(neigh_jaccard_bands_3_4[:, 0], neigh_jaccard_bands_3_4[:, 1], 'r-o', alpha=1.0, lw=4, label='Quality bands=3,4') plt.grid() plt.xticks(size=20) plt.yticks(size=20) plt.xlabel("#neighbours", size=24) plt.ylabel("Jaccard similarity", size=24) plt.xscale("log") plt.xlim(1.0, 100000) plt.ylim(0.05, 1.0) plt.legend(prop={'size': 20}) plt.show() #plt.xlim(0, 20000) ```
github_jupyter
``` %matplotlib inline import os import sys import glob import pprint import numpy as np import scipy as sp import pandas as pd import scipy.stats as sps import statsmodels.api as sm import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.mlab as mlab import matplotlib.ticker as ticker import matplotlib.gridspec as gridspec import radical.utils as ru import radical.pilot as rp import radical.analytics as ra from IPython.display import display pd.set_option('expand_frame_repr', False) # Global configurations # --------------------- # Use LaTeX and its body font for the diagrams' text. mpl.rcParams['text.usetex'] = True mpl.rcParams['font.family'] = 'serif' mpl.rcParams['font.serif'] = ['Nimbus Roman Becker No9L'] # Use thinner lines for axes to avoid distractions. mpl.rcParams['axes.linewidth'] = 0.75 mpl.rcParams['xtick.major.width'] = 0.75 mpl.rcParams['xtick.minor.width'] = 0.75 mpl.rcParams['ytick.major.width'] = 0.75 mpl.rcParams['ytick.minor.width'] = 0.75 # Do not use a box for the legend to avoid distractions. #mpl.rcParams['legend.frameon'] = False # Helpers # ------- # Use coordinated colors. These are the "Tableau 20" colors as # RGB. Each pair is strong/light. For a theory of color tableau20 = [(31 , 119, 180), (174, 199, 232), # blue [ 0,1 ] (255, 127, 14 ), (255, 187, 120), # orange [ 2,3 ] (44 , 160, 44 ), (152, 223, 138), # green [ 4,5 ] (214, 39 , 40 ), (255, 152, 150), # red [ 6,7 ] (148, 103, 189), (197, 176, 213), # purple [ 8,9 ] (140, 86 , 75 ), (196, 156, 148), # brown [10,11] (227, 119, 194), (247, 182, 210), # pink [12,13] (127, 127, 127), (199, 199, 199), # gray [14,15] (188, 189, 34 ), (219, 219, 141), # yellow [16,17] (23 , 190, 207), (158, 218, 229)] # cyan [18,19] # Scale the RGB values to the [0, 1] range, which is the format # matplotlib accepts. for i in range(len(tableau20)): r, g, b = tableau20[i] tableau20[i] = (r / 255., g / 255., b / 255.) # Return a single plot without right and top axes def fig_setup(): fig = plt.figure(figsize=(13,7)) ax = fig.add_subplot(111) ax.spines["top"].set_visible(False) ax.spines["right"].set_visible(False) ax.get_xaxis().tick_bottom() ax.get_yaxis().tick_left() return fig, ax def load_data(rdir): sessions = {} experiments = {} start = rdir.rfind(os.sep)+1 for path, dirs, files in os.walk(rdir): folders = path[start:].split(os.sep) if len(path[start:].split(os.sep)) == 2: sid = os.path.basename(glob.glob('%s/*.json' % path)[0])[:-5] if sid not in sessions.keys(): sessions[sid] = {} sessions[sid] = ra.Session(sid, 'radical.pilot', src=path) experiments[sid] = folders[0] return sessions, experiments # Load experiments' dataset into ra.session objects # stored in a DataFrame. rdir = '/Users/mturilli/Projects/RADICAL/github/experiments/AIMES-Swift/viveks_workflow/analysis/sessions/data/' sessions, experiments = load_data(rdir) sessions = pd.DataFrame({'session': sessions, 'experiment': experiments}) for sid in sessions.index: sessions.ix[sid, 'TTC'] = sessions.ix[sid, 'session'].ttc for sid in sessions.index: sessions.ix[sid, 'nunit'] = len(sessions.ix[sid, 'session'].filter(etype='unit', inplace=False).get()) sessions # Model of TOTAL pilot durations. # ttpdm = {'TT_PILOT_PMGR_SCHEDULING': ['NEW' , 'PMGR_LAUNCHING_PENDING'], # 'TT_PILOT_PMGR_QUEUING' : ['PMGR_LAUNCHING_PENDING', 'PMGR_LAUNCHING'], # 'TT_PILOT_LRMS_SUBMITTING': ['PMGR_LAUNCHING' , 'PMGR_ACTIVE_PENDING'], # 'TT_PILOT_LRMS_QUEUING' : ['PMGR_ACTIVE_PENDING' , 'PMGR_ACTIVE'], # 'TT_PILOT_LRMS_RUNNING' : ['PMGR_ACTIVE' , ['DONE', # 'CANCELED', # 'FAILED']]} ttpdm = {'TT_PILOT_LRMS_QUEUING' : [rp.PMGR_ACTIVE_PENDING , rp.PMGR_ACTIVE]} # Add total pilot durations to sessions' DF. for sid in sessions.index: s = sessions.ix[sid, 'session'].filter(etype='pilot', inplace=False) for d in ttpdm.keys(): sessions.ix[sid, d] = s.duration(ttpdm[d]) # Model of pilot durations. pdm = {#'PMGR_SCHEDULING': [rp.NEW , rp.PMGR_LAUNCHING_PENDING], #'PMGR_QUEUING' : [rp.PMGR_LAUNCHING_PENDING, rp.PMGR_LAUNCHING], #'LRMS_SUBMITTING': [rp.PMGR_LAUNCHING , rp.PMGR_ACTIVE_PENDING], 'LRMS_QUEUING' : [rp.PMGR_ACTIVE_PENDING , rp.PMGR_ACTIVE]}#, #'LRMS_RUNNING' : [rp.PMGR_ACTIVE , [rp.DONE, #rp.CANCELED, #rp.FAILED]]} # DataFrame structure for pilot durations. # pds = { 'pid': [], # 'sid': [], # 'experiment' : [], # 'PMGR_SCHEDULING': [], # 'PMGR_QUEUING' : [], # 'LRMS_SUBMITTING': [], # 'LRMS_QUEUING' : [], # 'LRMS_RUNNING' : []} pds = {'pid': [], 'sid': [], 'experiment': [], 'LRMS_QUEUING': []} # Calculate the duration for each state of each # pilot of each run and Populate the DataFrame # structure. for sid in sessions.index: s = sessions.ix[sid, 'session'].filter(etype='pilot', inplace=False) for p in s.list('uid'): sf = s.filter(uid=p, inplace=False) pds['pid'].append(p) pds['sid'].append(sid) pds['experiment'].append(sessions.ix[sid, 'experiment']) for d in pdm.keys(): if (not sf.timestamps(state=pdm[d][0]) or not sf.timestamps(state=pdm[d][1])): pds[d].append(None) continue pds[d].append(sf.duration(pdm[d])) # Populate the DataFrame. pilots = pd.DataFrame(pds) # Model of unit durations. # udm = {'TT_UNIT_UMGR_SCHEDULING' : ['NEW' , 'UMGR_SCHEDULING_PENDING'], #'TT_UNIT_UMGR_BINDING' : ['UMGR_SCHEDULING_PENDING' , 'UMGR_SCHEDULING'], #'TT_IF_UMGR_SCHEDULING' : ['UMGR_SCHEDULING' , 'UMGR_STAGING_INPUT_PENDING'], #'TT_IF_UMGR_QUEING' : ['UMGR_STAGING_INPUT_PENDING' , 'UMGR_STAGING_INPUT'], #'TT_IF_AGENT_SCHEDULING' : ['UMGR_STAGING_INPUT' , 'AGENT_STAGING_INPUT_PENDING'], #'TT_IF_AGENT_QUEUING' : ['AGENT_STAGING_INPUT_PENDING' , 'AGENT_STAGING_INPUT'], #'TT_IF_AGENT_TRANSFERRING' : ['AGENT_STAGING_INPUT' , 'AGENT_SCHEDULING_PENDING'], #'TT_UNIT_AGENT_QUEUING' : ['AGENT_SCHEDULING_PENDING' , 'AGENT_SCHEDULING'], #'TT_UNIT_AGENT_SCHEDULING' : ['AGENT_SCHEDULING' , 'AGENT_EXECUTING_PENDING'], #'TT_UNIT_AGENT_QUEUING_EXEC': ['AGENT_EXECUTING_PENDING' , 'AGENT_EXECUTING'], #'TT_UNIT_AGENT_EXECUTING' : ['AGENT_EXECUTING' , 'AGENT_STAGING_OUTPUT_PENDING']} #'TT_OF_AGENT_QUEUING' : ['AGENT_STAGING_OUTPUT_PENDING', 'AGENT_STAGING_OUTPUT'], #'TT_OF_UMGR_SCHEDULING' : ['AGENT_STAGING_OUTPUT' , 'UMGR_STAGING_OUTPUT_PENDING'], #'TT_OF_UMGR_QUEUING' : ['UMGR_STAGING_OUTPUT_PENDING' , 'UMGR_STAGING_OUTPUT'], #'TT_OF_UMGR_TRANSFERRING' : ['UMGR_STAGING_OUTPUT' , 'DONE']} udm = {'TT_UNIT_AGENT_EXECUTING' : [rp.AGENT_EXECUTING, rp.AGENT_STAGING_OUTPUT_PENDING]} # Calculate total unit durations for each session. for sid in sessions.index: s = sessions.ix[sid, 'session'].filter(etype='unit', inplace=False) # for unit in s.get(etype='unit'): # print # print s._sid # print unit.uid # for state in unit.states: # print "%-20s : %7.2f" % (state, unit.states[state]['time']) for d in udm.keys(): sessions.ix[sid, d] = s.duration(udm[d]) sessions fig, ax = fig_setup() title='XSEDE HPC Clusters: Comet, Gordon, Stampede, SuperMic\nKernel Density Estimation of Pilot Queuing Time (Tq)' tq_all = pilots['LRMS_QUEUING'].dropna().reset_index(drop=True) ptqs = pd.DataFrame({'all': tq_all}) ptqs.plot.density(ax=ax, color=tableau20[0], title=title) plt.axvline(pilots['LRMS_QUEUING'].min(), ymax=0.9, color='black', linestyle='dashed', linewidth=0.4) plt.axvline(pilots['LRMS_QUEUING'].mean(), ymax=0.9, color='red', linestyle='dashed', linewidth=0.4) plt.axvline(pilots['LRMS_QUEUING'].max(), ymax=0.9, color='green', linestyle='dashed', linewidth=0.4) ax.set_xlabel('Time (s)') ax.legend(labels=['Pilot Queuing Time (Tq)', 'Min', 'Mean', 'Max']) plt.savefig('xsede_tq_all_density.pdf', dpi=600, bbox_inches='tight') #display(pilots) # Model of unit durations. # udm = {'UNIT_UMGR_SCHEDULING' : ['NEW' , 'UMGR_SCHEDULING_PENDING'], # 'UNIT_UMGR_BINDING' : ['UMGR_SCHEDULING_PENDING' , 'UMGR_SCHEDULING'], # 'IF_UMGR_SCHEDULING' : ['UMGR_SCHEDULING' , 'UMGR_STAGING_INPUT_PENDING'], # 'IF_UMGR_QUEING' : ['UMGR_STAGING_INPUT_PENDING' , 'UMGR_STAGING_INPUT'], # 'IF_AGENT_SCHEDULING' : ['UMGR_STAGING_INPUT' , 'AGENT_STAGING_INPUT_PENDING'], # 'IF_AGENT_QUEUING' : ['AGENT_STAGING_INPUT_PENDING' , 'AGENT_STAGING_INPUT'], # 'IF_AGENT_TRANSFERRING' : ['AGENT_STAGING_INPUT' , 'AGENT_SCHEDULING_PENDING'], # 'UNIT_AGENT_QUEUING' : ['AGENT_SCHEDULING_PENDING' , 'AGENT_SCHEDULING'], # 'UNIT_AGENT_SCHEDULING' : ['AGENT_SCHEDULING' , 'AGENT_EXECUTING_PENDING'], # 'UNIT_AGENT_QUEUING_EXEC': ['AGENT_EXECUTING_PENDING' , 'AGENT_EXECUTING'], # 'UNIT_AGENT_EXECUTING' : ['AGENT_EXECUTING' , 'AGENT_STAGING_OUTPUT_PENDING'], # 'OF_AGENT_QUEUING' : ['AGENT_STAGING_OUTPUT_PENDING', 'AGENT_STAGING_OUTPUT'], # 'OF_UMGR_SCHEDULING' : ['AGENT_STAGING_OUTPUT' , 'UMGR_STAGING_OUTPUT_PENDING'], # 'OF_UMGR_QUEUING' : ['UMGR_STAGING_OUTPUT_PENDING' , 'UMGR_STAGING_OUTPUT'], # 'OF_UMGR_TRANSFERRING' : ['UMGR_STAGING_OUTPUT' , 'DONE']} udm = {'UNIT_AGENT_EXECUTING' : [rp.AGENT_EXECUTING, rp.AGENT_STAGING_OUTPUT_PENDING]} # DataFrame structure for pilot durations. # uds = { 'pid': [], # 'sid': [], # 'experiment' : [], # 'UNIT_UMGR_SCHEDULING' : [], # 'UNIT_UMGR_BINDING' : [], # 'IF_UMGR_SCHEDULING' : [], # 'IF_UMGR_QUEING' : [], # 'IF_AGENT_SCHEDULING' : [], # 'IF_AGENT_QUEUING' : [], # 'IF_AGENT_TRANSFERRING' : [], # 'UNIT_AGENT_QUEUING' : [], # 'UNIT_AGENT_SCHEDULING' : [], # 'UNIT_AGENT_QUEUING_EXEC': [], # 'UNIT_AGENT_EXECUTING' : [], # 'OF_AGENT_QUEUING' : [], # 'OF_UMGR_SCHEDULING' : [], # 'OF_UMGR_QUEUING' : [], # 'OF_UMGR_TRANSFERRING' : []} uds = { 'uid': [], 'sid': [], 'experiment': [], 'UNIT_AGENT_EXECUTING': []} # Calculate the duration for each state of each # pilot of each run and Populate the DataFrame # structure. for sid in sessions[['session', 'experiment']].index: print sid # if sessions.ix[sid, 'experiment'] in ['exp1','exp2']: # continue # print '%s - %s' % (sessions.ix[sid, 'experiment'], sid) s = sessions.ix[sid, 'session'].filter(etype='unit', inplace=False) for u in s.list('uid'): # print "\t%s" % u sf = s.filter(uid=u, inplace=False) uds['uid'].append(u) uds['sid'].append(sid) uds['experiment'].append(sessions.ix[sid, 'experiment']) for d in udm.keys(): # print '\t\t%s' % udm[d] # print '\t\t[%s, %s]' % (sf.timestamps(state=udm[d][0]), sf.timestamps(state=udm[d][1])) if (not sf.timestamps(state=udm[d][0]) or not sf.timestamps(state=udm[d][1])): pds[d].append(None) # print '\t\t%s: %s' % (d, 'None') continue # print sf.timestamps(state=udm[d][0]) # print sf.timestamps(state=udm[d][1]) # print '\t\t%s: %s' % (d, sf.duration(udm[d])) uds[d].append(sf.duration(udm[d])) # Populate the DataFrame. We have empty lists units = pd.DataFrame(dict([(k,pd.Series(v)) for k,v in uds.iteritems()])) # get all session IDs and profile paths dirs = glob.glob('/Users/mturilli/Projects/RADICAL/github/experiments/AIMES-Swift/viveks_workflow/analysis/sessions/data/exp1/rp.session.*/') sids = dict() for d in dirs: while d.endswith('/'): d = d[:-1] sids[os.path.basename(d)] = d # tx distribution is what we are interested in tx = list() tx_states = [rp.AGENT_EXECUTING, rp.AGENT_STAGING_OUTPUT_PENDING] # fill tx last_states = dict() for sid in sids: session = ra.Session(sid, 'radical.pilot', src=sids[sid]) units = session.filter(etype='unit', inplace=True) n = len(units.get()) for unit in units.get(): # we only want units from stage 2 if 'stage_2' not in unit.description['executable']: continue # get tx, and add it to the set of data points to plot. # ignore mismatching units. # also find out what the last state of the unit was (sorted by time) try: t = unit.duration(tx_states) if t: tx.append({'t' : t}) ls = sorted(unit.states.keys(), key=lambda x: (unit.states[x]['time']))[-1] except: pass # update counter for the last states if ls not in last_states: last_states[ls] = 0 last_states[ls] += 1 df = pd.DataFrame(tx) units = pd.read_csv('/Users/mturilli/Projects/RADICAL/github/radical.analytics/use_cases/rp_on_osg/units_tx.csv') # display(df['t'].tolist()) # display(units['UNIT_AGENT_EXECUTING'].tolist()) tx_xsede_osg = pd.DataFrame({'XSEDE': df['t'], 'OSG': units['UNIT_AGENT_EXECUTING']}) display(tx_xsede_osg) mpl.rcParams['text.usetex'] = True mpl.rcParams['font.family'] = 'sans-serif' mpl.rcParams['font.serif'] = ['Helvetica'] mpl.rcParams['legend.frameon'] = True mpl.rcParams['patch.linewidth'] = 0.75 SIZE = 20 plt.rc('font', size=SIZE) # controls default text sizes plt.rc('axes', titlesize=SIZE) # fontsize of the axes title plt.rc('axes', labelsize=SIZE) # fontsize of the x any y labels plt.rc('xtick', labelsize=SIZE) # fontsize of the tick labels plt.rc('ytick', labelsize=SIZE) # fontsize of the tick labels plt.rc('legend', fontsize=13) # legend fontsize plt.rc('figure', titlesize=SIZE) # # size of the figure title fig = plt.figure(figsize=(10,8)) ax = fig.add_subplot(111) mtitle ='OSG XSEDE Virtual Cluster and XSEDE HPC Clusters' stitle ='Comparison of Kernel Density Estimation of Task Execution Time ($T_x$)' title = '%s\n%s' % (mtitle, stitle) fig.suptitle(title, fontsize=19) # tx_all = units['UNIT_AGENT_EXECUTING'].dropna().reset_index(drop=True) # utxs = pd.DataFrame({'all': tx_all}) print tx_xsede_osg.describe() tx_xsede_osg.plot.density(ax=ax, color=[tableau20[2],tableau20[0]], linewidth=2)#, title=title) # plt.axvline(df['t'].min(), ymax=0.9, color='black', linestyle='dashed', linewidth=0.4) # plt.axvline(df['t'].mean(), ymax=0.9, color='red', linestyle='dashed', linewidth=0.4) # plt.axvline(df['t'].max(), ymax=0.9, color='green', linestyle='dashed', linewidth=0.4) ax.set_xlim((0, 1000)) ax.set_xlabel('$T_x$ (s)') ax.legend() plt.savefig('xsede_osg_tx_all_frequency.pdf', dpi=600, bbox_inches='tight') tx_xsede_osg.to_csv('osg_xsede_tx.csv') ```
github_jupyter
# HYGIENE PREDICTION OF FOOD CHAIN ESTABLISHMENTS IN FRANCE BASED ON DATA OF ALIM'CONFIANCE : COMPARISON OF MACHINE LEARNING MODEL WITH CLASSIFICATION PROBLEM <h3>Machine learning project<h3> <br> 1. Abstract 2. Introduction 3. Machine learning model computational 4. Result and Discussion 5. Conclusion<br> Machine learning model,classification problem:<br> * K Nearest Neigbor classifier * Gradient Boosting classifier * Random Forest classifier * Neural NetWork <br> With cross validation, - we will apply our machine learning - we will apply the hyperparameter for each model to search the best parameter value to optimize our model # ABSTRACT The precise health hygiene prediction of food chain establishments in France has many applications for hygiene monitoring in the various establishments of the food chain as well as the planning of food health controls in these establishments. Descriptive statistical methods have been used to provide information on the level of hygiene of these establishments. This study aims to predict the health hygiene of food chain establishments using data from Alim'Confiance by machine learning models. Machine learning models by the optimization of hyperparameters with cross-validation have been induced to predict the health hygiene of the establishments of the food chain in France. We then compared 4 machine learning models to find out the most robust model in terms of prediction using the models such as K Nearest Neighbord,Gradient Boosting classified, Random forest classified and Neural Network.It was concluded that the prediction performance of the Random forest Classifier was significantly robust with an 85% score in automatic and hyperparametre. but with the hyperparameter, we noticed in the Gradient boosting classifier model that if we increase the number of classification tree estimates by controlling the learning process, we will have a better classification than the random forest. # INTRODUCTION Like the saying goes, “A healthy people, is a healthy nation.” For people to stay healthy, it is important that some measures of hygiene are considered when handling food and drinks. Food hygiene can therefore be defined as the handling, preparing, and storing food or drinks in a way that best minimizes the risk of consumers becoming sick from the food-borne disease. The overall purpose of food hygiene is to prepare and provide safe food and consequently contribute to a healthy and productive society. The Federal Ministry of Agriculture and L’alimentation, France took the initiative towards boosting the confidence of the people regarding the level of sanitary measures maintained in various food chain (restaurants, canteens, and slaughterhouses, etc..) in France. The publication of the result of health checks in the food sector is a legitimate expectation of citizens which contributes to improving consumer confidence. Provided by the law of the future for agriculture, food, and forestry, of October 13, 2014, this measure is part of an evolution towards greater transparency of state action. Alim’confiance, the dataset on which we worked on comes from a certified public service. On its application as well as its website www.alim-confiance.gouv.fr , consumers can have access to the results of health checks carried out in all establishments in the food chain. The result allows you to know the overall level of hygiene of the food establishment and gives you an idea of compliance with hygiene standards: cleanliness of premises and equipment, hygiene of staff and handling, respect for the supply chain. Various Machine Learning ML have been applied on sanitary, health, biological data and more. Machine learning procedures will be carried out on Alim’Confiance data to classify the various food chain according to their level of compliance into Satisfactory, Very Satisfactory, To improve, and To be Corrected Urgently. # PROCEDURE First we preprocessed the data, second we split de data on train and test set with 70% of the train set and 30% of the test set , and next was the classification according to the results generated from the four methods of classification used (K Nearest Classifier, Gradient Boosting Classifier, Random Forest Classifier, and Neural Network). With Cross validation, we splitted the data into 5 train sets, test sets and fit the models to predict our target and evaluate the score of each models then we will applied the hyperparameter optimization on the 4 models of classification to get the best value of parameter to optimize our models. Regarding data visualization, we did Descriptive Statistics. ``` import pandas as pd from sklearn.model_selection import train_test_split import pandas as pd from sklearn import model_selection import sklearn as read_csv import numpy as np from sklearn.metrics import classification_report,accuracy_score,confusion_matrix from matplotlib import pyplot as plt from sklearn import svm from sklearn.neighbors import KNeighborsClassifier from sklearn.svm import SVC from sklearn.metrics import roc_curve, auc from sklearn.model_selection import train_test_split from sklearn.preprocessing import label_binarize from sklearn.multiclass import OneVsRestClassifier from scipy import interp from sklearn.preprocessing import LabelEncoder from sklearn import preprocessing from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler from sklearn.neural_network import MLPClassifier import numpy as np from random import shuffle from operator import itemgetter from sklearn import preprocessing from gplearn.genetic import SymbolicRegressor from sklearn.utils.random import check_random_state import numpy as np from sklearn.model_selection import KFold from sklearn.model_selection import cross_val_score from sklearn.ensemble import RandomForestClassifier from sklearn.ensemble import BaggingClassifier from sklearn.model_selection import cross_val_score, train_test_split from mlxtend.plotting import plot_learning_curves from mlxtend.plotting import plot_decision_regions import itertools from sklearn.tree import DecisionTreeClassifier from sklearn.model_selection import train_test_split, GridSearchCV import numpy as np import xgboost as xgb import seaborn as sns import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec from mlxtend.classifier import StackingClassifier from sklearn.linear_model import LogisticRegression from sklearn.model_selection import GridSearchCV from matplotlib import pyplot #We choose 5 cross validation for our machine learning model n_folds = KFold(n_splits =5,shuffle= False ) from sklearn.model_selection import RandomizedSearchCV from sklearn.metrics import jaccard_score import xgboost as xgb from sklearn.metrics import accuracy_score from numpy import mean from numpy import std from sklearn.model_selection import RepeatedStratifiedKFold # evaluate a given model using cross-validation # import packages for hyperparameters tuning from hyperopt import STATUS_OK, Trials, fmin, hp, tpe from itertools import cycle from sklearn.tree import DecisionTreeClassifier from sklearn import svm, datasets from sklearn.metrics import roc_curve, auc from sklearn.model_selection import train_test_split from sklearn.preprocessing import label_binarize from sklearn.multiclass import OneVsRestClassifier from scipy import interp ``` # CLASSIFICATION DATA ``` df=pd.read_csv("export_alimconfiance.csv", error_bad_lines=False,sep=';') df.head() df.dtypes df.shape df.columns ``` ## health control of food establishment chains [Link of data](https://data.opendatasoft.com/explore/dataset/export_alimconfiance%40dgal/table/?disjunctive.app_libelle_activite_etablissement&disjunctive.filtre&disjunctive.ods_type_activite) 3.Information about our target(multiclass classification problem) Official food safety checks released on March 1, 2017. Mentions of the 4 levels of hygiene: Very satisfactory level of hygiene: establishments that do not comply, or have only minor non-compliances. Satisfactory level of hygiene: establishments with non-compliances that do not justify the adoption of administrative police measures but to which the administrative authority sends a letter of reminder of the regulations in order to improve practices. Hygiene level to be improved: establishments whose operator has been ordered to take corrective action within a time frame set by the administrative authority and which leads to a new control of the state services to verify the implementation of these corrective measures. Hygiene level to be urgently corrected: establishments with non-compliances that could endanger the health of the consumer and for which the administrative authority orders administrative closure, withdrawal, or suspension of health accreditation. 5. Number of Instances: 30799 6. Number of Attributes: 12 7. Attribute information: 1. APP_Libelle_etablissement- wording of the establishment activities 2. Synthese_eval_sanit- health evaluation synthese (our target) 3. filtre 4. ods_type_activite - type of activities 5. SIRET- Establishment SIRET 6. Code_postal - establishment ZIP CODE 7. Libelle_commune- wording of common establishment 8. Numero_inspection - Inspection number 9. Date_inspection - Inspection date 10. Agrement 11. geores 8. Missing Attribute Values: 31444 # Multiclass: ``` c=df['Synthese_eval_sanit'].value_counts() #We can see the imbanlance class on our target c df['Synthese_eval_sanit'].value_counts(normalize=False).plot(kind = 'bar', title = "Evaluation synthesis of hygiene food") ``` # Check NaN on the data: ``` df.isnull().sum() ``` # Data cleaning and processing for machine learning model # Data cleaning: ``` # determine categorical and numerical features numerical_ix = df.select_dtypes(include=['int64', 'float64']).columns categorical_ix = df.select_dtypes(include=['object', 'bool']).columns print('numerical variable:') print( numerical_ix ) print('categorical variable') print(categorical_ix ) df.Agrement.describe() df['Agrement'].fillna('72080002',inplace=True) df.geores.describe() df['geores'].fillna('42.565838,8.756981',inplace=True) df.ods_type_activite.describe() df['ods_type_activite'].fillna('Autres',inplace=True) df.filtre.describe() df['filtre'].fillna('Restaurant',inplace=True) df.isnull().sum() ``` # Data preprocessing: # Data encoding for categorical variables: ``` encoded=df[['APP_Libelle_etablissement', 'SIRET', 'Code_postal', 'Libelle_commune', 'Numero_inspection', 'Date_inspection', 'APP_Libelle_activite_etablissement', 'Synthese_eval_sanit', 'Agrement', 'geores', 'filtre', 'ods_type_activite']].apply(LabelEncoder().fit_transform) # Adding both the dataframes encoded and remaining (without encoding) data =pd.concat([encoded], axis=1) data.head() c2=data['Synthese_eval_sanit'].value_counts() #We can see the imbanlance class on our target with numerical value after use the encoding algorithm. #To perform our model we neeed to use the imbalanced learning before to apply Machine learning model for #Good classification with imblearn package. c2 data['Synthese_eval_sanit'].value_counts(normalize=False).plot(kind = 'bar', title = "Evaluation synthesis of hygiene food") data.columns X=data[['APP_Libelle_etablissement', 'SIRET', 'Code_postal', 'Libelle_commune', 'Numero_inspection', 'Date_inspection', 'APP_Libelle_activite_etablissement', 'Agrement', 'geores', 'filtre', 'ods_type_activite']] y=data['Synthese_eval_sanit'] ``` # IMBALANCED LEARNING ``` from imblearn.over_sampling import RandomOverSampler ros = RandomOverSampler() X_ros, y_ros = ros.fit_sample(X, y) print(X_ros.shape,y_ros.shape) y_ros.value_counts(normalize=False).plot(kind = 'bar', title = "Evaluation synthesis of hygiene food with imbalanced learning") ``` # Standard scaling: ``` #Split data in training and testing sample with 70% for training and 30% for testing X_train, X_test, y_train, y_test = train_test_split(X_ros, y_ros, test_size = 0.3, random_state = 42) print(X_train.shape,X_test.shape,y_train.shape,y_test.shape) #Nous pouvons maintenant standardiser les variables, #c'est-à-dire les centrer (ramener leur moyenne à 0) #et les réduire (ramener leur écart-type à 1), #afin qu'elles se placent toutes à peu près sur la même échelle # standardiser les données std_scale = preprocessing.StandardScaler().fit(X_train) x_train_std = std_scale.transform(X_train) x_test_std = std_scale.transform(X_test) ``` # MACHINE LEARNING MODEL # K Nearest Neighbors(KNN) MODEL ``` knn = KNeighborsClassifier() knn.fit(x_train_std,y_train) y_pred = knn.predict(x_test_std) knn.score(x_train_std,y_train) knn.score(x_test_std,y_test) ``` # KNN CROSS VALIDATION ``` accuracy_train=cross_val_score(knn,x_train_std,y_train,cv=n_folds,scoring ='accuracy') accuracy_test=cross_val_score(knn,x_test_std,y_test,cv=n_folds,scoring ='accuracy') print(accuracy_train.mean()) print(accuracy_test.mean()) #CONFRONTATION ENTRE Y OBSERVEE SUR L ECHANTILLON TEST ET LA PREDICTION #PERMET DE VERIFIER SUR NOTRE CLASSIFICATION EST BONNE OU PAS ICI SCORE = VAL(matrixCONFUSION) DONC OK confusion_mtx1=confusion_matrix(y_test,y_pred) # plot the confusion matrix f,ax = plt.subplots(figsize=(6, 5)) sns.heatmap(confusion_mtx1, annot=True, linewidths=0.01,cmap="Greens",linecolor="gray", fmt= '.1f',ax=ax) plt.xlabel("Predicted Label") plt.ylabel("True Label") plt.title("Confusion Matrix of K Nearest Neighbors(KNN) ") plt.show() from sklearn.metrics import classification_report,accuracy_score,confusion_matrix print('Results on the test set with K Nearest Neighbors:') print(classification_report(y_test, y_pred)) ``` # HYPERPARAMETER OF KNN MODEL ``` #Performing cross validation neighbors = [] cv_scores = [] from sklearn.model_selection import cross_val_score #perform 5 fold cross validation for k in range(1,51,2): neighbors.append(k) knn = KNeighborsClassifier(n_neighbors = k) scores = cross_val_score(knn,x_train_std,y_train,cv=5, scoring = 'accuracy') cv_scores.append(scores.mean()) #Misclassification error versus k MSE = [1-x for x in cv_scores] #determining the best k optimal_k = neighbors[MSE.index(min(MSE))] print('The optimal number of neighbors is %d ' %optimal_k) #plot misclassification error versus k plt.figure(figsize = (10,6)) plt.plot(neighbors, MSE) plt.xlabel('Number of neighbors') plt.ylabel('Misclassification Error') plt.show() knnhyp = KNeighborsClassifier(n_neighbors = 1) knnhyp.fit(x_train_std,y_train) scores =knnhyp.score(x_train_std,y_train) print('K Neightbors classifier Optimization train score: ' + str(scores)) scores = knnhyp.score(x_test_std, y_test) print('K Neightbors classifierclassifier Optimization test score: ' + str(scores)) ``` # KNN CROSS VALIDATION WITH HYPERPARAMETER VALUE ``` accuracy_train=cross_val_score(knnhyp,x_train_std,y_train,cv=n_folds,scoring ='accuracy') accuracy_test=cross_val_score(knnhyp,x_test_std,y_test,cv=n_folds,scoring ='accuracy') print(accuracy_train.mean()) print(accuracy_test.mean()) y_predknn = knnhyp.predict(x_test_std) #CONFRONTATION ENTRE Y OBSERVEE SUR L ECHANTILLON TEST ET LA PREDICTION #PERMET DE VERIFIER SUR NOTRE CLASSIFICATION EST BONNE OU PAS ICI SCORE = VAL(matrixCONFUSION) DONC OK confusion_mtx1HYPOPT=confusion_matrix(y_test,y_predknn) # plot the confusion matrix f,ax = plt.subplots(figsize=(6, 5)) sns.heatmap(confusion_mtx1HYPOPT, annot=True, linewidths=0.01,cmap="Greens",linecolor="gray", fmt= '.1f',ax=ax) plt.xlabel("Predicted Label") plt.ylabel("True Label") plt.title("Confusion Matrix of K Nearest Neighbors(KNN) ") plt.show() from sklearn.metrics import classification_report,accuracy_score,confusion_matrix print('Results on the test set with hyperparameter with K nearest Neighbors:') print(classification_report(y_test, y_predknn)) ``` # GRADIENT BOOSTING CLASSIFIER MODEL ``` from sklearn.ensemble import GradientBoostingClassifier modelgb = GradientBoostingClassifier() modelgb.fit(x_train_std,y_train) scores = modelgb.score(x_train_std,y_train) print('Gradient boosting classifier train score: ' + str(scores)) scores = modelgb.score(x_test_std, y_test) print('Gradient boosting classifier test score: ' + str(scores)) ``` # Gradient boosting cross validation: ``` accuracy_train=cross_val_score(modelgb,x_train_std,y_train,cv=n_folds,scoring ='accuracy') accuracy_test=cross_val_score(modelgb,x_test_std,y_test,cv=n_folds,scoring ='accuracy') print(accuracy_train.mean()) print(accuracy_test.mean()) predictions = modelgb.predict(x_test_std) from sklearn.metrics import confusion_matrix confusion_mtx2=confusion_matrix(y_test,predictions) # plot the confusion matrix f,ax = plt.subplots(figsize=(6, 5)) sns.heatmap(confusion_mtx2, annot=True, linewidths=0.01,cmap="Greens",linecolor="gray", fmt= '.1f',ax=ax) plt.xlabel("Predicted Label") plt.ylabel("True Label") plt.title("Confusion Matrix Gradient Boosting Classifier") plt.show() from sklearn.metrics import classification_report,accuracy_score,confusion_matrix print('Results on the test set with gradient Boosting:') print(classification_report(y_test,predictions)) ``` # HYPERPARAMETER OF GRADIENT BOOSTING CLASSIFIER ``` # get a list of models to evaluate def get_models(): models = dict() # define number of trees to consider n_trees = [10, 50, 100, 500, 1000, 5000,10000] for n in n_trees: models[str(n)] = GradientBoostingClassifier(n_estimators=n) return models def evaluate_model(model, X, y): # define the evaluation procedure cv = RepeatedStratifiedKFold(n_splits=5, n_repeats=3, random_state=1) # evaluate the model and collect the results scores = cross_val_score(model, X, y, scoring='accuracy', cv=cv, n_jobs=-1) return scores # get the models to evaluate models = get_models() # evaluate the models and store results results, names = list(), list() for name, model in models.items(): # evaluate the model scores = evaluate_model(model, x_test_std, y_test) # store the results results.append(scores) names.append(name) # summarize the performance along the way print('>%s %.3f (%.3f)' % (name, mean(scores), std(scores))) # plot model performance for comparison pyplot.boxplot(results, labels=names, showmeans=True) pyplot.show() modelgbhpop = GradientBoostingClassifier(n_estimators=10000) modelgbhpop.fit(x_train_std,y_train) scores = modelgbhpop.score(x_train_std,y_train) print('Gradient boosting classifier Optimization train score: ' + str(scores)) scores = modelgbhpop.score(x_test_std, y_test) print('Gradient boosting classifier Optimization test score: ' + str(scores)) ``` # GRADIENT BOOSTING CROSS VALIDATION WITH HYPERPARAMETER ``` accuracy_train=cross_val_score(modelgbhpop,x_train_std,y_train,cv=n_folds,scoring ='accuracy') accuracy_test=cross_val_score(modelgbhpop,x_test_std,y_test,cv=n_folds,scoring ='accuracy') print(accuracy_train.mean()) print(accuracy_test.mean()) y_predbosting = modelgbhpop.predict(x_test_std) from sklearn.metrics import confusion_matrix confusion_mtx2hypopt=confusion_matrix(y_test,y_predbosting) # plot the confusion matrix f,ax = plt.subplots(figsize=(6, 5)) sns.heatmap(confusion_mtx2hypopt, annot=True, linewidths=0.01,cmap="Greens",linecolor="gray", fmt= '.1f',ax=ax) plt.xlabel("Predicted Label") plt.ylabel("True Label") plt.title("Confusion Matrix Gradient Boosting Classifier with hyperparameter") plt.show() from sklearn.metrics import classification_report,accuracy_score,confusion_matrix print('Results on the test set with hyperparameter with Gradient Boosting:') print(classification_report(y_test, y_predbosting)) ``` # RANDOM FOREST CLASSIFIER ``` model = RandomForestClassifier(n_estimators=100) model.fit(x_train_std, y_train) acc = model.score(x_train_std, y_train) print('Random Forest train score: ' + str(acc)) scores = model.score(x_test_std, y_test) print('Random Forest test score: ' + str(scores)) ``` # Random Forest Cross Validation Score: ``` accuracy_train=cross_val_score(model,x_train_std,y_train,cv=n_folds,scoring ='accuracy') accuracy_test=cross_val_score(model,x_test_std,y_test,cv=n_folds,scoring ='accuracy') print(accuracy_train.mean()) print(accuracy_test.mean()) y_pred = model.predict(x_test_std) from sklearn.metrics import confusion_matrix confusion_mtx3=confusion_matrix(y_test,y_pred) # plot the confusion matrix f,ax = plt.subplots(figsize=(6, 5)) sns.heatmap(confusion_mtx3, annot=True, linewidths=0.01,cmap="Greens",linecolor="gray", fmt= '.1f',ax=ax) plt.xlabel("Predicted Label") plt.ylabel("True Label") plt.title("Confusion Matrix of Random Forest Classifier") plt.show() print('Results on the test set with Random Forest :') print(classification_report(y_test, y_pred)) ``` # HYPERPARAMETER WITH GRID SEARCH CV OF RANDOM FOREST CLASSIFIER ``` # TODO: Import 'GridSearchCV', 'make_scorer', and any other necessary libraries from sklearn.model_selection import GridSearchCV from sklearn.metrics import make_scorer, fbeta_score # TODO: Initialize the classifier rf = RandomForestClassifier() # TODO: Create the parameters list you wish to tune, using a dictionary if needed. # HINT: parameters = {'parameter_1': [value1, value2], 'parameter_2': [value1, value2]} parameters = { 'n_estimators': [50, 100, 200], 'min_samples_leaf': [1, 2, 4], 'min_samples_split': [2, 5, 10], } # TODO: Perform grid search on the classifier using 'scorer' as the scoring method using GridSearchCV() grid_obj = GridSearchCV(rf, parameters, cv=5) # TODO: Fit the grid search object to the training data and find the optimal parameters using fit() grid_fit = grid_obj.fit(x_train_std, y_train) # How does one get the model with the best score? # There is a function by which you can call the best model by asking for the best score amongst all the scores produced. # grid.best_score_ gives the best score obtained by the grid search. # grid.best_params_ gives print(grid_fit.best_score_) print(grid_fit.best_params_) print(grid_fit.best_estimator_) modelhyp = RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini', max_depth=None, max_features='auto', max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, min_samples_leaf=1, min_samples_split=2, min_weight_fraction_leaf=0.0, n_estimators=200, n_jobs=None, oob_score=False, random_state=None, verbose=0, warm_start=False) modelhyp.fit(x_train_std, y_train) acc = modelhyp.score(x_train_std, y_train) print('Random forest hyperparameter train score: ' + str(acc)) scores = modelhyp.score(x_test_std, y_test) print('Random forest hyperparameter train score: ' + str(scores)) ``` # RANDOM FOREST CROSS VALIDATION WITH HYPERPARAMETER ``` accuracy_train=cross_val_score(modelhyp,x_train_std,y_train,cv=n_folds,scoring ='accuracy') accuracy_test=cross_val_score(modelhyp,x_test_std,y_test,cv=n_folds,scoring ='accuracy') print(accuracy_train.mean()) print(accuracy_test.mean()) y_pred2 = modelhyp.predict(x_test_std) from sklearn.metrics import confusion_matrix confusion_mtx3hypopt=confusion_matrix(y_test,y_pred2) from sklearn.metrics import classification_report,accuracy_score,confusion_matrix print('Results on the test set with hyperparameter with Random Forest:') print(classification_report(y_test, y_pred2)) ``` # NEURAL NETWORK ``` nn = MLPClassifier() nn.fit(x_train_std,y_train) acc = nn.score(x_train_std, y_train) print('neural network train score: ' + str(acc)) scores = nn.score(x_test_std, y_test) print('neural network test score: ' + str(scores)) y_predNN = nn.predict(x_test_std) from sklearn.metrics import confusion_matrix confusion_mtx4=confusion_matrix(y_test,y_predNN) # plot the confusion matrix f,ax = plt.subplots(figsize=(8, 5)) sns.heatmap(confusion_mtx4, annot=True, linewidths=0.01,cmap="Greens",linecolor="gray", fmt= '.1f',ax=ax) plt.xlabel("Predicted Label") plt.ylabel("True Label") plt.title("Confusion Matrix of NEURAL NETWORK") plt.show() ``` # Neural Network Cross Validation score: ``` accuracy_train=cross_val_score(nn,x_train_std,y_train,cv=n_folds,scoring ='accuracy') accuracy_test=cross_val_score(nn,x_test_std,y_test,cv=n_folds,scoring ='accuracy') print(accuracy_train.mean()) print(accuracy_test.mean()) y_pred = nn.predict(x_test_std) from sklearn.metrics import classification_report,accuracy_score,confusion_matrix print('Results on the test set with Neural Network') print(classification_report(y_test, y_pred)) ``` # HYPERPARAMETER OF NEURAL NET WORK-Multi Layer Perceptron(MLP) ``` parameter_space = { 'hidden_layer_sizes': [(50,50,50), (50,100,50), (100,)], 'activation': ['tanh', 'relu'], 'solver': ['sgd', 'adam'], 'alpha': [0.0001, 0.05], 'learning_rate': ['constant','adaptive'], } clf = GridSearchCV(nn, parameter_space, n_jobs=-1, cv=5) clf.fit(x_train_std, y_train) # Best paramete set print('Best parameters found:\n', clf.best_params_) # All results means = clf.cv_results_['mean_test_score'] stds = clf.cv_results_['std_test_score'] for mean, std, params in zip(means, stds, clf.cv_results_['params']): print("%0.3f (+/-%0.03f) for %r" % (mean, std * 2, params)) print(clf.best_score_) acc = clf.score(x_train_std, y_train) print('Neural network hyperparameter train score: ' + str(acc)) scores = clf.score(x_test_std, y_test) print('Neural network hyperparameter test score: ' + str(scores)) ``` # NEURAL NETWORK CROSS VALIDATION SCORE WITH HYPERPARAMETER ``` accuracy_train=cross_val_score(clf,x_train_std,y_train,cv=n_folds,scoring ='accuracy') accuracy_test=cross_val_score(clf,x_test_std,y_test,cv=n_folds,scoring ='accuracy') print(accuracy_train.mean()) print(accuracy_test.mean()) y_predNNHYP = clf.predict(x_test_std) from sklearn.metrics import confusion_matrix confusion_mtx4=confusion_matrix(y_test,y_predNNHYP) # plot the confusion matrix f,ax = plt.subplots(figsize=(8, 5)) sns.heatmap(confusion_mtx4, annot=True, linewidths=0.01,cmap="Greens",linecolor="gray", fmt= '.1f',ax=ax) plt.xlabel("Predicted Label") plt.ylabel("True Label") plt.title("Confusion Matrix of NEURAL NETWORK") plt.show() y_pred = clf.predict(x_test_std) from sklearn.metrics import classification_report print('Results on the test set with hyperparameter with Neural Network:') print(classification_report(y_test, y_predNNHYP)) ``` # AUTOMATIC MACHINE LEARNING COMPARISON ``` # prepare models models = [] models.append(('K-Nearest Neighbor', KNeighborsClassifier())) models.append(('Gradient boosting Classifier', GradientBoostingClassifier())) models.append(('Random Forest Classifier', RandomForestClassifier(n_estimators=100))) models.append(('Neural Network', MLPClassifier())) # evaluate each model in turn results = [] names = [] scoring = 'accuracy' for name, model in models: kfold = KFold(n_splits=5) result = cross_val_score(model, x_train_std, y_train, cv=kfold, scoring=scoring) results.append(result) names.append(name) results_nump = np.array(results) msg = "%s: %f , %f" % (name, results_nump.mean(), results_nump.std()) #two statistics: mean and std.deviation print(msg) # boxplot algorithm comparison fig = pyplot.figure(figsize = (12,7)) fig.suptitle('Machine Learning classification algorithm comparison') ax = fig.add_subplot(111) pyplot.boxplot(results) ax.set_xticklabels(names) pyplot.show() ``` # COMPARISON MACHINE LEARNING MODEL WITH HYPERPARAMETER RESULT ``` # prepare models models = [] models.append(('K-Nearest Neighbor', KNeighborsClassifier(n_neighbors = 1))) models.append(('Gradient BoostingClassifier', GradientBoostingClassifier(n_estimators=10000))) models.append(('Random ForestClassifier', RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini', max_depth=None, max_features='auto', max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, min_samples_leaf=1, min_samples_split=2, min_weight_fraction_leaf=0.0, n_estimators=200, n_jobs=None, oob_score=False, random_state=None, verbose=0, warm_start=False))) models.append(('Neural Network', MLPClassifier(activation= 'tanh', alpha= 0.0001, hidden_layer_sizes= [50, 100, 50], learning_rate= 'constant', solver= 'adam'))) # evaluate each model in turn results = [] names = [] scoring = 'accuracy' for name, model in models: kfold = KFold(n_splits=5) result = cross_val_score(model, x_train_std, y_train, cv=kfold, scoring=scoring) results.append(result) names.append(name) results_nump = np.array(results) msg = "%s: %f , %f" % (name, results_nump.mean(), results_nump.std()) #two statistics: mean and std.deviation print(msg) # boxplot algorithm comparison fig = pyplot.figure(figsize = (12,7)) fig.suptitle('Machine Learning classification algorithm comparison With Hyperparameter Optimization Result') ax = fig.add_subplot(111) pyplot.boxplot(results) ax.set_xticklabels(names) pyplot.show() ``` <h3>ROC AUC FOR OUR FINAL BEST MODEL WITH HYPERPARAMETER<h3> <br> 1. ROC AUC FOR RANDOM FOREST CLASSIFIER 2. ROC AUC FOR GRADIENT BOOSTING CLASSIFIER ``` # Binarize the output from sklearn.preprocessing import label_binarize y_ros = label_binarize(y_ros, classes=[0, 1,2,3]) n_classes = y_ros.shape[1] print(n_classes) # Add noisy features to make the problem harder random_state = np.random.RandomState(0) n_samples, n_features = X.shape X = np.c_[X, random_state.randn(n_samples, 200 * n_features)] # shuffle and split training and test sets X_train, X_test, y_train, y_test = train_test_split(X_ros, y_ros, test_size=.3, random_state=42) #Nous pouvons maintenant standardiser les variables, #c'est-à-dire les centrer (ramener leur moyenne à 0) #et les réduire (ramener leur écart-type à 1), #afin qu'elles se placent toutes à peu près sur la même échelle # standardiser les données std_scale = preprocessing.StandardScaler().fit(X_train) X_train = std_scale.transform(X_train) X_test = std_scale.transform(X_test) ``` # ROC AUC FOR RANDOM FOREST CLASSIFIER WITH HYPERPARAMETER ``` # Learn to predict each class against the other RFclassifier = OneVsRestClassifier(RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini', max_depth=None, max_features='auto', max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, min_samples_leaf=1, min_samples_split=2, min_weight_fraction_leaf=0.0, n_estimators=200, n_jobs=None, oob_score=False, random_state=None, verbose=0, warm_start=False)) y_score = RFclassifier.fit(X_train, y_train).predict_proba(X_test) # Compute ROC curve and ROC area for each class fpr = dict() tpr = dict() roc_auc = dict() for i in range(n_classes): fpr[i], tpr[i], _ = roc_curve(y_test[:, i], y_score[:, i]) roc_auc[i] = auc(fpr[i], tpr[i]) # Compute micro-average ROC curve and ROC area fpr["micro"], tpr["micro"], _ = roc_curve(y_test.ravel(), y_score.ravel()) roc_auc["micro"] = auc(fpr["micro"], tpr["micro"]) # First aggregate all false positive rates all_fpr = np.unique(np.concatenate([fpr[i] for i in range(n_classes)])) # Then interpolate all ROC curves at this points mean_tpr = np.zeros_like(all_fpr) for i in range(n_classes): mean_tpr += np.interp(all_fpr, fpr[i], tpr[i]) # Finally average it and compute AUC mean_tpr /= n_classes fpr["macro"] = all_fpr tpr["macro"] = mean_tpr roc_auc["macro"] = auc(fpr["macro"], tpr["macro"]) # Plot all ROC curves plt.figure() lw = 2 plt.plot(fpr["micro"], tpr["micro"], label='micro-average ROC curve (area = {0:0.2f})' ''.format(roc_auc["micro"]), color='deeppink', linestyle=':', linewidth=4) plt.plot(fpr["macro"], tpr["macro"], label='macro-average ROC curve (area = {0:0.2f})' ''.format(roc_auc["macro"]), color='navy', linestyle=':', linewidth=4) index=['No Injury',"Minor Injury","Severe Injury","Fatal Injury"] colors = cycle(['aqua', 'darkorange', 'cornflowerblue','red']) for i, color in zip(range(n_classes),colors): if i==0: classe="A améliorer" if i==1: classe=="A corriger de manière urgente" if i==2 : classe=="Satisfaisant" if i==3 : classe=="Très satisfaisant" plt.plot(fpr[i], tpr[i], color=color,lw=lw, label='ROC curve of class {0} (area = {1:0.2f})' ''.format(i, roc_auc[i])) #["Minor Injury","Severe Injury","Fatal Injury" ,"No Injury"] plt.plot([0, 1], [0, 1], 'k--', lw=lw) plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Some extension of Receiver operating characteristic to multi-class for random forest classifier with hyperparameter') plt.legend(loc="lower right") plt.show() ``` # ROC AUC FOR GRADIENT BOOSTING CLASSIFIER WITH HYPERPARAMETER ``` # Learn to predict each class against the other GBclassifier = OneVsRestClassifier(GradientBoostingClassifier(n_estimators=10000)) y_score = GBclassifier.fit(X_train, y_train).predict_proba(X_test) # Compute ROC curve and ROC area for each class fpr = dict() tpr = dict() roc_auc = dict() for i in range(n_classes): fpr[i], tpr[i], _ = roc_curve(y_test[:, i], y_score[:, i]) roc_auc[i] = auc(fpr[i], tpr[i]) # Compute micro-average ROC curve and ROC area fpr["micro"], tpr["micro"], _ = roc_curve(y_test.ravel(), y_score.ravel()) roc_auc["micro"] = auc(fpr["micro"], tpr["micro"]) # First aggregate all false positive rates all_fpr = np.unique(np.concatenate([fpr[i] for i in range(n_classes)])) # Then interpolate all ROC curves at this points mean_tpr = np.zeros_like(all_fpr) for i in range(n_classes): mean_tpr += np.interp(all_fpr, fpr[i], tpr[i]) # Finally average it and compute AUC mean_tpr /= n_classes fpr["macro"] = all_fpr tpr["macro"] = mean_tpr roc_auc["macro"] = auc(fpr["macro"], tpr["macro"]) # Plot all ROC curves plt.figure() lw = 2 plt.plot(fpr["micro"], tpr["micro"], label='micro-average ROC curve (area = {0:0.2f})' ''.format(roc_auc["micro"]), color='deeppink', linestyle=':', linewidth=4) plt.plot(fpr["macro"], tpr["macro"], label='macro-average ROC curve (area = {0:0.2f})' ''.format(roc_auc["macro"]), color='navy', linestyle=':', linewidth=4) index=['No Injury',"Minor Injury","Severe Injury","Fatal Injury"] colors = cycle(['aqua', 'darkorange', 'cornflowerblue','red']) for i, color in zip(range(n_classes),colors): if i==0: classe="A améliorer" if i==1: classe=="A corriger de manière urgente" if i==2 : classe=="Satisfaisant" if i==3 : classe=="Très satisfaisant" plt.plot(fpr[i], tpr[i], color=color,lw=lw, label='ROC curve of class {0} (area = {1:0.2f})' ''.format(i, roc_auc[i])) #["Minor Injury","Severe Injury","Fatal Injury" ,"No Injury"] plt.plot([0, 1], [0, 1], 'k--', lw=lw) plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Some extension of Receiver operating characteristic to multi-class for gradient boosting classifier with hyperparameter') plt.legend(loc="lower right") plt.show() ``` # CONCLUSION We can conclude that after our study on the different models, random forest and gradient boosting remain the most efficient algorithms in classification with hyperparameter optimization. However, we increased the number of estimates which is the number of trees for the two models, but it turned out that these models also had difficulties during machine learning. Building the most achivied model has not been possible due to: The meticulousness, the tediousness and the iterativeness of the process requires relevant and powerful computation. Therefore, working from a local evironment with low GPU make it worst. This is the case of jupyther notebook. Our future work : Hybrid with genetic algorithm + Neural Network(Multilayer perceptron) # REFERENCE [Reference 1](Adi, S., Adishesha, V., Bharadwaj, K., & Narayan, A. (2020). Earthquake Damage Prediction Using Random Forest and Gradient Boosting Classifier. American Journal of Biological and Environmental Statistics, 6, 58. https://doi.org/10.11648/j.ajbes.20200603.14) <br> [Reference 2](Bergstra, J., & Bengio, Y. (s.d.). Random Search for Hyper-Parameter Optimization. 25)<br> [Reference 3](A brief introduction to Multilayer Perceptrons. https://doi.org/10.17632/xszb89kvhk.1) <br> [Reference 4](Khorshidi, H., & Aickelin, U. (2020). Synthetic Over-sampling with the Minority and Majority classes for imbalance problems.) <br> [Reference 5](Pulabaigari, V., & T, H. S. (2011). An Improvement to k-Nearest Neighbor Classifier. In 2011 IEEE Recent Advances in Intelligent Computational Systems, RAICS 2011. https://doi.org/10.1109/RAICS.2011.6069307)
github_jupyter
<h1 style="text-align:center;">Cell Catcher <span style="text-align:center;font-size: 0.5em;">0.4.4</span></h1> <h2 style="text-align:center;">Mito Hacker Toolkit <i style="font-size: 0.5em;">0.7.1</i></h2> <h3 style="text-align:center;">Kashatus Lab @ UVA</h3> # Welcome to Cell Catcher #### Cell Catcher is part of Mito Hacker toolkit that enables you to separate individual cells from fluorescently labeled multi-cell images. This Jupyter notebook provides you with step-by-step directions to separate individual cells from multi-cell images. ## 1) Importing necessary libraries Please check the requirements in the Readme file. ##### Just run the following block of code, you are not expected to enter any data here. ``` #Base Libraries import os import matplotlib.pyplot as plt import numpy as np import pandas as pd from matplotlib.gridspec import GridSpec import cv2 import shutil #Interaction import ipywidgets as widgets from IPython.display import display from ipywidgets import interact, interactive, fixed, interact_manual, IntSlider, Checkbox, FloatSlider, Dropdown from IPython.display import clear_output #Core Functions import cemia55s as cemia style = {'description_width': 'initial'} layout = widgets.Layout(width='95%') ``` ## 2) Locate and Sample Files <br> <details> <summary><span style="font-size:16px;font-weight: bold; color:red">What should I do next? (click here to expand)</span></summary> #### <span style="color:red;">You should interact with the next cell: </span> Please run the next cell, a box will appear. Enter the relative/absolute address of the folder that contains your images inside the box, then press the enter key. #### <span style="color:red;">Examples: </span> * Relative Address * Use . if the images are in the same folder as this file * If your folder of the images (my_folder_of_images) is located in the same directory as this file, you should enter: my_folder_of_images * Absolute Address *If your images are located on Desktop * Mac: you should enter: /Users/username/Desktop/my_folder_of_images * Windows: you should enter: C:\Users\username\Desktop\my_folder_of_images #### <span style="color:red;">Note: </span> * It is preferred to have the folder of your images in the same folder as the current file that you are running * You should press enter after you enetered the address in the box. </details> ``` address,file_list = cemia.address() ``` ### How many files to sample? <br> <details> <summary><span style="font-size:16px;font-weight: bold; color:red">What should I do next? (click here to expand)</span></summary> #### <span style="color:red;">You should interact with the next cell: </span> Please run the next cell, a box will appear. Enter the number of the files you want to sample inside the box, then press the enter key. #### You should enter the maximum number of the sample files that you want to use in the rest of the app. The purpose of these sample images is to help you to tune your parameters. ##### Just sample a reasonable number of files. #### <span style="color:red;">Note:</span> * The number of sampled images would be equal or lower than the number your enter here. The maximum indicated number is the total number of the files in that folder, which may or may not be valid images. * Press the enter key after you entered the desired number of files, and proceed to the next cell. #### <span style="color:red;">Interaction required</span> </details> ``` how_many = cemia.how_many(file_list) ``` ##### Next cell randomly samples some images for parameter tuning purposes. ##### Just run the following block of code, you are not expected to enter any data here. ``` random_files = cemia.random_files(address,file_list,how_many) ``` ## 3) Finding and isolating individual cells in the sample images ##### Just run the following block of code, you are not expected to enter any data here. ``` threshold_pro = ['Assisted Automatic (Pro)'] abspath = os.path.join(address,'temp') ``` ### 3.1) Identifying Nuclei ##### The next block of code is designed to identify individual nuclei in the image. While in most cases the default values will perform well, you may find it useful to tune the values of different parameters, and find a combination that works best for your dataset. <br> <details> <summary><span style="font-size:16px;font-weight: bold; color:red">List of parameters that you will adjust in the next cell (click here to expand)</span></summary> #### Nuclei Signal Threshold * By changing the value of this parameter, you change the signal threshold for detecting nuclei in the image. Lower threshold may help you to detect dimmer nuclei in the image. However, in some cases extemely low threshold values may cause problems by capturing the background noise as nuclei. * Select a threshold value that reasonably works for your sample images. You may check sample images by selecting them from the dropdown menu. #### Nuclei Non Uniformity * This option helps you to reach a better nuclei segmentation results over a wider range of images. #### Nuclei Size Threshold * This option helps you to decide on the minimum acceptable nucleus size in your images. #### Correct Nuclei Shape * This feature tries to reconstruct the shape of the poorly illuminated nuclei in the image. * In some cases, this correction may result in nuclei with angular shapes.</p> * This phenomenon usually does not have an adverse effect on your analysis, since these binary nuclei are merely used as masks on the real nuclei in the image, and their goal is maximal capturing of the nuclei in the image. Ultimately the original shape of the nuclei (from the original image) would be present in the image. #### Low Nuclei Signal * In cases where the signal level in the nuclei channel of your images is low, or your images suffer from low contrast, this option may help you to capture more nuclei in the image. #### <span style="color:red;">Note:</span> <p>Make sure your selected settings work well on all your sample images by selecting different images from the dropdown menu. If they work nicely on sample images, they will do the same on all your images.</p> ### <span style="color:red;">Important Note:</span> <p>If you have used Nuc Adder to simulate missing nuclei, we suggest to select "Low Nuclei Signal" optiom and use higher values for "Nuclei Non Uniformity"(100+).</p> ### How to reset to the default values? * Just run the cell again. </details> ``` nuc_mask = [] #List of Parameters params = cemia.catcher_initial_params @interact(file=Dropdown(options=random_files, description='Select a File',style=style, layout=layout), Intensity_Threshold=IntSlider(min=0,max=100,step=1,value=10,continuous_update=False, description='Nuclei Signal Threshold', style=style,layout=layout), NonUniformity=IntSlider(min=1,max=200,step=2,value=25,continuous_update=False, description='Nuclei Non Uniformity', style=style,layout=layout), Size_Threshold=IntSlider(min=100,max=5000,step=100,value=1000,continuous_update=False,description='Nuclei Size Threshold',layout=layout,style=style), correct=Checkbox(value=True,description='Correct Nuclei Shape',layout = layout, style=style), diffuse=Checkbox(value=False,description='Low Nuclei Signal Level',layout = layout, style=style)) def segment_nucleus(file,Intensity_Threshold,NonUniformity, Size_Threshold, correct, diffuse): fullpath_input = os.path.join(address, file) abspath = os.path.join(address, 'cell_catcher') print(fullpath_input) print(abspath) namestring = file[:file.rfind('.')] + '.tif' #Update parameters, based on user interaction params['Intensity_threshold'].append(Intensity_Threshold) params['Size_threshold'].append(Size_Threshold) params['diffused_bg'].append(diffuse) params['nuc_correction'].append(correct) params['non_uniformity'].append(NonUniformity) try: mask = cemia.nucleus_filtering(fullpath_input, abspath, Intensity_Threshold, Size_Threshold,True,NonUniformity,correct, diffused=diffuse) nuc_mask.append(mask) except: print('Something is not right! Try another image.') pass print('You can now go to next step!') ``` ### 3.2) Identifying Mitochondria ##### The next block of code is designed to identify and separate individual cells in the image. While in most cases the default values will perform well, you may may find it useful to tune the values of different parameters, and find a combination that works best for your dataset. <br> <details> <summary><span style="font-size:16px;font-weight: bold; color:red">List of parameters that you will adjust in the next cell (click to expand)</span></summary> #### Mitochondrial Signal Threshold * This slider sets the intensity threshold for mitochondria. Lower threshold results in capturing more possible mitochondria in the image. Check additional info about this slider and its effects in the "Global Mitochondrial Mask" part of the 'Important Notes' section. #### Mitochondrial Search Radius For Ghost Cells * This slider sets the radial distance around the nuclei to search for mitochondria. This tool is used to identify the ghost cells in the image * The ghost cells are the cells where their nucleus is stained but mitochondrial staining is missing. #### Maximum Mitochondrial Content For Ghost Cells * This slider sets the minimum acceptable amount of mitochondrial content around a cell (within the radius set above). The cells with mitochondrial content below this threshold will be marked as ghost cells. #### Remove The Ghost Cells * By selecting this option, you remove the nuclei of the cells marked as ghost cells from the image. #### Low Mitochondrial Signal * You may select this option if the signal level, or the contrast (Signal to Noise Ratio (SNR) in the mitochondrial channel of your images is low. * Based on the image condition this option may have additional applications. Please refer to the "Important Notes" section. #### My Cells Are Reasonably Separated * If your cells are sparsely distributed across your images, you can use this option along with "Low Mitochondrial Signal" option to speed up your cell separation up to 10X. Please refer to the "Important Notes" section. #### Separate Cells * This box should be checked in order to separate the individual cells in the image. * Please refer to the additional notes below to find the best time to check this box. </details> <br> <details> <summary><span style="font-size:16px;font-weight: bold; color:red">Important Notes (click to expand)</span></summary> ### What does the "Global Mitochondrial Mask" figure tell you? #### The image titled "Global Mitochondrial Mask" serves an important purpose, and can be extremely useful if used and interpreted properly. This figure represents the global mitochondrial content mask for the image, and is not intended to reflect the final and detailed mitochondrial mapping or network in your cells (That's Mito Miner's job). The yellow objects on the image reflect all the objects on the image that are assessed as the probable mitochondrial content in the image, and would be assigned to different nuclei. This may also include some background noise, which is okay, since Mito Miner will take care of it. Lowering the "Mitochondrial Signal Threshold" would result in increase in the number and the area of the yellow objects in the image. This means that you have more mitochondrial candidate objects, which may increase the chance of capturing of true mitochondria in each image. * This is true as long as the yellow objects across the image do not overlap and/or you are not capturing too much noise as mitochondria (i.e. parts of the image that you are sure that are noise and not real mitochondria) * More yellow content in the image means more assignment tasks, which in turn may increase the processing time. * Important: check a few images (using the drop down menu above) before you decide on your final threshold value, and make sure the set of parameters reasonably represents the mitochondrial content in all of those images, since the same threshold will be applied to the batch of images you are analyzing together. * There is an exception which is discussed in the "My Cells Are Entangled" part. ### When to use "Low Mitochondrial Signal" * The most obvious situation is when you have low signal or low contrast images. Low signal levels, and low Signal to Noise Ratio (SNR), make it harder for Cell Catcher to detect mitochondria in the image and subsequently assign them to different cells. By selecting this option Cell Catcher will perform additional pre-processing on the images in attempt to capture more mitochondria. * If you select this option in high signal/SNR images, it will result in forming of yellow clusters in the "Global Mitochondrial Mask" figure, which is totally fine if the following two conditions are met: * As a result of selecting this option you are not capturing excessive amounts of noise as mitochondrial candidates in the image (Similar to lowering the "Mitochondrial Signal Threshold"). * The yellow blobs formed around cells, or in general the yellow objects across the image are not overlapping or excessively touching each other. * In both cases this option may increase the processing time since Cell Catcher should assign more content to various cells*. *There is an exception which is discussed in the "My Cells Are Entangled" part. ### When to use "My Cells Are Entangled" If your cells have mitochondrial networks that are entangled, and it is very hard to decide on the boundaries of the adjacent cells, you may use this option. However, this option may increase the processing time up to 10X. * When you have cells with entangled mitochondrial networks, if you select "Low Mitochondrial Signal" and/or you drastically lower the "Mitochondrial Signal Threshold” value, your actions may result in overlap or excessive touching of the mitochondrial networks from adjacent cells that may make the processing and separation of cells harder. ##### Before selecting this option, you should make sure that this approach is appropriate for all the majority of the images in your batch. ### When to check the "Separate cells" box? * While you are deciding on the best set of parameters for your sample images (which can individually be selected from the dropdown menu at the top), we suggest to keep the "Separate Cells" unchecked. Once you are happy with the combination of your parameters, then select this box to isolate individual cells in your desired images. * Every time you select a new cell, while the segment cell is checked, it will automatically start to segment the cells in the image, which may take some time. Once segmentation is done, the segmented cells will show up. ### How to reset to the default values? * Just run the cell again. In other words, every time you re-run a cell with sliders and checkboxes, the values will reset to their default values. </details> ``` @interact(file=Dropdown(options=random_files, description='Select a File',style=style, layout=layout), Threshold=IntSlider(min=5,max=100,step=1,value=65,continuous_update=False,description='Mitochondrial Signal Threshold',layout=layout, style=style), dilation=IntSlider(min=20,max=100,step=5,value=35,continuous_update=False,description='Mitochondrial Search Radius For Ghost Cells',layout=layout, style=style), empty_cell_threshold=IntSlider(min=0,max=250000,step=1000,value=0,continuous_update=False,description='Maximum Mitochondrial Content For Ghost Cells',layout=layout, style=style), correct=Checkbox(value=False,description='Remove The Ghost Cells',style=style, layout=layout), low_mito=Checkbox(value=False,description='Low Mitochondrial Signal (Read the notes in the previous cell to properly use this option)',style=style, layout=layout), entangled=Checkbox(value=False,description='My Cells Are Entangled (Read the notes in the previous cell to properly use this option)',style=style, layout=layout), separate=Checkbox(value=False,description='Separate Cells (This May take a while, read the notes in the previous cell before selecting it.)',style=style, layout=layout)) def segment_cell(file,Threshold, dilation,empty_cell_threshold, correct, low_mito,entangled,separate): fullpath_input = os.path.join(address, file) abspath = os.path.join(address, 'cell_catcher_temp') namestring = file[:file.rfind('.')] + '.tif' #Updating parameters based on user interaction params['mito_threshold'].append(Threshold) params['empty_cell_thresh'].append(empty_cell_threshold) params['mito_low'].append(low_mito) params['sparse'].append(entangled) params['correct_cells'].append(correct) try: mask_blue=cemia.auto_segmentation(fullpath_input, abspath, namestring,Threshold,separate,dilation, correct, params['Intensity_threshold'][-1], params['Size_threshold'][-1],params['empty_cell_thresh'][-1], hide=False,nuc_correct=False,diffused=params['diffused_bg'][-1], mito_diffused=params['mito_low'][-1],entangled=params['sparse'][-1], non_uniformity=params['non_uniformity'][-1]) except: print('{} is not a valid image file, try another file.'.format(file)) pass print('The following settings will be used to analyze all the images!') print('**************************************************************') params_pd = {} for k in params: try: params_pd[k] = params[k][-1] print(f'{k}: {params_pd[k]}') except: pass params_pd = pd.DataFrame(params_pd, index=[0]) params_pd.to_csv(os.path.join(address ,'cell_catcher_params.csv'), index=False) ``` ## 4) Processing all the cells ##### Just run next block of code, and then go and enjoy your time. Running this block of code may take few hours depending on the number of images that you have. ``` try: os.makedirs(os.path.join(address, 'output')) except FileExistsError: pass cell_list = os.listdir(address) for file in file_list: fullpath_input = os.path.join(address, file) abspath = os.path.join(address, 'output') namestring = file[:file.rfind('.')] + '.tif' print(file) try: cemia.auto_segmentation(fullpath_input, abspath, namestring,params['mito_threshold'][-1],True,params['neighorhood'][-1], params['correct_cells'][-1], params['Intensity_threshold'][-1], params['Size_threshold'][-1], params['empty_cell_thresh'][-1], hide=True, nuc_correct=False, diffused=params['diffused_bg'][-1],mito_diffused=params['mito_low'][-1],entangled=params['sparse'][-1], non_uniformity=params['non_uniformity'][-1]) cemia.single_cell_QC(abspath, hide=True) except: print('{} is not a valid image file, trying the next file.\n'.format(file)) pass print('You are all set!\n') ``` ## Optional Step: Remove Cell Catcher Temp folders #### If you want to delete the temporary folders created by Cell Catcher, please run the following cell. This is the folder that contains the cells that you isolated when you were experimenting with Cell Catcher. ``` try: shutil.rmtree(os.path.join(address,'cell_catcher_temp')) except: pass ``` # The End!
github_jupyter
<h1> Getting started with TensorFlow </h1> In this notebook, you play around with the TensorFlow Python API. ``` import tensorflow as tf import numpy as np print(tf.__version__) ``` <h2> Adding two tensors </h2> First, let's try doing this using numpy, the Python numeric package. numpy code is immediately evaluated. ``` a = np.array([5, 3, 8]) b = np.array([3, -1, 2]) c = np.add(a, b) print(c) ``` The equivalent code in TensorFlow consists of two steps: <p> <h3> Step 1: Build the graph </h3> ``` a = tf.constant([5, 3, 8]) b = tf.constant([3, -1, 2]) c = tf.add(a, b) print(c) ``` c is an Op ("Add") that returns a tensor of shape (3,) and holds int32. The shape is inferred from the computation graph. Try the following in the cell above: <ol> <li> Change the 5 to 5.0, and similarly the other five numbers. What happens when you run this cell? </li> <li> Add an extra number to a, but leave b at the original (3,) shape. What happens when you run this cell? </li> <li> Change the code back to a version that works </li> </ol> <p/> <h3> Step 2: Run the graph ``` with tf.Session() as sess: result = sess.run(c) print(result) ``` <h2> Using a feed_dict </h2> Same graph, but without hardcoding inputs at build stage ``` a = tf.placeholder(dtype=tf.int32, shape=(None,)) # batchsize x scalar b = tf.placeholder(dtype=tf.int32, shape=(None,)) c = tf.add(a, b) with tf.Session() as sess: result = sess.run(c, feed_dict={ a: [3, 4, 5], b: [-1, 2, 3] }) print(result) ``` <h2> Heron's Formula in TensorFlow </h2> The area of triangle whose three sides are $(a, b, c)$ is $\sqrt{s(s-a)(s-b)(s-c)}$ where $s=\frac{a+b+c}{2}$ Look up the available operations at https://www.tensorflow.org/api_docs/python/tf ``` def compute_area(sides): # slice the input to get the sides a = sides[:,0] # 5.0, 2.3 b = sides[:,1] # 3.0, 4.1 c = sides[:,2] # 7.1, 4.8 # Heron's formula s = (a + b + c) * 0.5 # (a + b) is a short-cut to tf.add(a, b) areasq = s * (s - a) * (s - b) * (s - c) # (a * b) is a short-cut to tf.multiply(a, b), not tf.matmul(a, b) return tf.sqrt(areasq) with tf.Session() as sess: # pass in two triangles area = compute_area(tf.constant([ [5.0, 3.0, 7.1], [2.3, 4.1, 4.8] ])) result = sess.run(area) print(result) ``` <h2> Placeholder and feed_dict </h2> More common is to define the input to a program as a placeholder and then to feed in the inputs. The difference between the code below and the code above is whether the "area" graph is coded up with the input values or whether the "area" graph is coded up with a placeholder through which inputs will be passed in at run-time. ``` with tf.Session() as sess: sides = tf.placeholder(tf.float32, shape=(None, 3)) # batchsize number of triangles, 3 sides area = compute_area(sides) result = sess.run(area, feed_dict = { sides: [ [5.0, 3.0, 7.1], [2.3, 4.1, 4.8] ] }) print(result) ``` ## tf.eager tf.eager allows you to avoid the build-then-run stages. However, most production code will follow the lazy evaluation paradigm because the lazy evaluation paradigm is what allows for multi-device support and distribution. <p> One thing you could do is to develop using tf.eager and then comment out the eager execution and add in the session management code. <b>You may need to restart the session to try this out.</b> ``` import tensorflow as tf tf.enable_eager_execution() def compute_area(sides): # slice the input to get the sides a = sides[:,0] # 5.0, 2.3 b = sides[:,1] # 3.0, 4.1 c = sides[:,2] # 7.1, 4.8 # Heron's formula s = (a + b + c) * 0.5 # (a + b) is a short-cut to tf.add(a, b) areasq = s * (s - a) * (s - b) * (s - c) # (a * b) is a short-cut to tf.multiply(a, b), not tf.matmul(a, b) return tf.sqrt(areasq) area = compute_area(tf.constant([ [5.0, 3.0, 7.1], [2.3, 4.1, 4.8] ])) print(area) ``` ## Challenge Exercise Use TensorFlow to find the roots of a fourth-degree polynomial using [Halley's Method](https://en.wikipedia.org/wiki/Halley%27s_method). The five coefficients (i.e. $a_0$ to $a_4$) of <p> $f(x) = a_0 + a_1 x + a_2 x^2 + a_3 x^3 + a_4 x^4$ <p> will be fed into the program, as will the initial guess $x_0$. Your program will start from that initial guess and then iterate one step using the formula: <img src="https://wikimedia.org/api/rest_v1/media/math/render/svg/142614c0378a1d61cb623c1352bf85b6b7bc4397" /> <p> If you got the above easily, try iterating indefinitely until the change between $x_n$ and $x_{n+1}$ is less than some specified tolerance. Hint: Use [tf.while_loop](https://www.tensorflow.org/api_docs/python/tf/while_loop) Copyright 2017 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License
github_jupyter
``` name = '2019-02-28-functions-will' title = 'Functions in Python, an introduction' tags = 'functions, basics' author = 'Wilhelm Hodder' from nb_tools import connect_notebook_to_post from IPython.core.display import HTML html = connect_notebook_to_post(name, title, tags, author) ``` ## Basic principles and features Functions are exactly that: they usually take an input and return an output. When you do your typical Python coding you will be using functions all the time, for example **np.mean()** or **np.arange()** from the numpy library. The great thing is you can write them yourself! Below is a very simple example: ``` def print_a_phrase(): # we start the definition of a function with "def" print("Academics of the world unite! You have nothing to lose but your over-priced proprietary software licenses.") #return 0; print_a_phrase() ``` We define the function using **def**, followed by whatever name we choose for the function, which is immediately followed by a round bracket **()**. The bracket is where you would write your *arguments* in, for example your input variable. The function above doesn't take an input, but it prints a pre-defined phrase. If we were to make it more dynamic and make it print any input we want to give it, it would just become **print()**, so not much use for this here: Do not re-invent the wheel! It also doesn't actually *return* anything, it just *does* something. In C++ this function would be defined as **void**. What if we do give it an input? Below are two examples of simple functions for unit conversion: ``` def convert_pa_to_mb(pascal): millibar = pascal * 0.01 return millibar ``` See how the above takes the input, operates on it, and then **returns** your output. Note how we didn't specifify what form **Pascal** has to take: we could put in an integer or a float. This is due to Python's *polymorphism*. We could also put a string in, and it wouldn't complain until it has to do maths on it, which is when it causes an error. More on this later. ``` convert_pa_to_mb(80000) ``` But if your function is that simple, you can save a line by calculating and returning the result in one go: ``` def convert_mb_to_pa(millibar): return millibar * 100 convert_mb_to_pa(1050) ``` Now all of this was very basic, and you might think, why not just write the calculation directly into my main code? For a start, as your work becomes more sophisticated the longer and more complex your calculations and operations become. Then consider that you'll probably end up wanting to reuse the same task in your code or in another code. If you wrote out the same stuff again and again your code would get very messy very quickly. Instead it really does help to keep recurring functions neatly titied away at the top or bottom of your code, or in a seperate file. ``` def check_integer_and_change(value): if value.is_integer() == False: remainder = value while remainder > 1: remainder = remainder - 1 # reduce number to smallest positive value if remainder >= 0.5: # if half ovr above, round up value = value + 1 - remainder else: value = value - remainder # round down return value ``` Above is just another example of a function; it figures out if a value is an integer, and if it is not, it rounds it up or down, as appropriate. Notice **is_integer()** is also a function, from the main python library. Here it doesn't take an input in it's brackets **()**, but instead it's "attached" to the variable **value**. This is because it is a *class function*, and in Python variables are *class objects*, but that's a story for another presentation. In fact, you can find an excellent tutorial on classes here: https://docs.python.org/3/tutorial/classes.html . ``` import numpy as np # need this to make array my_array = np.arange(5) # make an array of integers new_array = np.array([1.2, 8, 4.5]) # make another array to insert into our main array my_array = np.concatenate((my_array, new_array)) # let's add some non-integers to our little array print(my_array) for i in range(len(my_array)): my_array[i] = check_integer_and_change(my_array[i]) # we perform our function from above on each array element print(my_array) ``` Another good reason for using functions is how it deals with *memory*: If you use arrays a lot, and you do all your calculations in line with your main code then you might start piling up a lot of *stuff*, i.e. you use up your memory, which can lead to your program to slow, or even memory leackage. Instead, functions take your input, temporarily take some extra space in your memory, and once they spit out their output, they delete whatever extra stuff they needed for their calculation, but without affecting your input, unless you want it to. - **for** and **while** loops, or when you use **if**, also delete any variables that were defined within them, but they might change your input from before the loop, if you're not careful! To illustrate this danger: ``` def double_something(value): value = value * 2 # we actively modify the original input variable; in many cases the original value would be irretrievable return value input_value = 5.0 new_value = double_something(input_value) print("new_value =", new_value) # now check if our original input is the same print("input =", input_value) # now let's do the same the function does, but in a loop for 1 iteration: value = 5.0 new_value = 0 for i in range(1): # we copy the function above exactly value = value * 2 new_value = value # our "return" print("new_value =", new_value) # now check if our original input is the same print("input =", value) ``` So we can see that due to sloppy coding we now changed our original input in the **for** loop, but preserved it when we used a function instead. There are instances where a function could permanently affect your input data, due to the fact that in python when you use the **=** operator, the variables you get are really just pointers to the same data. It is recommended to make sure you've properly copied vital data before passing it to a function. Now let's look at putting different variable types in, see what we can get out, and think of how what we'll find could be useful to us. Say you want a function that can operate on a single quantity, as well as multiple quantities, e.g. in an array. For this example we will do a unit conversion and then calculate the average of all the input values. But we will use **try** and **except** to make a distinction between single values and arrays. ``` def convert_JeV_and_mean(eV_values): # take input in eV joule_values = 1.60218e-18 * eV_values # here just do the simple conversion # if we want the mean from numpy we need to make sure we only do that for an array input try: array_length = len(joule_values) # if we have a single value, this line will cause an error mean = np.mean(joule_values) except: return joule_values # if it's just a single value, return it by itself return joule_values, mean # if it's an array, we can return both it and its mean ``` Let's put in a float... ``` convert_JeV_and_mean(1.0) ``` Only a single output was returned: the converted float. Now let's input a **numpy array**. (Btw, the values seen below are of the order GeV, which is a common sight in high energy particle physics, and in astrophysics) ``` some_data = np.array([5.0956e-11, 5.1130e-11, 4.8856e-11 ]) convert_JeV_and_mean(some_data) ``` The output above looks complicated, but it is essentially first the array of converted values, and then the mean. But this bracketed output looks messy and in your own code you would do something like this: ``` results, mean = convert_JeV_and_mean(some_data) print("results =", results); print("mean =", mean, "J") ``` As the function potentially outputs two different objects, we can assign them to seperate variables as shown above. Notice how the order of the output (i.e. values *then* mean) corresponds to the order in which we wrote them after **return** at the bottom of our function. ## Examples of advanced features ### Decorators and Wrappers Quite neatly, we can define functions within functions, and also return functions from functions. An example where this is applied is the use of **decorators** and **wrappers**, which are types of functions. Below is a demonstration of a very simple example: we have a function called **func()**, and we *wrap* it up in another function, which will just measure time, inside the decorator. ``` from functools import wraps import time def decorator(f): @wraps(f) def wrapper(*args, **kwargs): start_time = time.time() rv = f(*args, **kwargs) # here we run the function f print("Time taken =", time.time() - start_time) # difference in points in time gives duration of f run return rv return wrapper # we return the function called wrapper @decorator def func(): pass # does nothing, just for demonstration ``` The `@` followed by the name of a function, here **wraps** and **decorator**, acts like a kind of override. You place the @ right above a function definition, which, for example, tells the program that whenever **func** is run, it is *decorated* by the function called **decorator**. decorator returns **wrapper**, which will now run everytime func is run. **\*args** and **\*\*kwargs** are ways of allowing you to pass a flexible number of arguments to your function, and are explained here: http://book.pythontips.com/en/latest/args_and_kwargs.html . Let's see if it works: ``` func() ``` Running **func()** printed the time taken, which will naturally be negligible, due to the simplicity of the function. ### Docstrings Finally, not necessarily an "advanced" feature but still useful, we have **docstrings**, which are known to be *documentation* inside your code. You can insert a docstring anywhere in your code, but it's not advised as that can slow your program down, and in most places you should use *comments* instead. However, they are very useful, say, at the top of a function definition to explain *what* the function does. For example: ``` def check_integer_and_round(value): """ Function takes a float or integer value and tests the quantity for its type. If the input is an integer ther function does nothing more and returns the original input If the input is a non-integer it rounds it to the nearest whole integer, and returns the result. """ if value.is_integer() == False: remainder = value while remainder > 1: remainder = remainder - 1 # reduce number to smallest positive value if remainder >= 0.5: # if half ovr above, round up value = value + 1 - remainder else: value = value - remainder # round down return value ``` We reused the previous function for rounding numbers to integers, with a small change to its name to avoid any issues with doubly defining it. We also addedd some text within two triple quotation marks `"""`; this is a docstring. Like a comment, which starts with a hash `#`, it does nothing functionally when the code is run, it simply serves to help the user understand what the function does. In your terminal you can call it with the **help()** function: ``` help(check_integer_and_round) ``` A few more examples can be found in an earlier post: [Some peculiarities of using functions in Python](https://ueapy.github.io/some-peculiarities-of-using-functions-in-python.html). ``` HTML(html) ```
github_jupyter
# Parsing ## Overview Syntactic analysis (or **parsing**) of a sentence is the process of uncovering the phrase structure of the sentence according to the rules of grammar. There are two main approaches to parsing. *Top-down*, start with the starting symbol and build a parse tree with the given words as its leaves, and *bottom-up*, where we start from the given words and build a tree that has the starting symbol as its root. Both approaches involve "guessing" ahead, so it may take longer to parse a sentence (the wrong guess mean a lot of backtracking). Thankfully, a lot of effort is spent in analyzing already analyzed substrings, so we can follow a dynamic programming approach to store and reuse these parses instead of recomputing them. In dynamic programming, we use a data structure known as a chart, thus the algorithms parsing a chart is called **chart parsing**. We will cover several different chart parsing algorithms. ## Chart Parsing ### Overview The chart parsing algorithm is a general form of the following algorithms. Given a non-probabilistic grammar and a sentence, this algorithm builds a parse tree in a top-down manner, with the words of the sentence as the leaves. It works with a dynamic programming approach, building a chart to store parses for substrings so that it doesn't have to analyze them again (just like the CYK algorithm). Each non-terminal, starting from S, gets replaced by its right-hand side rules in the chart until we end up with the correct parses. ### Implementation A parse is in the form `[start, end, non-terminal, sub-tree, expected-transformation]`, where `sub-tree` is a tree with the corresponding `non-terminal` as its root and `expected-transformation` is a right-hand side rule of the `non-terminal`. The chart parsing is implemented in a class, `Chart`. It is initialized with grammar and can return the list of all the parses of a sentence with the `parses` function. The chart is a list of lists. The lists correspond to the lengths of substrings (including the empty string), from start to finish. When we say 'a point in the chart', we refer to a list of a certain length. A quick rundown of the class functions: * `parses`: Returns a list of parses for a given sentence. If the sentence can't be parsed, it will return an empty list. Initializes the process by calling `parse` from the starting symbol. * `parse`: Parses the list of words and builds the chart. * `add_edge`: Adds another edge to the chart at a given point. Also, examines whether the edge extends or predicts another edge. If the edge itself is not expecting a transformation, it will extend other edges and it will predict edges otherwise. * `scanner`: Given a word and a point in the chart, it extends edges that were expecting a transformation that can result in the given word. For example, if the word 'the' is an 'Article' and we are examining two edges at a chart's point, with one expecting an 'Article' and the other a 'Verb', the first one will be extended while the second one will not. * `predictor`: If an edge can't extend other edges (because it is expecting a transformation itself), we will add to the chart rules/transformations that can help extend the edge. The new edges come from the right-hand side of the expected transformation's rules. For example, if an edge is expecting the transformation 'Adjective Noun', we will add to the chart an edge for each right-hand side rule of the non-terminal 'Adjective'. * `extender`: Extends edges given an edge (called `E`). If `E`'s non-terminal is the same as the expected transformation of another edge (let's call it `A`), add to the chart a new edge with the non-terminal of `A` and the transformations of `A` minus the non-terminal that matched with `E`'s non-terminal. For example, if an edge `E` has 'Article' as its non-terminal and is expecting no transformation, we need to see what edges it can extend. Let's examine the edge `N`. This expects a transformation of 'Noun Verb'. 'Noun' does not match with 'Article', so we move on. Another edge, `A`, expects a transformation of 'Article Noun' and has a non-terminal of 'NP'. We have a match! A new edge will be added with 'NP' as its non-terminal (the non-terminal of `A`) and 'Noun' as the expected transformation (the rest of the expected transformation of `A`). You can view the source code by running the cell below: ``` psource(Chart) ``` ### Example We will use the grammar `E0` to parse the sentence "the stench is in 2 2". First, we need to build a `Chart` object: ``` chart = Chart(E0) ``` And then we simply call the `parses` function: ``` print(chart.parses('the stench is in 2 2')) ``` You can see which edges get added by setting the optional initialization argument `trace` to true. ``` chart_trace = Chart(nlp.E0, trace=True) chart_trace.parses('the stench is in 2 2') ``` Let's try and parse a sentence that is not recognized by the grammar: ``` print(chart.parses('the stench 2 2')) ``` An empty list was returned. ## CYK Parse The *CYK Parsing Algorithm* (named after its inventors, Cocke, Younger, and Kasami) utilizes dynamic programming to parse sentences of grammar in *Chomsky Normal Form*. The CYK algorithm returns an *M x N x N* array (named *P*), where *N* is the number of words in the sentence and *M* the number of non-terminal symbols in the grammar. Each element in this array shows the probability of a substring being transformed from a particular non-terminal. To find the most probable parse of the sentence, a search in the resulting array is required. Search heuristic algorithms work well in this space, and we can derive the heuristics from the properties of the grammar. The algorithm in short works like this: There is an external loop that determines the length of the substring. Then the algorithm loops through the words in the sentence. For each word, it again loops through all the words to its right up to the first-loop length. The substring will work on in this iteration is the words from the second-loop word with the first-loop length. Finally, it loops through all the rules in the grammar and updates the substring's probability for each right-hand side non-terminal. ### Implementation The implementation takes as input a list of words and a probabilistic grammar (from the `ProbGrammar` class detailed above) in CNF and returns the table/dictionary *P*. An item's key in *P* is a tuple in the form `(Non-terminal, the start of a substring, length of substring)`, and the value is a `Tree` object. The `Tree` data structure has two attributes: `root` and `leaves`. `root` stores the value of current tree node and `leaves` is a list of children nodes which may be terminal states(words in the sentence) or a sub tree. For example, for the sentence "the monkey is dancing" and the substring "the monkey" an item can be `('NP', 0, 2): <Tree object>`, which means the first two words (the substring from index 0 and length 2) can be parse to a `NP` and the detailed operations are recorded by a `Tree` object. Before we continue, you can take a look at the source code by running the cell below: ``` import os, sys sys.path = [os.path.abspath("../../")] + sys.path from nlp4e import * from notebook4e import psource psource(CYK_parse) ``` When updating the probability of a substring, we pick the max of its current one and the probability of the substring broken into two parts: one from the second-loop word with third-loop length, and the other from the first part's end to the remainder of the first-loop length. ### Example Let's build a probabilistic grammar in CNF: ``` E_Prob_Chomsky = ProbGrammar("E_Prob_Chomsky", # A Probabilistic Grammar in CNF ProbRules( S = "NP VP [1]", NP = "Article Noun [0.6] | Adjective Noun [0.4]", VP = "Verb NP [0.5] | Verb Adjective [0.5]", ), ProbLexicon( Article = "the [0.5] | a [0.25] | an [0.25]", Noun = "robot [0.4] | sheep [0.4] | fence [0.2]", Adjective = "good [0.5] | new [0.2] | sad [0.3]", Verb = "is [0.5] | say [0.3] | are [0.2]" )) ``` Now let's see the probabilities table for the sentence "the robot is good": ``` words = ['the', 'robot', 'is', 'good'] grammar = E_Prob_Chomsky P = CYK_parse(words, grammar) print(P) ``` A `defaultdict` object is returned (`defaultdict` is basically a dictionary but with a default value/type). Keys are tuples in the form mentioned above and the values are the corresponding parse trees which demonstrates how the sentence will be parsed. Let's check the details of each parsing: ``` parses = {k: p.leaves for k, p in P.items()} print(parses) ``` Please note that each item in the returned dict represents a parsing strategy. For instance, `('Article', 0, 0): ['the']` means parsing the article at position 0 from the word `the`. For the key `'VP', 2, 3`, it is mapped to another `Tree` which means this is a nested parsing step. If we print this item in detail: ``` for subtree in P['VP', 2, 3].leaves: print(subtree.leaves) ``` So we can interpret this step as parsing the word at index 2 and 3 together('is' and 'good') as a verh phrase. ## A-star Parsing The CYK algorithm uses space of $O(n^2m)$ for the P and T tables, where n is the number of words in the sentence, and m is the number of nonterminal symbols in the grammar and takes time $O(n^3m)$. This is the best algorithm if we want to find the best parse and works for all possible context-free grammars. But actually, we only want to parse natural languages, not all possible grammars, which allows us to apply more efficient algorithms. By applying a-start search, we are using the state-space search and we can get $O(n)$ running time. In this situation, each state is a list of items (words or categories), the start state is a list of words, and a goal state is the single item S. In our code, we implemented a demonstration of `astar_search_parsing` which deals with the text parsing problem. By specifying different `words` and `gramma`, we can use this searching strategy to deal with different text parsing problems. The algorithm returns a boolean telling whether the input words is a sentence under the given grammar. For detailed implementation, please execute the following block: ``` psource(astar_search_parsing) ``` ### Example Now let's try "the wumpus is dead" example. First we need to define the grammer and words in the sentence. ``` grammar = E0 words = ['the', 'wumpus', 'is', 'dead'] astar_search_parsing(words, grammar) ``` The algorithm returns a 'S' which means it treats the inputs as a sentence. If we change the order of words to make it unreadable: ``` words_swaped = ["the", "is", "wupus", "dead"] astar_search_parsing(words_swaped, grammar) ``` Then the algorithm asserts that out words cannot be a sentence. ## Beam Search Parsing In the beam searching algorithm, we still treat the text parsing problem as a state-space searching algorithm. when using beam search, we consider only the b most probable alternative parses. This means we are not guaranteed to find the parse with the highest probability, but (with a careful implementation) the parser can operate in $O(n)$ time and still finds the best parse most of the time. A beam search parser with b = 1 is called a **deterministic parser**. ### Implementation In the beam search, we maintain a `frontier` which is a priority queue keep tracking of the current frontier of searching. In each step, we explore all the examples in `frontier` and saves the best n examples as the frontier of the exploration of the next step. For detailed implementation, please view with the following code: ``` psource(beam_search_parsing) ``` ### Example Let's try both the positive and negative wumpus example on this algorithm: ``` beam_search_parsing(words, grammar) beam_search_parsing(words_swaped, grammar) ```
github_jupyter
# Examining False Positives from DR5 [v1.1] v1.0 -- Examining v2 of gensample v1.1 -- Examining David's eyeball list ``` %matplotlib notebook # imports import pdb from matplotlib import pyplot as plt from astropy import units as u from specdb.specdb import IgmSpec from pyigm.surveys import dlasurvey as pyi_dla from pyigm.abssys.utils import hi_model sys.path.append(os.path.abspath("../../src")) import vette_results as vetter ``` ## IGMSpec ``` igmsp = IgmSpec() ``` ## Load SDSS DR5 ``` sdss = pyi_dla.DLASurvey.load_SDSS_DR5() sdss ``` ### For vetting ``` sdss_all = pyi_dla.DLASurvey.load_SDSS_DR5(sample='all_sys') s_coord = sdss_all.coord s_zabs = sdss_all.zabs np.min(sdss_all.NHI) def chk_against_sdss(isys): gdsep = isys.coord.separation(s_coord) < 2*u.arcsec gdz = np.abs(s_zabs-isys.zabs) < 0.1 # match = gdsep & gdz if np.sum(match) == 0: print("No match in JXP DR5") return for ii in np.where(match)[0]: #pdb.set_trace() print("Matched to {}".format(sdss_all._abs_sys[ii])) # Show DLA def plot_dla(dla, wvoff=40.): # Get spectrum all_spec, all_meta = igmsp.allspec_at_coord(dla.coord, groups=['SDSS_DR7']) spec = all_spec[0] # Get wavelength limits wvcen = (1+dla.zabs)*1215.67 gd_wv = (spec.wavelength.value > wvcen-wvoff) & (spec.wavelength.value < wvcen+wvoff) # Continuum? use_co = False if spec.co_is_set: use_co = True if spec.co[0] != 1.: use_co = False if use_co: mxco = np.max(spec.co[gd_wv]) co = self.co else: mxco = np.max(spec.flux[gd_wv]) co = mxco # Create DLA lya, lines = hi_model(dla, spec, lya_only=True) # Plot plt.clf() ax = plt.gca() ax.plot(spec.wavelength, spec.flux, 'k', drawstyle='steps-mid') ax.plot(spec.wavelength, spec.sig, 'r:') # Model ax.plot(lya.wavelength, lya.flux*co, 'g') # model if use_co: ax.plot(spec.wavelength, spec.co, '--', color='gray') # Axes ax.set_xlim(wvcen-wvoff, wvcen+wvoff) ax.set_ylim(-0.1*mxco, mxco*1.1) plt.show() ``` ## v2 of gensample ``` ml_survey = vetter.json_to_sdss_dlasurvey('../../results/results_catalog_dr7_model_gensample_v2.json',sdss) false_neg, midx, false_pos = vetter.vette_dlasurvey(ml_survey, sdss) # Table for David vetter.mk_false_neg_table(false_pos, '../../results/false_positives_DR5_v2_gen.csv') ``` ### Examine globally ``` len(false_pos) # NHI NHI = np.array([x.NHI for x in false_pos]) plt.clf() ax = plt.gca() ax.hist(NHI, bins=40) ax.set_xlim(20., 21.1) ax.set_xlabel('log NHI') plt.show() # z z = [x.zabs for x in false_pos] plt.clf() ax = plt.gca() ax.hist(z, bins=40) ax.set_xlim(2., 5.) ax.set_xlabel('z_abs') plt.show() ``` ### Examine a few individually #### 0 JXP identified a system there. NHI just below DLA cut-off ``` idx = 0 false_pos[idx] chk_against_sdss(false_pos[idx]) ``` #### 1, 2, 3 Low S/N data No matches to JXP ``` idx = 1 print(false_pos[idx]) chk_against_sdss(false_pos[idx]) ``` #### 4 Match to low NHI in JXP ``` idx = 4 print(false_pos[idx]) chk_against_sdss(false_pos[idx]) ``` #### 5 Plausible, low NHI DLA; metals Missed entirey by JXP ``` idx = 5 print(false_pos[idx]) chk_against_sdss(false_pos[idx]) ``` #### 6 No JXP match Weak NHI; not likely a DLA ``` idx = 6 print(false_pos[idx]) chk_against_sdss(false_pos[idx]) plot_dla(false_pos[idx], wvoff=60.) ``` #### 7 Weak, very unlikely DLA ``` idx = 7 print(false_pos[idx]) chk_against_sdss(false_pos[idx]) ``` #### 8 Matched to weak JXP system ``` idx = 8 print(false_pos[idx]) chk_against_sdss(false_pos[idx]) ``` #### 9 Junk ``` idx = 9 print(false_pos[idx]) chk_against_sdss(false_pos[idx]) plot_dla(false_pos[idx], wvoff=60.) ``` #### 10 More junk (flux spike) ``` idx = 10 print(false_pos[idx]) chk_against_sdss(false_pos[idx]) plot_dla(false_pos[idx], wvoff=60.) ``` #### 11, 12 Low S/N Could be real ``` idx = 11 print(false_pos[idx]) chk_against_sdss(false_pos[idx]) plot_dla(false_pos[idx], wvoff=60.) ``` #### 13 Plausible; likely metals ``` idx = 13 print(false_pos[idx]) chk_against_sdss(false_pos[idx]) plot_dla(false_pos[idx], wvoff=60.) ``` #### 14 ``` idx = 14 print(false_pos[idx]) chk_against_sdss(false_pos[idx]) ``` #### 15 ``` idx = 15 print(false_pos[idx]) chk_against_sdss(false_pos[idx]) ``` #### 16 Strong absorber But NHI < 20.3 ``` idx = 16 print(false_pos[idx]) chk_against_sdss(false_pos[idx]) plot_dla(false_pos[idx], wvoff=60.) ``` #### 17 ``` idx = 17 print(false_pos[idx]) chk_against_sdss(false_pos[idx]) ``` #### 18 ``` idx = 18 print(false_pos[idx]) chk_against_sdss(false_pos[idx]) ``` #### 19 Low S/N Could be legit ``` idx = 19 print(false_pos[idx]) chk_against_sdss(false_pos[idx]) plot_dla(false_pos[idx], wvoff=60.) ``` #### 20 ``` idx = 20 print(false_pos[idx]) chk_against_sdss(false_pos[idx]) ``` ---- ## Examining David's high confidence FPs ### Load v4.3.1 ``` ml_survey = vetter.json_to_sdss_dlasurvey('../../results/results_model_4.3.1_data_dr5.json',sdss) false_neg, midx, false_pos = vetter.vette_dlasurvey(ml_survey, sdss) ``` ### Examine ### 416-228 High z system (NHI=20.35) is the FP Not quite 20.3. Probably more like 20.2 ``` idx = 19 print(false_pos[idx], false_pos[idx].plate, false_pos[idx].fiber) chk_against_sdss(false_pos[idx]) plot_dla(false_pos[idx], wvoff=60.) ``` ### 437-532 Higher-z system I fitted as 20.2 ``` idx = 20 print(false_pos[idx], false_pos[idx].plate, false_pos[idx].fiber) chk_against_sdss(false_pos[idx]) ``` ### 466-634 Flux doesn't go to zero May be a BAL; not a DLA ``` idx = 22 print(false_pos[idx], false_pos[idx].plate, false_pos[idx].fiber) chk_against_sdss(false_pos[idx]) ``` ### 450-590 I fitted with 20.2 ``` idx = 23 print(false_pos[idx], false_pos[idx].plate, false_pos[idx].fiber) chk_against_sdss(false_pos[idx]) ``` ### 817-540 Definite junk (z=3.5876 system) ### 826-589 Fitted as 20.25 by JXP (z=3.2 system) ``` idx = 85 print(false_pos[idx], false_pos[idx].plate, false_pos[idx].fiber) chk_against_sdss(false_pos[idx]) ``` ### 860-441 Fitted as 20.25 by JXP ``` idx = 94 print(false_pos[idx], false_pos[idx].plate, false_pos[idx].fiber) chk_against_sdss(false_pos[idx]) ``` ### 872-298 Could be legit. All depends on the flux at 4570A ``` idx = 97 print(false_pos[idx], false_pos[idx].plate, false_pos[idx].fiber) chk_against_sdss(false_pos[idx]) plot_dla(false_pos[idx], wvoff=60.) ``` ### 879-614 Fitted as 19.8 by JXP ``` idx = 101 print(false_pos[idx], false_pos[idx].plate, false_pos[idx].fiber) chk_against_sdss(false_pos[idx]) ``` ### 894-631 Flux does not go to zero; could be data quality issue ### 910-526 Appears to be missing in JXP catalog Only the z~zem system was analyzed ``` idx = 106 print(false_pos[idx], false_pos[idx].plate, false_pos[idx].fiber) chk_against_sdss(false_pos[idx]) ``` ### 965-399 Could be real Not analyzed by JXP ``` idx = 115 print(false_pos[idx], false_pos[idx].plate, false_pos[idx].fiber) chk_against_sdss(false_pos[idx]) plot_dla(false_pos[idx], wvoff=60.) ``` ### 1010-22 Fit by JXP as 20.1 ``` idx = 123 print(false_pos[idx], false_pos[idx].plate, false_pos[idx].fiber) chk_against_sdss(false_pos[idx]) ``` ### 1015-64 Flux in core is worrisome, but more likely data failure than anything else Strong metals; likely DLA ``` idx = 124 print(false_pos[idx], false_pos[idx].plate, false_pos[idx].fiber) chk_against_sdss(false_pos[idx]) plot_dla(false_pos[idx], wvoff=60.) ``` ### 1173-575 JXP fit as 20.25 ``` idx = 133 print(false_pos[idx], false_pos[idx].plate, false_pos[idx].fiber) chk_against_sdss(false_pos[idx]) ``` ### 1240-256 Fit by JXP at 20.25 ``` idx = 144 print(false_pos[idx], false_pos[idx].plate, false_pos[idx].fiber) chk_against_sdss(false_pos[idx]) ``` ### 1279-213 In DR5. Large z offset? ``` idx = 149 print(false_pos[idx], false_pos[idx].plate, false_pos[idx].fiber) chk_against_sdss(false_pos[idx]) ``` ### 1282-555 Fit as 20.2 by JXP ``` idx = 150 print(false_pos[idx], false_pos[idx].plate, false_pos[idx].fiber) chk_against_sdss(false_pos[idx]) ```
github_jupyter
## Data Given For Tutorial - Created into CSVs in this notebook: $$ \text{P(Score} = x \text{| race) (calculated)} $$ $$ \text{P(NonDefault | Race) (Pi Values)} $$ $$ \text{P(NonDefault | Score} \geq x \text{, race) (calculated)} $$ $$ \text{P(race) (Figure 9)} $$ **For Reference, all data is from here:** ### Figure 3A: https://www.federalreserve.gov/boarddocs/rptcongress/creditscore/figtables3.htm#d3A ### Figure 7A: https://www.federalreserve.gov/boarddocs/rptcongress/creditscore/figtables7.htm#d7A ### Figure 6A: https://www.federalreserve.gov/boarddocs/rptcongress/creditscore/figtables6.htm#d6A ### Figure 9A: https://www.federalreserve.gov/boarddocs/rptcongress/creditscore/datamodel_tables.htm ``` import pandas as pd import numpy as np %matplotlib inline ``` ** For Naming Scheme Reference: ** - LEq: <= - GEq: >= - S: Score - D: Default - ND: NonDefault - R: Race - Eq: = ``` ProbNDGivenSEqXAndR = 1 - (pd.read_csv("Figure6A.csv").set_index("Score") / 100) ProbSLeqXGivenDAndNDAndR = pd.read_csv("Figure7A-fixed.csv").set_index("Score") / 100 ProbSLeqXGivenR = pd.read_csv("Figure3A.csv").set_index("Score") / 100 ProbSEqXGivenDAndNDAndR = ProbSLeqXGivenDAndNDAndR.diff().fillna(value=ProbSLeqXGivenDAndNDAndR.loc[0]) ProbSEqXGivenR = ProbSLeqXGivenR.diff().fillna(value=ProbSLeqXGivenR.loc[0]) testdf = pd.DataFrame( data=[0.02, 0.01, 0.03] ) testdf.iloc[::-1].cumsum()[::-1] ``` *** ## Calculating P(NonDefault | Race) - Pi Values ### Step 1: Caclulate : $$ \text{P(Score} = x \text{| Default, race), and}$$ $$ \text{P(Score} = x \text{| NonDefault, race)}$$ ``` ProbSEqXGivenDAndR = ProbSEqXGivenDAndNDAndR[['White (Default)', 'Black (Default)', 'Hispanic (Default)', 'Asian (Default)']] ProbSEqXGivenNDAndR = ProbSEqXGivenDAndNDAndR[['White (NonDefault)', 'Black (NonDefault)', 'Hispanic (NonDefault)', 'Asian (NonDefault)']] ProbSEqXGivenNDAndR.head() ProbSEqXGivenDAndR.head() ProbNDGivenSEqXAndR.head() ProbSEqXGivenNDAndR.columns = ['White', 'Black', 'Hispanic', 'Asian'] ProbSEqXGivenDAndR.columns = ['White', 'Black', 'Hispanic', 'Asian'] def getPi(raceName): return (-ProbNDGivenSEqXAndR[[raceName]] * ProbSEqXGivenDAndR[[raceName]])/((ProbSEqXGivenNDAndR[[raceName]] * ProbNDGivenSEqXAndR[[raceName]]) - (ProbNDGivenSEqXAndR[[raceName]] * ProbSEqXGivenDAndR[[raceName]]) - ProbSEqXGivenNDAndR[[raceName]]) WhitePis = getPi('White') BlackPis = getPi('Black') AsianPis = getPi('Asian') HispanicPis = getPi('Hispanic') WhitePis[np.abs(WhitePis.White-WhitePis.White.mean()) <= (0.2*WhitePis.White.std())][1:].plot() def getMedianAndMiddle(dataSet, Name, delta): pis = dataSet[np.abs(dataSet[[Name]]-dataSet[[Name]].mean()) <= (0.2*dataSet[[Name]].std())] length = len(pis) middle = pis.iloc[(int)(length/2.0) + delta] median = pis.median() return (middle,median) getMedianAndMiddle(WhitePis, 'White', 1) getMedianAndMiddle(BlackPis, 'Black', 0) getMedianAndMiddle(AsianPis, 'Asian', 1) getMedianAndMiddle(HispanicPis, 'Hispanic', 1)[1].values[0] piValues = [getMedianAndMiddle(WhitePis, 'White', 1)[1].values[0], getMedianAndMiddle(BlackPis, 'Black', 0)[1].values[0], getMedianAndMiddle(AsianPis, 'Asian', 1)[1].values[0], getMedianAndMiddle(HispanicPis, 'Hispanic', 1)[1].values[0]] pis = pd.DataFrame( data=[piValues], columns=['white', 'black', 'asian', 'hispanic'] ) pis # test right now # piValues=[0.758674, 0.336551, 0.806850, 0.568113] # pis = pd.DataFrame( # data=[piValues], # columns=['white', 'black', 'asian', 'hispanic'] # ) # pis ``` *** ``` # I'm testing for what the pi values should be here # Theoretically P(s=x|race) * P(ND|s=x) / P(s=x|ND) == pi (P(ND|race)) ((ProbSEqXGivenR * ProbNDGivenSEqXAndR) / ProbSEqXGivenNDAndR).replace([np.inf, -np.inf], np.nan).dropna().plot() ((ProbSEqXGivenR * ProbNDGivenSEqXAndR) / ProbSEqXGivenNDAndR).replace([np.inf, -np.inf], np.nan).dropna().mean() ``` *** # Sensitivity: P(S>=x | NonDefault, race) ** They calculate this in the tutorial manually, but checking here to cross reference ** ``` ProbSEqXGivenNDAndR.iloc[::-1].cumsum()[::-1].plot() ProbSEqXGivenNDAndR.iloc[::-1].cumsum()[::-1].head() ``` *** # Precision: P(NonDefault | Score >= x) ### Here: P(NonDefault | Score >= x, race) ``` ProbNDGivenSGEqXAndR = (((ProbSEqXGivenR * ProbNDGivenSEqXAndR).iloc[::-1].cumsum()[::-1]) / (ProbSEqXGivenR.iloc[::-1].cumsum()[::-1])).fillna(value=0) ProbNDGivenSGEqXAndR.head() ``` *** ## Creating P(race) ``` sizes = [133165, 18274, 14702, 7906] total = sum(sizes) ProbOfBeingRace = pd.DataFrame( { 'Demographic' : ['white', 'black', 'hispanic', 'asian'], 'P(race)' : [sizes[0]/total, sizes[1]/total, sizes[2]/total, sizes[3]/total] }, columns=["Demographic", "P(race)"] ) ``` *** ## Checking Final Answers for Tutorial w/ new values ``` sensitivities = ProbSEqXGivenNDAndR.iloc[::-1].cumsum()[::-1].round(2) totalDF = pd.DataFrame({ 'sensitivity': np.arange(0.0, 1.01, 0.01).tolist() }) # function to format the threshold scores to match the sensitivity value at the index def getScoreArray(race, data): scores = [None] * 101 for index, row in data.iterrows(): sens = data.loc[index][race] if(len(totalDF[totalDF['sensitivity'] == sens].index.values) >= 1): i = totalDF[totalDF['sensitivity'] == sens].index.values[0] scores[i] = index return scores demographics = ['White', 'Black', 'Asian', 'Hispanic'] for demographic in demographics: totalDF['t_' + demographic] = getScoreArray(demographic, sensitivities[[demographic]]) totalDF.set_index('sensitivity') def getPrecisionOrder(t_race, dataPrecision): prec = [] for i in range(len(totalDF)): if(totalDF[t_race][i] != None): currPrec = dataPrecision[totalDF[t_race][i]] if(isinstance(currPrec, np.ndarray)): currPrec = 0 prec.append(currPrec) return prec precision = ProbNDGivenSGEqXAndR for demographic in demographics: tmp = precision[demographic] * ProbOfBeingRace.set_index('Demographic').loc[demographic.lower()]['P(race)'] totalDF[demographic[0] + '_prec'] = getPrecisionOrder('t_' + demographic, tmp) totalDF.set_index('sensitivity', inplace=True) totalDF['total_prec'] = totalDF[['W_prec', 'B_prec', 'A_prec', 'H_prec']].sum(axis=1) closestPrecision = min(totalDF["total_prec"], key=lambda x:abs(x-0.82)) totalDF[totalDF['total_prec'] == closestPrecision] ``` *** ### Creating the CSVs for the Tutorial ``` ProbSEqXGivenR.to_csv('NEW_ProbSEqXGivenR.csv') pis.set_index('white').to_csv('NEW_pis.csv') ProbNDGivenSGEqXAndR.to_csv('NEW_ProbNDGivenSGEqXAndR.csv') ProbOfBeingRace.set_index('Demographic').to_csv('NEW_ProbR.csv') ```
github_jupyter
``` #hide #default_exp dev.docs ``` # Documentation This notebook documents the documentation utility functions developed for disseminating this research <br> ### Imports ``` #exports import json import numpy as np import pandas as pd import junix from html.parser import HTMLParser from nbdev.export2html import convert_md import os import re import codecs from tqdm import tqdm from warnings import warn ``` <br> ### User Inputs ``` dev_nbs_dir = '../nbs' docs_dir = '../docs' docs_nb_img_dir = f'{docs_dir}/img/nbs' ``` <br> ### Converting the Notebooks to Documentation We'll first convert the notebooks to markdown ``` #exports def convert_file_to_json(filepath): with open(filepath, 'r', encoding='utf8') as f: contents = f.read() f.close() return json.loads(contents) junix.exporter.convert_file_to_json = convert_file_to_json def encode_file_as_utf8(fp, open_encoding=None, retry_count=0): if retry_count >= 5: raise ValueError('Have exceeded maximum number of retries') try: with codecs.open(fp, 'r', encoding=open_encoding) as file: contents = file.read(1048576) file.close() if not contents: pass else: with codecs.open(fp, 'w', 'utf-8') as file: file.write(contents) except: encode_file_as_utf8(fp, open_encoding='utf-8', retry_count=retry_count+1) def convert_nb_to_md(nb_file, nbs_dir, docs_nb_img_dir, docs_dir): if os.path.exists(docs_nb_img_dir) is False: os.makedirs(docs_nb_img_dir) nb_fp = f'{nbs_dir}/{nb_file}' junix.export_images(nb_fp, docs_nb_img_dir) convert_md(nb_fp, docs_dir, img_path=f'{docs_nb_img_dir}/', jekyll=False) md_fp = docs_dir + '/'+ nb_file.replace('.ipynb', '') + '.md' encode_file_as_utf8(md_fp) nb_file = '01-utils.ipynb' convert_nb_to_md(nb_file, dev_nbs_dir, docs_nb_img_dir, docs_dir) ``` <br> We'll then parse the HTML tables into markdown ``` #exports class MyHTMLParser(HTMLParser): def __init__(self): super().__init__() self.tags = [] def handle_starttag(self, tag, attrs): self.tags.append(self.get_starttag_text()) def handle_endtag(self, tag): self.tags.append(f"</{tag}>") get_substring_idxs = lambda string, substring: [num for num in range(len(string)-len(substring)+1) if string[num:num+len(substring)]==substring] def convert_df_to_md(df): idx_col = df.columns[0] df = df.set_index(idx_col) if not isinstance(df.index.name, str): df.index.name = df.index.name[-1] df.columns = [col[0] if not isinstance(col, str) else col for col in df.columns] table_md = df.to_markdown() return table_md def remove_empty_index_col(df): if 'Unnamed: 0' not in df.columns: return df if (df['Unnamed: 0']==pd.Series(range(df.shape[0]), name='Unnamed: 0')).mean()==1: df = df.drop(columns=['Unnamed: 0']) return df def extract_div_to_md_table(start_idx, end_idx, table_and_div_tags, file_txt): n_start_divs_before = table_and_div_tags[:start_idx].count('<div>') n_end_divs_before = table_and_div_tags[:end_idx].count('</div>') div_start_idx = get_substring_idxs(file_txt, '<div>')[n_start_divs_before-1] div_end_idx = get_substring_idxs(file_txt, '</div>')[n_end_divs_before] div_txt = file_txt[div_start_idx:div_end_idx] potential_dfs = pd.read_html(div_txt) assert len(potential_dfs) == 1, 'Multiple tables were found when there should be only one' df = potential_dfs[0] df = remove_empty_index_col(df) md_table = convert_df_to_md(df) return div_txt, md_table def extract_div_to_md_tables(md_fp): with open(md_fp, 'r', encoding='utf-8') as f: file_txt = f.read() parser = MyHTMLParser() parser.feed(file_txt) table_and_div_tags = [tag for tag in parser.tags if tag in ['<div>', '</div>', '<table border="1" class="dataframe">', '</table>']] table_start_tag_idxs = [i for i, tag in enumerate(table_and_div_tags) if tag=='<table border="1" class="dataframe">'] table_end_tag_idxs = [table_start_tag_idx+table_and_div_tags[table_start_tag_idx:].index('</table>') for table_start_tag_idx in table_start_tag_idxs] div_to_md_tables = [] for start_idx, end_idx in zip(table_start_tag_idxs, table_end_tag_idxs): div_txt, md_table = extract_div_to_md_table(start_idx, end_idx, table_and_div_tags, file_txt) div_to_md_tables += [(div_txt, md_table)] return div_to_md_tables def clean_md_file_tables(md_fp): div_to_md_tables = extract_div_to_md_tables(md_fp) with open(md_fp, 'r', encoding='utf-8') as f: md_file_text = f.read() for div_txt, md_txt in div_to_md_tables: md_file_text = md_file_text.replace(div_txt, md_txt) with open(md_fp, 'w', encoding='utf-8') as f: f.write(md_file_text) return md_fp = '../docs/01-utils.md' clean_md_file_tables(md_fp) ``` <br> We'll add a short function for cleaning the progress bar output ``` #exports def clean_progress_bars(md_fp, dodgy_char='â–ˆ'): with open(md_fp, 'r', encoding='utf-8') as f: md_file_text = f.read() md_file_text = md_file_text.replace(f'|{dodgy_char}', '').replace(f'{dodgy_char}|', '').replace(dodgy_char, '') with open(md_fp, 'w', encoding='utf-8') as f: f.write(md_file_text) return clean_progress_bars(md_fp) ``` <br> We'll also correct the filepaths of the notebook images ``` #exports def correct_png_name(incorrect_png_name, md_fp): cell, output = incorrect_png_name.split('_')[1:] filename = md_fp.split('/')[-1][:-3] corrected_png_name = f"{filename}_cell_{int(cell)+1}_output_{output}" return corrected_png_name get_nb_naive_png_names = lambda img_dir: [f[:-4] for f in os.listdir(img_dir) if f[:6]=='output'] def specify_nb_in_img_fp(md_fp, img_dir='img/nbs'): nb_naive_png_names = get_nb_naive_png_names(img_dir) nb_specific_png_names = [correct_png_name(nb_naive_png_name, md_fp) for nb_naive_png_name in nb_naive_png_names] for nb_naive_png_name, nb_specific_png_name in zip(nb_naive_png_names, nb_specific_png_names): old_img_fp = f'{img_dir}/{nb_naive_png_name}.png' new_img_fp = f'{img_dir}/{nb_specific_png_name}.png' os.remove(new_img_fp) if os.path.exists(new_img_fp) else None os.rename(old_img_fp, new_img_fp) specify_nb_in_img_fp(md_fp, img_dir=docs_nb_img_dir) ``` <br> And finally clean the filepaths and filenames for any images in the notebooks ``` #exports def get_filename_correction_map(md_file_text, md_fp): png_idxs = [png_str.start() for png_str in re.finditer('.png\)', md_file_text)] png_names = [md_file_text[:png_idx].split('/')[-1] for png_idx in png_idxs] filename_correction_map = { f'{png_name}.png': f'{correct_png_name(png_name, md_fp)}.png' for png_name in png_names if png_name[:6] == 'output' } return filename_correction_map def clean_md_text_img_fps(md_file_text, md_fp): md_file_text = md_file_text.replace('../docs/img/nbs', 'img/nbs') filename_correction_map = get_filename_correction_map(md_file_text, md_fp) for incorrect_name, correct_name in filename_correction_map.items(): md_file_text = md_file_text.replace(incorrect_name, correct_name) return md_file_text def clean_md_files_img_fps(md_fp): with open(md_fp, 'r', encoding='utf-8') as f: md_file_text = f.read() md_file_text = clean_md_text_img_fps(md_file_text, md_fp) with open(md_fp, 'w', encoding='utf-8') as f: f.write(md_file_text) return clean_md_file_tables(md_fp) clean_progress_bars(md_fp) specify_nb_in_img_fp(md_fp, img_dir=docs_nb_img_dir) clean_md_files_img_fps(md_fp) #exports def convert_and_clean_nb_to_md(nbs_dir, docs_nb_img_dir, docs_dir): nb_files = [f for f in os.listdir(nbs_dir) if f[-6:]=='.ipynb' and f!='00-documentation.ipynb'] for nb_file in tqdm(nb_files): convert_nb_to_md(nb_file, nbs_dir, docs_nb_img_dir, docs_dir) md_fp = docs_dir + '/' + nb_file.replace('ipynb', 'md') clean_md_file_tables(md_fp) clean_progress_bars(md_fp) specify_nb_in_img_fp(md_fp, img_dir=docs_nb_img_dir) clean_md_files_img_fps(md_fp) for nb_dir in [dev_nbs_dir]: convert_and_clean_nb_to_md(nb_dir, docs_nb_img_dir, docs_dir) ```
github_jupyter
<a href="https://colab.research.google.com/github/JiaminJIAN/20MA573/blob/master/src/Volatility%20smile.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Volatility smile Volatility smiles are implied volatility patterns that arise in pricing financial options. It corresponds to finding one single parameter (implied volatility) that is needed to be modified for the Black-Scholes formula to fit market prices. Graphing implied volatilities against strike prices for a given expiry yields a skewed "smile" instead of the expected flat surface. Next, we shall demonstrate volatility smiles by computing implied volatility to multiple market option prices. For instance, we can fix the maturity, and compute volatilities for different strikes. If we plot a strike versus vol figure , we shall see the smily face there. - copy/paste/upload data from [here](https://github.com/songqsh/20s_ma573/blob/master/src/20optiondata2.dat) ``` import matplotlib.pyplot as plt import numpy as np import scipy.optimize as so import scipy.stats as ss ``` - Read data from .dat file. It has call option prices of - maturities 2 months and 5 months; - strikes of 97, 99, 101, 103 ``` '''====== Read data =========''' #Read four-column data #columns are otype, maturity, strike, option_price np_option_data1 = np.loadtxt('20optiondata2.dat', comments='#', delimiter=',') print('>>>>>>otype, maturity, strike, option_price') print(np_option_data1) '''========= option class init ==========''' class VanillaOption: def __init__( self, otype = 1, # 1: 'call' # -1: 'put' strike = 110., maturity = 1., market_price = 10.): self.otype = otype self.strike = strike self.maturity = maturity self.market_price = market_price #this will be used for calibration def payoff(self, s): #s: excercise price otype = self.otype k = self.strike maturity = self.maturity return max([0, (s - k)*otype]) '''============ Gbm class =============''' class Gbm: def __init__(self, init_state = 100., drift_ratio = .0475, vol_ratio = .2 ): self.init_state = init_state self.drift_ratio = drift_ratio self.vol_ratio = vol_ratio '''======== Black-Scholes-Merton formula. ==========''' def bsm_price(self, vanilla_option): s0 = self.init_state sigma = self.vol_ratio r = self.drift_ratio otype = vanilla_option.otype k = vanilla_option.strike maturity = vanilla_option.maturity d1 = (np.log(s0 / k) + (r + 0.5 * sigma ** 2) * maturity) / (sigma * np.sqrt(maturity)) d2 = d1 - sigma * np.sqrt(maturity) return (otype * s0 * ss.norm.cdf(otype * d1) #line break needs parenthesis - otype * np.exp(-r * maturity) * k * ss.norm.cdf(otype * d2)) Gbm.bsm_price = bsm_price '''================ define an error function ====================''' def error_function(vol, gbm, option): gbm.vol_ratio = vol return abs(option.market_price - gbm.bsm_price(option)) '''========== define a method to seek for an implied volatility ============''' import scipy.optimize as so def implied_volatility(gbm, option): init_vol = .1 #initial guess return so.fmin(error_function, init_vol, args = (gbm, option), disp = 0)[0] '''============== below defines for underlying process =================''' gbm1 = Gbm( init_state = 100., #market data drift_ratio = .05, #market data vol_ratio = .1 #initial guess ) '''==================== create option_list from the data =======================''' num_row = np_option_data1.shape[0] option_list = [] for i in range(num_row): option1 = VanillaOption( otype = np_option_data1[i,0], strike = np_option_data1[i,2], maturity = np_option_data1[i,1], market_price = np_option_data1[i,3] ) option_list.append(option1) #expand one column for vol np_option_data2 = np.append(np_option_data1, np.zeros([num_row,1]), axis = 1) #compute implied vols and add them into the last column for i in range(num_row): np_option_data2[i,4] = implied_volatility(gbm1, option_list[i]) print('>>>>>>otype, maturity, strike, option_price, implied vol') print(np_option_data2) filter1 = np_option_data2[np_option_data2[:,1] == 2/12] plt.plot(filter1[:,2], filter1[:,4], label = '2 mon maturity') filter2 = np_option_data2[np_option_data2[:,1] == 5/12] plt.plot(filter2[:,2], filter2[:,4], label = '5 mon maturity') plt.ylabel('implied vol') plt.xlabel('strike') plt.legend(); ```
github_jupyter
# 머신 러닝 교과서 3판 # 네이버 영화 리뷰 감성 분류 ``` # 코랩에서 실행할 경우 최신 버전의 사이킷런을 설치합니다. !pip install --upgrade scikit-learn ``` IMDb 영화 리뷰 데이터셋과 비슷한 네이버 영화 리뷰 데이터셋(https://github.com/e9t/nsmc)을 사용해 한글 문장의 감성 분류 예제를 다루어 보겠습니다. 이 데이터는 네이버 영화 사이트에 있는 리뷰 20만 개를 모은 것입니다. 네이버 영화 리뷰 데이터셋 깃허브에서 직접 데이터를 다운로드 받아도 되지만 편의를 위해 이 책의 깃허브의 `ch09` 폴더에 데이터셋을 넣어 놓았습니다. 20만개 데이터 중 15만개는 훈련 데이터셋으로 `ratings_train.txt` 파일에 저장되어 있고 5만개는 테스트 데이터셋으로 `ratings_test.txt` 파일에 저장되어 있습니다. 리뷰의 길이는 140을 넘지 않습니다. 부정 리뷰는 1\~4까지 점수를 매긴 리뷰이고 긍정 리뷰는 6\~10까지 점수를 매긴 리뷰입니다. 훈련 데이터셋과 테스트 데이터셋의 부정과 긍정 리뷰는 약 50%씩 구성되어 있습니다. 한글은 영어와 달리 조사와 어미가 발달해 있기 때문에 BoW나 어간 추출보다 표제어 추출 방식이 적합합니다. 이런 작업을 형태소 분석이라 부릅니다. 파이썬에서 한글 형태소 분석을 하기 위한 대표적인 패키지는 `konlpy`와 `soynlp`입니다. 두 패키지를 모두 사용해 네이버 영화 리뷰를 긍정과 부정으로 분류해 보겠습니다. 먼저 이 예제를 실행하려면 `konlpy`와 `soynlp`가 필요합니다. 다음 명령을 실행해 두 패키지를 설치해 주세요. ``` !pip install konlpy soynlp ``` 최신 tweepy를 설치할 경우 StreamListener가 없다는 에러가 발생(https://github.com/tweepy/tweepy/issues/1531) 하므로 3.10버전을 설치해 주세요. ``` !pip install tweepy==3.10 ``` 그다음 `konlpy`, `pandas`, `numpy`를 임포트합니다. ``` import konlpy import pandas as pd import numpy as np ``` 코랩을 사용하는 경우 다음 코드 셀을 실행하세요. ``` !wget https://github.com/rickiepark/python-machine-learning-book-3rd-edition/raw/master/ch08/ratings_train.txt -O ratings_train.txt ``` 감성 분류를 시작하기 전에 훈련 데이터셋과 테스트 데이터셋을 각각 판다스 데이터프레임으로 읽은 후 넘파이 배열로 준비하겠습니다. 먼저 훈련 데이터셋부터 읽어 보죠. `ratings_train.txt` 파일은 하나의 리뷰가 한 행을 구성하며 각 필드는 탭으로 구분되어 있기 때문에 판다스의 `read_csv()` 함수로 간편하게 읽어 들일 수 있습니다. `read_csv()`는 기본적으로 콤마를 기준으로 필드를 구분하므로 `delimiter='\t'`으로 지정하여 탭으로 변경합니다. 기본적으로 판다스는 빈 문자열을 NaN으로 인식합니다. 빈 문자열을 그대로 유지하기 위해 `keep_default_na` 매개변수를 `False`로 지정합니다. ``` df_train = pd.read_csv('ratings_train.txt', delimiter='\t', keep_default_na=False) ``` 데이터프레임의 `head()` 메서드를 호출하면 처음 5개의 행을 출력해 줍니다. 이 예제에서 사용할 데이터는 document 열과 label 열입니다. label은 리뷰가 긍정(1)인지 부정(0)인지를 나타내는 값입니다. ``` df_train.head() ``` 데이터프레임의 열을 선택하여 `Series` 객체의 `values` 속성을 사용하면 document 열과 label 열을 넘파이 배열로 저장할 수 있습니다. 각각 훈련 데이터셋의 특성과 타깃 값으로 저장합니다. ``` X_train = df_train['document'].values y_train = df_train['label'].values ``` 코랩을 사용하는 경우 다음 코드 셀을 실행하세요. ``` !wget https://github.com/rickiepark/python-machine-learning-book-3rd-edition/raw/master/ch08/ratings_test.txt -O ratings_test.txt ``` `ratings_test.txt` 파일에 대해서도 동일한 작업을 수행합니다. ``` df_test = pd.read_csv('ratings_test.txt', delimiter='\t', keep_default_na=False) X_test = df_test['document'].values y_test = df_test['label'].values ``` 훈련 데이터셋과 테스트 데이터셋의 크기를 확인해 보죠. 각각 150,000개와 50,000개의 샘플을 가지고 있고 양성 클래스와 음성 클래스의 비율은 거의 50%에 가깝습니다. ``` print(len(X_train), np.bincount(y_train)) print(len(X_test), np.bincount(y_test)) ``` 훈련 데이터셋과 테스트 데이터셋을 준비했으므로 형태소 분석기를 사용해 본격적인 감성 분류 작업을 시작해 보겠습니다. `konlpy`는 5개의 한국어 형태소 분석기를 파이썬 클래스로 감싸서 제공하는 래퍼 패키지입니다. `konlpy`가 제공하는 형태소 분석기에 대한 자세한 내용은 온라인 문서(https://konlpy.org/ko/latest/)를 참고하세요. 이 예에서는 스칼라로 개발된 open-korean-text 한국어 처리기(https://github.com/open-korean-text/open-korean-text)를 제공하는 `Okt` 클래스를 사용해 보겠습니다. open-korean-text는 비교적 성능이 높고 별다른 설치 없이 구글 코랩에서도 바로 사용할 수 있습니다. `konlpy.tag` 패키지에서 `Okt` 클래스를 임포트하고 객체를 만든 다음 훈련 데이터셋에 있는 문장 하나를 `morphs()` 메서드로 형태소로 나누어 보겠습니다. ``` from konlpy.tag import Okt okt = Okt() print(X_train[4]) print(okt.morphs(X_train[4])) ``` 한글 문장에서 조사와 어미가 잘 구분되어 출력된 것을 볼 수 있습니다. '사이몬페그'와 같은 고유 명사는 처리하는데 어려움을 겪고 있네요. 완벽하지는 않지만 이 클래스를 사용해 분류 문제를 풀어 보겠습니다. `TfidfVectorzier`는 기본적으로 공백을 기준으로 토큰을 구분하지만 `tokenizer` 매개변수에 토큰화를 위한 사용자 정의 함수를 전달할 수 있습니다. 따라서 앞서 테스트했던 `okt.morphs` 메서드를 전달하면 형태소 분석을 통해 토큰화를 수행할 수 있습니다. `tokenizer` 매개변수를 사용할 때 패턴`token_pattern=None`으로 지정하여 `token_pattern` 매개변수가 사용되지 않는다는 경고 메시지가 나오지 않게 합니다. `TfidfVectorzier`을 `ngram_range=(1, 2)`로 설정하여 유니그램과 바이그램을 사용하고 `min_df=3`으로 지정하여 3회 미만으로 등장하는 토큰은 무시합니다. 또한 `max_df=0.9`로 두어 가장 많이 등장하는 상위 10%의 토큰도 무시하겠습니다. 이런 작업이 불용어로 생각할 수 있는 토큰을 제거할 것입니다. 컴퓨팅 파워가 충분하다면 하이퍼파라미터 탐색 단계에서 `TfidfVectorzier`의 매개변수도 탐색해 보는 것이 좋습니다. 여기에서는 임의의 매개변수 값을 지정하여 데이터를 미리 변환하고 하이퍼파라미터 탐색에서는 분류기의 매개변수만 탐색하겠습니다. 노트: 토큰 데이터를 생성하는 시간이 많이 걸리므로 주피터 노트북에서는 다음 번 실행 때 이 과정을 건너 뛸 수 있도록 이 데이터를 한 번 생성하여 npz 파일로 저장합니다. ``` import os from scipy.sparse import save_npz, load_npz from sklearn.feature_extraction.text import TfidfVectorizer if not os.path.isfile('okt_train.npz'): tfidf = TfidfVectorizer(ngram_range=(1, 2), min_df=3, max_df=0.9, tokenizer=okt.morphs, token_pattern=None) tfidf.fit(X_train) X_train_okt = tfidf.transform(X_train) X_test_okt = tfidf.transform(X_test) save_npz('okt_train.npz', X_train_okt) save_npz('okt_test.npz', X_test_okt) else: X_train_okt = load_npz('okt_train.npz') X_test_okt = load_npz('okt_test.npz') ``` `X_train_okt`와 `X_test_okt`가 준비되었으므로 `SGDClassifier` 클래스를 사용해 감성 분류 문제를 풀어 보겠습니다. 탐색할 `SGDClassifier`의 매개변수는 규제를 위한 `alpha` 매개변수입니다. `RandomizedSearchCV` 클래스를 사용하기 위해 `loguniform` 함수로 탐색 범위를 지정하겠습니다. 여기에서는 `SGDClassifier`의 손실 함수로 로지스틱 손실(`'log'`)을 사용하지만 다른 손실 함수를 매개변수 탐색에 포함할 수 있습니다. 총 반복 회수(`n_iter`)는 50회로 지정합니다. 만약 CPU 코어가 여러개라면 `n_jobs` 매개변수를 1 이상으로 설정하여 수행 속도를 높일 수 있습니다. ``` from sklearn.model_selection import RandomizedSearchCV from sklearn.linear_model import SGDClassifier from sklearn.utils.fixes import loguniform sgd = SGDClassifier(loss='log', random_state=1) param_dist = {'alpha': loguniform(0.0001, 100.0)} rsv_okt = RandomizedSearchCV(estimator=sgd, param_distributions=param_dist, n_iter=50, random_state=1, verbose=1) rsv_okt.fit(X_train_okt, y_train) ``` 하이퍼파라미터 탐색으로 찾은 최상의 점수와 매개변수 값을 확인해 보죠. ``` print(rsv_okt.best_score_) print(rsv_okt.best_params_) ``` 테스트 데이터셋 `X_test_okt`에서 점수도 확인해 보겠습니다. ``` rsv_okt.score(X_test_okt, y_test) ``` 약 82%의 정확도를 냈습니다. 간단한 작업으로 꽤 좋은 성능을 냈습니다. `konlpy`의 다른 형태소 분석 클래스를 사용하거나 `SGDClassifier` 외에 다른 분류기를 시도하지 않을 이유는 없습니다. 충분한 컴퓨팅 파워가 없다면 사이킷런 0.24버전에서 추가되는 `HalvingRandomSearchCV` 클래스를 사용해 볼 수도 있습니다. 이번에는 또 다른 파이썬 형태소 분석기인 `soynlp`를 사용해 보겠습니다. `soynlp`는 순수하게 파이썬으로 구현된 형태소 분석 패키지입니다. 깃허브(https://github.com/lovit/soynlp)에는 소스 코드 뿐만 아니라 다양한 튜토리얼도 함께 제공합니다. `soynlp`는 3개의 토큰화 클래스를 제공합니다. 기본적으로 띄어쓰기가 잘 되어 있다면 `LTokenizer`가 잘 맞습니다. 이외에는 `MaxScoreTokenizer`와 `RegexTokenizer`가 있습니다. 이 예에서는 `LTokenizer`를 사용해 보겠습니다. 먼저 `soynlp.tokenizer`에서 `LTokenizer`를 임포트합니다. ``` from soynlp.tokenizer import LTokenizer ``` `LTokenizer` 클래스의 객체를 만든다음 앞에서와 같이 훈련 데이터셋에 있는 샘플(`X_train[4]`) 하나의 형태소를 분석해 보겠습니다. ``` lto = LTokenizer() print(lto.tokenize(X_train[4])) ``` `soynlp`는 말뭉치의 통계 데이터를 기반으로 동작하기 때문에 기본 `LTokenizer` 객체로는 공백으로만 토큰화를 수행합니다. `LTokenizer`에 필요한 통계 데이터를 생성하기 위해서 `WordExtractor`를 사용해 보겠습니다. ``` from soynlp.word import WordExtractor ``` `WordExtractor` 객체를 만든 후 `train()` 메서드에 `X_train`을 전달하여 훈련합니다. 훈련이 끝나면 `word_scores()` 메서드에서 단어의 점수를 얻을 수 있습니다. 반환된 `scores` 객체는 단어마다 결합 점수(cohesion score)와 브랜칭 엔트로피(branching entropy)를 가진 딕셔너리입니다. ``` word_ext = WordExtractor() word_ext.train(X_train) scores = word_ext.word_scores() ``` `soynlp` 깃허브의 튜토리얼(https://github.com/lovit/soynlp/blob/master/tutorials/wordextractor_lecture.ipynb)을 따라 결합 점수(`cohesion_forward`)와 브랜칭 엔트로피(`right_branching_entropy`)에 지수를 취한 값에 곱하여 최종 점수를 만들겠습니다. ``` import math score_dict = {key: scores[key].cohesion_forward * math.exp(scores[key].right_branching_entropy) for key in scores} ``` 이제 이 점수를 `LTokenizer`의 `scores` 매개변수로 전달하여 객체를 만들고 앞에서 테스트한 샘플에 다시 적용해 보겠습니다. ``` lto = LTokenizer(scores=score_dict) print(lto.tokenize(X_train[4])) ``` 단어 점수를 활용했기 때문에 토큰 추출이 훨씬 잘 된 것을 볼 수 있습니다. `lto.tokenizer` 메서드를 `TfidVectorizer` 클래스에 전달하여 `konlpy`를 사용했을 때와 같은 조건으로 훈련 데이터셋과 테스트 데이터셋을 변환해 보겠습니다. ``` if not os.path.isfile('soy_train.npz'): tfidf = TfidfVectorizer(ngram_range=(1, 2), min_df=3, max_df=0.9, tokenizer=lto.tokenize, token_pattern=None) tfidf.fit(X_train) X_train_soy = tfidf.transform(X_train) X_test_soy = tfidf.transform(X_test) save_npz('soy_train.npz', X_train_soy) save_npz('soy_test.npz', X_test_soy) else: X_train_soy = load_npz('soy_train.npz') X_test_soy = load_npz('soy_test.npz') ``` 동일한 `SGDClassifier` 객체와 매개변수 분포를 지정하고 하이퍼파라미터 탐색을 수행해 보겠습니다. ``` rsv_soy = RandomizedSearchCV(estimator=sgd, param_distributions=param_dist, n_iter=50, random_state=1, verbose=1) rsv_soy.fit(X_train_soy, y_train) ``` `soynlp`를 사용했을 때 최상의 점수와 매개변수는 다음과 같습니다. ``` print(rsv_soy.best_score_) print(rsv_soy.best_params_) ``` 마지막으로 테스트 데이터셋에 대한 점수를 확인해 보겠습니다. ``` rsv_soy.score(X_test_soy, y_test) ``` `Okt`를 사용했을 때 보다는 조금 더 낮지만 약 81% 이상의 정확도를 얻었습니다.
github_jupyter
## Homework01: Three headed network in PyTorch This notebook accompanies the [week02 seminar](https://github.com/ml-mipt/ml-mipt/blob/advanced/week02_CNN_n_Vanishing_gradient/week02_CNN_for_texts.ipynb). Refer to that notebook for more comments. All the preprocessing is the same as in the classwork. *Including the data leakage in the train test split (it's still for bonus points).* ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline import nltk import tqdm from collections import Counter ``` If you have already downloaded the data on the Seminar, simply run through the next cells. Otherwise uncomment the next cell (and comment the another one ;) ``` # uncomment and run this cell, if you don't have data locally yet. # !curl -L https://www.dropbox.com/s/5msc5ix7ndyba10/Train_rev1.csv.tar.gz?dl=1 -o Train_rev1.csv.tar.gz # !tar -xvzf ./Train_rev1.csv.tar.gz # data = pd.read_csv("./Train_rev1.csv", index_col=None) # wget https://raw.githubusercontent.com/ml-mipt/ml-mipt/advanced/homeworks/homework1_three_headed_network/network.py # run this cell if you have downloaded the dataset on the seminar data = pd.read_csv("../../week02_CNN_n_Vanishing_gradient/Train_rev1.csv", index_col=None) data['Log1pSalary'] = np.log1p(data['SalaryNormalized']).astype('float32') text_columns = ["Title", "FullDescription"] categorical_columns = ["Category", "Company", "LocationNormalized", "ContractType", "ContractTime"] target_column = "Log1pSalary" data[categorical_columns] = data[categorical_columns].fillna('NaN') # cast missing values to string "NaN" data.sample(3) data_for_autotest = data[-5000:] data = data[:-5000] tokenizer = nltk.tokenize.WordPunctTokenizer() # see task above def normalize(text): text = str(text).lower() return ' '.join(tokenizer.tokenize(text)) data[text_columns] = data[text_columns].applymap(normalize) print("Tokenized:") print(data["FullDescription"][2::100000]) assert data["FullDescription"][2][:50] == 'mathematical modeller / simulation analyst / opera' assert data["Title"][54321] == 'international digital account manager ( german )' # Count how many times does each token occur in both "Title" and "FullDescription" in total # build a dictionary { token -> it's count } from collections import Counter from tqdm import tqdm as tqdm token_counts = Counter()# <YOUR CODE HERE> for _, row in tqdm(data[text_columns].iterrows()): for string in row: token_counts.update(string.split()) # hint: you may or may not want to use collections.Counter token_counts.most_common(1)[0][1] print("Total unique tokens :", len(token_counts)) print('\n'.join(map(str, token_counts.most_common(n=5)))) print('...') print('\n'.join(map(str, token_counts.most_common()[-3:]))) assert token_counts.most_common(1)[0][1] in range(2500000, 2700000) assert len(token_counts) in range(200000, 210000) print('Correct!') min_count = 10 # tokens from token_counts keys that had at least min_count occurrences throughout the dataset tokens = [token for token, count in token_counts.items() if count >= min_count]# <YOUR CODE HERE> # Add a special tokens for unknown and empty words UNK, PAD = "UNK", "PAD" tokens = [UNK, PAD] + sorted(tokens) print("Vocabulary size:", len(tokens)) assert type(tokens) == list assert len(tokens) in range(32000, 35000) assert 'me' in tokens assert UNK in tokens print("Correct!") token_to_id = {token: idx for idx, token in enumerate(tokens)} assert isinstance(token_to_id, dict) assert len(token_to_id) == len(tokens) for tok in tokens: assert tokens[token_to_id[tok]] == tok print("Correct!") UNK_IX, PAD_IX = map(token_to_id.get, [UNK, PAD]) def as_matrix(sequences, max_len=None): """ Convert a list of tokens into a matrix with padding """ if isinstance(sequences[0], str): sequences = list(map(str.split, sequences)) max_len = min(max(map(len, sequences)), max_len or float('inf')) matrix = np.full((len(sequences), max_len), np.int32(PAD_IX)) for i,seq in enumerate(sequences): row_ix = [token_to_id.get(word, UNK_IX) for word in seq[:max_len]] matrix[i, :len(row_ix)] = row_ix return matrix print("Lines:") print('\n'.join(data["Title"][::100000].values), end='\n\n') print("Matrix:") print(as_matrix(data["Title"][::100000])) from sklearn.feature_extraction import DictVectorizer # we only consider top-1k most frequent companies to minimize memory usage top_companies, top_counts = zip(*Counter(data['Company']).most_common(1000)) recognized_companies = set(top_companies) data["Company"] = data["Company"].apply(lambda comp: comp if comp in recognized_companies else "Other") categorical_vectorizer = DictVectorizer(dtype=np.float32, sparse=False) categorical_vectorizer.fit(data[categorical_columns].apply(dict, axis=1)) ``` ### The deep learning part Once we've learned to tokenize the data, let's design a machine learning experiment. As before, we won't focus too much on validation, opting for a simple train-test split. __To be completely rigorous,__ we've comitted a small crime here: we used the whole data for tokenization and vocabulary building. A more strict way would be to do that part on training set only. You may want to do that and measure the magnitude of changes. #### Here comes the simple one-headed network from the seminar. ``` from sklearn.model_selection import train_test_split data_train, data_val = train_test_split(data, test_size=0.2, random_state=42) data_train.index = range(len(data_train)) data_val.index = range(len(data_val)) print("Train size = ", len(data_train)) print("Validation size = ", len(data_val)) def make_batch(data, max_len=None, word_dropout=0): """ Creates a keras-friendly dict from the batch data. :param word_dropout: replaces token index with UNK_IX with this probability :returns: a dict with {'title' : int64[batch, title_max_len] """ batch = {} batch["Title"] = as_matrix(data["Title"].values, max_len) batch["FullDescription"] = as_matrix(data["FullDescription"].values, max_len) batch['Categorical'] = categorical_vectorizer.transform(data[categorical_columns].apply(dict, axis=1)) if word_dropout != 0: batch["FullDescription"] = apply_word_dropout(batch["FullDescription"], 1. - word_dropout) if target_column in data.columns: batch[target_column] = data[target_column].values return batch def apply_word_dropout(matrix, keep_prop, replace_with=UNK_IX, pad_ix=PAD_IX,): dropout_mask = np.random.choice(2, np.shape(matrix), p=[keep_prop, 1 - keep_prop]) dropout_mask &= matrix != pad_ix return np.choose(dropout_mask, [matrix, np.full_like(matrix, replace_with)]) a = make_batch(data_train[:3], max_len=10) ``` But to start with let's build the simple model using only the part of the data. Let's create the baseline solution using only the description part (so it should definetely fit into the Sequential model). ``` import torch from torch import nn import torch.nn.functional as F # You will need these to make it simple class Flatten(nn.Module): def forward(self, input): return input.view(input.size(0), -1) class Reorder(nn.Module): def forward(self, input): return input.permute((0, 2, 1)) ``` To generate minibatches we will use simple pyton generator. ``` def iterate_minibatches(data, batch_size=256, shuffle=True, cycle=False, **kwargs): """ iterates minibatches of data in random order """ while True: indices = np.arange(len(data)) if shuffle: indices = np.random.permutation(indices) for start in range(0, len(indices), batch_size): batch = make_batch(data.iloc[indices[start : start + batch_size]], **kwargs) target = batch.pop(target_column) yield batch, target if not cycle: break iterator = iterate_minibatches(data_train, 3) batch, target = next(iterator) # Here is some startup code: n_tokens=len(tokens) n_cat_features=len(categorical_vectorizer.vocabulary_) hid_size=64 simple_model = nn.Sequential() simple_model.add_module('emb', nn.Embedding(num_embeddings=n_tokens, embedding_dim=hid_size)) simple_model.add_module('reorder', Reorder()) simple_model.add_module('conv1', nn.Conv1d( in_channels=hid_size, out_channels=hid_size, kernel_size=2) ) simple_model.add_module('relu1', nn.ReLU()) simple_model.add_module('adapt_avg_pool', nn.AdaptiveAvgPool1d(output_size=1)) simple_model.add_module('flatten1', Flatten()) simple_model.add_module('linear1', nn.Linear(in_features=hid_size, out_features=1)) # <YOUR CODE HERE> batch ``` __Remember!__ We are working with regression problem and predicting only one number. ``` # Try this to check your model. `torch.long` tensors are required for nn.Embedding layers. simple_model(torch.tensor(batch['FullDescription'], dtype=torch.long)) batch['FullDescription'].shape ``` And now simple training pipeline (it's commented because we've already done that in class. No need to do it again). ``` # from IPython.display import clear_output # from random import sample # epochs = 1 # model = simple_model # opt = torch.optim.Adam(model.parameters()) # loss_func = nn.MSELoss() # history = [] # for epoch_num in range(epochs): # for idx, (batch, target) in enumerate(iterate_minibatches(data_train)): # # Preprocessing the batch data and target # batch = torch.tensor(batch['FullDescription'], dtype=torch.long) # target = torch.tensor(target) # predictions = model(batch) # predictions = predictions.view(predictions.size(0)) # loss = loss_func(predictions, target)# <YOUR CODE HERE> # # train with backprop # loss.backward() # opt.step() # opt.zero_grad() # # <YOUR CODE HERE> # history.append(loss.data.numpy()) # if (idx+1)%10==0: # clear_output(True) # plt.plot(history,label='loss') # plt.legend() # plt.show() ``` ### Actual homework starts here __Your ultimate task is to code the three headed network described on the picture below.__ To make it closer to the real world, please store the network code in file `network.py` in this directory. #### Architecture Our main model consists of three branches: * Title encoder * Description encoder * Categorical features encoder We will then feed all 3 branches into one common network that predicts salary. <img src="https://github.com/yandexdataschool/nlp_course/raw/master/resources/w2_conv_arch.png" width=600px> This clearly doesn't fit into PyTorch __Sequential__ interface. To build such a network, one will have to use [__PyTorch nn.Module API__](https://pytorch.org/docs/stable/nn.html#torch.nn.Module). ``` import network # Re-run this cell if you updated the file with network source code import imp imp.reload(network) model = network.ThreeInputsNet( n_tokens=len(tokens), n_cat_features=len(categorical_vectorizer.vocabulary_), # this parameter defines the number of the inputs in the layer, # which stands after the concatenation. In should be found out by you. concat_number_of_features=<YOUR CODE HERE> ) testing_batch, _ = next(iterate_minibatches(data_train, 3)) testing_batch = [ torch.tensor(testing_batch['Title'], dtype=torch.long), torch.tensor(testing_batch['FullDescription'], dtype=torch.long), torch.tensor(testing_batch['Categorical']) ] assert model(testing_batch).shape == torch.Size([3, 1]) assert model(testing_batch).dtype == torch.float32 print('Seems fine!') ``` Now train the network for a while (100 batches would be fine). ``` # Training pipeline comes here (almost the same as for the simple_model) ``` Now, to evaluate the model it can be switched to `eval` state. ``` model.eval() def generate_submission(model, data, batch_size=256, name="", three_inputs_mode=True, **kw): squared_error = abs_error = num_samples = 0.0 output_list = [] for batch_x, batch_y in tqdm(iterate_minibatches(data, batch_size=batch_size, shuffle=False, **kw)): if three_inputs_mode: batch = [ torch.tensor(batch_x['Title'], dtype=torch.long), torch.tensor(batch_x['FullDescription'], dtype=torch.long), torch.tensor(batch_x['Categorical']) ] else: batch = torch.tensor(batch_x['FullDescription'], dtype=torch.long) batch_pred = model(batch)[:, 0].detach().numpy() output_list.append((list(batch_pred), list(batch_y))) squared_error += np.sum(np.square(batch_pred - batch_y)) abs_error += np.sum(np.abs(batch_pred - batch_y)) num_samples += len(batch_y) print("%s results:" % (name or "")) print("Mean square error: %.5f" % (squared_error / num_samples)) print("Mean absolute error: %.5f" % (abs_error / num_samples)) batch_pred = [c for x in output_list for c in x[0]] batch_y = [c for x in output_list for c in x[1]] output_df = pd.DataFrame(list(zip(batch_pred, batch_y)), columns=['batch_pred', 'batch_y']) output_df.to_csv('submission.csv', index=False) generate_submission(model, data_for_autotest, name='Submission') print('Submission file generated') ``` __To hand in this homework, please upload `network.py` file with code and `submission.csv` to the google form.__
github_jupyter
![qiskit_header.png](attachment:qiskit_header.png) ## Purity Randomized Benchmarking ## Introduction **Purity Randomized Benchmarking** is a variant of the Randomized Benchmarking (RB) method, which quantifies how *coherent* the errors are. The protocol executes the RB sequences containing Clifford gates, and then calculates the *purity* $Tr(\rho^2)$, and fits the purity result to an exponentially decaying curve. This notebook gives an example for how to use the ``ignis.verification.randomized_benchmarking`` module in order to perform purity RB. ``` #Import general libraries (needed for functions) import numpy as np import matplotlib.pyplot as plt from IPython import display #Import the RB functions import qiskit.ignis.verification.randomized_benchmarking as rb #Import the measurement mitigation functions import qiskit.ignis.mitigation.measurement as mc #Import Qiskit classes import qiskit from qiskit.providers.aer import noise from qiskit.providers.aer.noise.errors.standard_errors import depolarizing_error, coherent_unitary_error from qiskit.quantum_info import state_fidelity ``` ## Select the Parameters of the Purity RB Run First, wee need to choose the regular RB parameters: - **nseeds**: The number of seeds. For each seed you will get a separate list of output circuits. - **length_vector**: The length vector of Clifford lengths. Must be in ascending order. RB sequences of increasing length grow on top of the previous sequences. - **rb_pattern**: A list of the form [[i],[j],[k],...] or [[i,j],[k,l],...], etc. which will make simultaneous RB sequences. All the patterns should have the same dimetion, namely only 1-qubit sequences Qk or only 2-qubit sequences Qi,Qj, etc. The number of qubits is the sum of the entries. - **length_multiplier = None**: No length_multiplier for purity RB. - **seed_offset**: What to start the seeds at (e.g. if we want to add more seeds later). - **align_cliffs**: If true adds a barrier across all qubits in rb_pattern after each set of cliffords. As well as another parameter for purity RB: - **is_purity = True** In this example we run 2Q purity RB (on qubits Q0,Q1). ``` # Example of 2-qubits Purity RB #Number of qubits nQ = 2 #Number of seeds (random sequences) nseeds = 3 #Number of Cliffords in the sequence (start, stop, steps) nCliffs = np.arange(1,200,20) #2Q RB on Q0,Q1 rb_pattern = [[0,1]] ``` ## Generate Purity RB sequences We generate purity RB sequences. We start with a small example (so it doesn't take too long to run). In order to generate the purity RB sequences **rb_purity_circs**, which is a list of lists of lists of quantum circuits, we run the function `rb.randomized_benchmarking_seq`. This function returns: - **rb_purity_circs**: A list of lists of lists of circuits for the purity RB sequences (separate list for each of the $3^n$ options and for each seed). - **xdata**: The Clifford lengths (with multiplier if applicable). As well as: - **npurity**: the number of purity rb circuits (per seed) which equals to $3^n$, where $n$ is the dimension, e.g npurity=3 for 1-qubit RB, npurity=9 for 2-qubit RB. In order to generate each of the $3^n$ circuits, we need to do (per each of the $n$ qubits) either: - nothing (Pauli-$Z$), or - $\pi/2$-rotation around $x$ (Pauli-$X$), or - $\pi/2$-rotation around $y$ (Pauli-$Y$), and then measure the result. ``` rb_opts = {} rb_opts['length_vector'] = nCliffs rb_opts['nseeds'] = nseeds rb_opts['rb_pattern'] = rb_pattern rb_opts['is_purity'] = True rb_purity_circs, xdata, npurity = rb.randomized_benchmarking_seq(**rb_opts) print (npurity) ``` To illustrate, we print the circuit names for purity RB (for length=0 and seed=0): ``` for j in range(len(rb_purity_circs[0])): print (rb_purity_circs[0][j][0].name) ``` As an example, we print the circuit corresponding to the first RB sequences, for the first and last parameter. ``` for i in {0, npurity-1}: print ("circ no. ", i) print (rb_purity_circs[0][i][0]) ``` ## Define a non-coherent noise model We define a non-coherent noise model for the simulator. To simulate decay, we add depolarizing error probabilities to the CNOT gate. ``` noise_model = noise.NoiseModel() p2Q = 0.01 noise_model.add_all_qubit_quantum_error(depolarizing_error(p2Q, 2), 'cx') ``` We can execute the purity RB sequences either using a Qiskit Aer Simulator (with some noise model) or using an IBMQ provider, and obtain a list of results, `result_list`. ``` #Execute purity RB circuits backend = qiskit.Aer.get_backend('qasm_simulator') basis_gates = ['u1','u2','u3','cx'] # use U,CX for now shots = 200 purity_result_list = [] import time for rb_seed in range(len(rb_purity_circs)): for d in range(npurity): print('Executing seed %d purity %d length %d'%(rb_seed, d, len(nCliffs))) new_circ = rb_purity_circs[rb_seed][d] job = qiskit.execute(new_circ, backend=backend, noise_model=noise_model, shots=shots, basis_gates=['u1','u2','u3','cx']) purity_result_list.append(job.result()) print("Finished Simulating Purity RB Circuits") ``` ## Fit the results Calculate the *purity* $Tr(\rho^2)$ as the sum $\sum_k \langle P_k \rangle ^2/2^n$, and fit the purity result against an exponentially decaying function to obtain $\alpha$. ``` rbfit_purity = rb.PurityRBFitter(purity_result_list, npurity, xdata, rb_opts['rb_pattern']) ``` Print the fit result (separately for each pattern): ``` print ("fit:", rbfit_purity.fit) ``` ## Plot the results and the fit ``` plt.figure(figsize=(8, 6)) ax = plt.subplot(1, 1, 1) # Plot the essence by calling plot_rb_data rbfit_purity.plot_rb_data(0, ax=ax, add_label=True, show_plt=False) # Add title and label ax.set_title('%d Qubit Purity RB'%(nQ), fontsize=18) plt.show() ``` ## Standard RB results For comparison, we also print the standard RB fit results: ``` standard_result_list = [] count = 0 for rb_seed in range(len(rb_purity_circs)): for d in range(npurity): if d==0: standard_result_list.append(purity_result_list[count]) count += 1 rbfit_standard = rb.RBFitter(standard_result_list, xdata, rb_opts['rb_pattern']) print (rbfit_standard.fit) plt.figure(figsize=(8, 6)) ax = plt.subplot(1, 1, 1) # Plot the essence by calling plot_rb_data rbfit_standard.plot_rb_data(0, ax=ax, add_label=True, show_plt=False) # Add title and label ax.set_title('%d Qubit Standard RB'%(nQ), fontsize=18) plt.show() ``` ## Measurement noise model and measurement error mitigation Since part of the noise might be due to measurement errors and not only due to coherent errors, we repeat the example with measurement noise and demonstrate a mitigation of measurement errors before calculating the purity RB fitter. ``` #Add measurement noise for qi in range(nQ): read_err = noise.errors.readout_error.ReadoutError([[0.75, 0.25],[0.1,0.9]]) noise_model.add_readout_error(read_err,[qi]) #Generate the calibration circuits meas_calibs, state_labels = mc.complete_meas_cal(qubit_list=[0,1]) backend = qiskit.Aer.get_backend('qasm_simulator') shots = 200 #Execute the calibration circuits job_cal = qiskit.execute(meas_calibs, backend=backend, shots=shots, noise_model=noise_model) meas_result = job_cal.result() #Execute the purity RB circuits meas_purity_result_list = [] for rb_seed in range(len(rb_purity_circs)): for d in range(npurity): print('Executing seed %d purity %d length %d'%(rb_seed, d, len(nCliffs))) new_circ = rb_purity_circs[rb_seed][d] job_pur = qiskit.execute(new_circ, backend=backend, shots=shots, noise_model=noise_model, basis_gates=['u1','u2','u3','cx']) meas_purity_result_list.append(job_pur.result()) #Fitters meas_fitter = mc.CompleteMeasFitter(meas_result, state_labels) rbfit_purity = rb.PurityRBFitter(meas_purity_result_list, npurity, xdata, rb_opts['rb_pattern']) #no correction rho_pur = rbfit_purity.fit print('Fit (no correction) =', rho_pur) #correct data correct_purity_result_list = [] for meas_result in meas_purity_result_list: correct_purity_result_list.append(meas_fitter.filter.apply(meas_result)) #with correction rbfit_cor = rb.PurityRBFitter(correct_purity_result_list, npurity, xdata, rb_opts['rb_pattern']) rho_pur = rbfit_cor.fit print('Fit (w/ correction) =', rho_pur) plt.figure(figsize=(8, 6)) ax = plt.subplot(1, 1, 1) # Plot the essence by calling plot_rb_data rbfit_purity.plot_rb_data(0, ax=ax, add_label=True, show_plt=False) # Add title and label ax.set_title('%d Qubit Purity RB'%(nQ), fontsize=18) plt.show() plt.figure(figsize=(8, 6)) ax = plt.subplot(1, 1, 1) # Plot the essence by calling plot_rb_data rbfit_cor.plot_rb_data(0, ax=ax, add_label=True, show_plt=False) # Add title and label ax.set_title('%d Qubit Mitigated Purity RB'%(nQ), fontsize=18) plt.show() ``` ## Define a coherent noise model We define a coherent noise model for the simulator. In this example we expect the purity RB to measure no errors, but standard RB will still measure a non-zero error. ``` err_unitary = np.zeros([2, 2], dtype=complex) angle_err = 0.1 for i in range(2): err_unitary[i, i] = np.cos(angle_err) err_unitary[i, (i+1) % 2] = np.sin(angle_err) err_unitary[0, 1] *= -1.0 error = coherent_unitary_error(err_unitary) noise_model = noise.NoiseModel() noise_model.add_all_qubit_quantum_error(error, 'u3') #Execute purity RB circuits backend = qiskit.Aer.get_backend('qasm_simulator') basis_gates = ['u1','u2','u3','cx'] # use U,CX for now shots = 200 coherent_purity_result_list = [] import time for rb_seed in range(len(rb_purity_circs)): for d in range(npurity): print('Executing seed %d purity %d length %d'%(rb_seed, d, len(nCliffs))) new_circ = rb_purity_circs[rb_seed][d] job = qiskit.execute(new_circ, backend=backend, shots=shots, noise_model=noise_model, basis_gates=['u1','u2','u3','cx']) coherent_purity_result_list.append(job.result()) print("Finished Simulating Purity RB Circuits") rbfit_purity = rb.PurityRBFitter(coherent_purity_result_list, npurity, xdata, rb_opts['rb_pattern']) ``` Print the fit result (separately for each pattern): ``` print ("fit:", rbfit_purity.fit) ``` ## Plot the results and the fit ``` plt.figure(figsize=(8, 6)) ax = plt.subplot(1, 1, 1) # Plot the essence by calling plot_rb_data rbfit_purity.plot_rb_data(0, ax=ax, add_label=True, show_plt=False) # Add title and label ax.set_title('%d Qubit Purity RB'%(nQ), fontsize=18) plt.show() ``` ## Standard RB results For comparison, we also print the standard RB fit results: ``` standard_result_list = [] count = 0 for rb_seed in range(len(rb_purity_circs)): for d in range(npurity): if d==0: standard_result_list.append(coherent_purity_result_list[count]) count += 1 rbfit_standard = rb.RBFitter(standard_result_list, xdata, rb_opts['rb_pattern']) print (rbfit_standard.fit) plt.figure(figsize=(8, 6)) ax = plt.subplot(1, 1, 1) # Plot the essence by calling plot_rb_data rbfit_standard.plot_rb_data(0, ax=ax, add_label=True, show_plt=False) # Add title and label ax.set_title('%d Qubit Standard RB'%(nQ), fontsize=18) plt.show() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright ```
github_jupyter
## Creating CNN Using Transfer Learning (RestNet50) ``` # import the libraries as shown below from tensorflow.keras.layers import Input, Lambda, Dense, Flatten,Conv2D from tensorflow.keras.models import Model from tensorflow.keras.applications.vgg19 import VGG19 from tensorflow.keras.applications.resnet50 import ResNet50 from tensorflow.keras.applications.resnet50 import preprocess_input from tensorflow.keras.preprocessing import image from tensorflow.keras.preprocessing.image import ImageDataGenerator,load_img from tensorflow.keras.models import Sequential import numpy as np from glob import glob import matplotlib.pyplot as plt from google.colab import drive drive.mount('/content/drive/') # re-size all the images to this IMAGE_SIZE = [224, 224] train_path = '/content/drive/MyDrive/Colab Notebooks/Dataset/Train' valid_path = '/content/drive/MyDrive/Colab Notebooks/Dataset/Test' # Import the Resnet50 library as shown below and add preprocessing layer to the front of VGG # Here we will be using imagenet weights resnet = ResNet50(input_shape=IMAGE_SIZE + [3], weights='imagenet', include_top=False) # don't train existing weights for layer in resnet.layers: layer.trainable = False # useful for getting number of output classes folders = glob('/content/drive/MyDrive/Colab Notebooks/Dataset/Train/*') folders # our layers - you can add more if you want x = Flatten()(resnet.output) prediction = Dense(len(folders), activation='softmax')(x) # create a model object model = Model(inputs=resnet.input, outputs=prediction) # view the structure of the model model.summary() # tell the model what cost and optimization method to use model.compile( loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'] ) # Use the Image Data Generator to import the images from the dataset from tensorflow.keras.preprocessing.image import ImageDataGenerator train_datagen = ImageDataGenerator(rescale = 1./255, shear_range = 0.2, zoom_range = 0.2, horizontal_flip = True) test_datagen = ImageDataGenerator(rescale = 1./255) # Make sure you provide the same target size as initialied for the image size training_set = train_datagen.flow_from_directory('/content/drive/MyDrive/Colab Notebooks/Dataset/Train', target_size = (224, 224), batch_size = 32, class_mode = 'categorical') training_set test_set = test_datagen.flow_from_directory('/content/drive/MyDrive/Colab Notebooks/Dataset/Test', target_size = (224, 224), batch_size = 32, class_mode = 'categorical') # fit the model # Run the cell. It will take some time to execute r = model.fit_generator( training_set, validation_data=test_set, epochs=50, steps_per_epoch=len(training_set), validation_steps=len(test_set) ) # plot the loss plt.plot(r.history['loss'], label='train loss') plt.plot(r.history['val_loss'], label='val loss') plt.legend() plt.show() plt.savefig('LossVal_loss') # plot the accuracy plt.plot(r.history['accuracy'], label='train acc') plt.plot(r.history['val_accuracy'], label='val acc') plt.legend() plt.show() plt.savefig('AccVal_acc') # save it as a h5 file from tensorflow.keras.models import load_model model.save('model_resnet.h5') y_pred = model.predict(test_set) y_pred import numpy as np y_pred = np.argmax(y_pred, axis=1) y_pred from tensorflow.keras.models import load_model from tensorflow.keras.preprocessing import image model=load_model('model_resnet.h5') img=image.load_img('/content/drive/MyDrive/Colab Notebooks/Dataset/Test/Uninfected/2.png',target_size=(224,224)) x=image.img_to_array(img) x x.shape x=x/255 x=np.expand_dims(x,axis=0) img_data=preprocess_input(x) img_data.shape model.predict(img_data) a=np.argmax(model.predict(img_data), axis=1) a if(a==1): print("Uninfected") else: print("Infected") ```
github_jupyter
# Before begins This notebook is written in google colab. To see some interactive plots, please enter the colab link Below. <a href="https://colab.research.google.com/drive/1n9XYmcvefp6rSD-rH7uZqfw3eVQ_cnxh?usp=sharing" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open in Colab"/></a> # Overview <br> ## Competition Description <img src="https://storage.googleapis.com/kaggle-competitions/kaggle/3936/logos/thumb76_76.png" width=40 align='left' alt="Open in Colab"/></a> &nbsp; <font size="5">[Forest Cover Type Prediction](https://www.kaggle.com/c/house-prices-advanced-regression-techniques)</font> - Problem type: (Multi-class) classification - Predict the forest categories by using cartographic variables - Evaluation metric: Accuracy <br> ## Notebook Description This notebook provides the '**proper workflow**' for kaggle submission. The workflow is divided into three main steps. 1. Data preprocessing 2. Model selection (hyper parameter tuning, model combination, model comparison) 3. Training final model & Prediction on Test-set At each stage, detailed descriptions of the work and an appropriate procedure will be provided. Through this notebook, readers can learn the 'proper workflow' to be done for kaggle submission, and using this as a basic structure, someone will be able to apply this to other competitions easily with some adjustments **Warnings**: - The purpose of this notebook - This notebook focuses on the 'procedure' rather than the 'result'. - Thus this notebook does not guide you on how to achieve the top score. Since I personally think that any result can only have a meaning through an appropriate procedure. - But since this is a competition, it cannot be avoided that the score is important. Following this notebook, you will get the top 15% (score: 0.12519) result in this competition - The readers this notebook is intended for - Who are aware of the basic usage of data processing tools (e.g., numpy, pandas) - Who are aware of the basic concepts of machine learning models # 0. Configuration Set the configurations for this notebook ``` config = { 'data_name': 'Forest_Type', 'random_state': 2022 } ``` # 1. Data preprocessing The data preprocessing works are divided into 9 steps here. Some of these steps are mandatory and some are optional. Optional steps are marked separately. It is important to go through each step in order. Be careful not to reverse the order. ## 1-1. Load Dataset Load train-set and test-set on working environment Please download the data from [(Kaggle) Forest Cover Type](https://www.kaggle.com/c/forest-cover-type-prediction/data) and upload on your google drive in the path 'content/drive/MyDrive/Work/Kaggle/Forest_Type/Data' ``` from google.colab import drive drive.mount('/content/drive') import numpy as np import pandas as pd train = pd.read_csv('/content/drive/MyDrive/Work/Kaggle/{}/Data/train.csv'.format(config['data_name'])) test = pd.read_csv('/content/drive/MyDrive/Work/Kaggle/{}/Data/test.csv'.format(config['data_name'])) ``` ### > Concatenate the 'train' and 'test' data for preprocessing Data preprocessing work should be applied equally for train-set and test-set. In order to work at once, exclude the response variable 'Cover_Type' from 'train' and combine it with 'test'. ``` all_features = pd.concat((train.drop(['Id','Cover_Type'], axis=1), test.drop(['Id'], axis=1)), axis=0) ``` ## 1-2. Missing Value Treatment Missing (NA) values in Data must be treated properly before model training. There are three main treatment methods: 1. Remove the variables which have NA values 2. Remove the rows (observations) which have NA values 3. Impute the NA values with other values Which of the above methods is chosen is at the analyst's discretion. It is important to choose the appropriate method for the situation. ### > Check missing values in each variable There is no missing values in the data-set ``` all_features.isnull().sum().values ``` ## 1-3. Adding new features (*optional*) New variables can be created using the given data. These variables are called 'derived variables'. New informations can be added by creating appropriate derived variables. This can have a positive effect on model performance. (Not always) ### > Get Euclidean distance by using horizontal distance and vertical distance There are 'Horizontal_Distance_To_Hydrology' and 'Vertical_Distance_To_Hydrology'. By using Pythagorean theorem, we can calculate the Euclidean distance to hydrology ``` all_features['Euclidean_Distance_To_Hydrology'] = np.sqrt(np.power(all_features['Horizontal_Distance_To_Hydrology'],2) + np.power(all_features['Vertical_Distance_To_Hydrology'],2)) ``` ## 1-4. Variable modification ### > Aspect <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/1/1a/Brosen_windrose.svg/600px-Brosen_windrose.svg.png" width=180 align='left' alt="Open in Colab"/></a> According to the data description, 'Aspect' indicates the Aspect in degrees azimuth. In the cartographic data, the azimuth is the angular direction of the sun, measured from the north in clockwise degrees from 0 to 360. For example, An azimuth of 90 degrees is east. Since the values of 'Aspect' vary from 0 to 360, this variable's actual information, which is the azimuth angle, can not be obtained in modeling. Thus we need to convert these values ​​appropriately to represent the azimuth angle. <br> Procedure: - Bin values into discrete intervals based on the cardinal direction - Label the binned discrete intervals based on the cardinal direction ``` aspect_label_list = ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW'] aspect_interval = np.linspace(11.25, 371.25, 17) aspect_interval[0] = 0 all_features['Aspect_direction'] = pd.cut(all_features['Aspect']+11.25, aspect_interval, right=True, labels=aspect_label_list, ordered=False) all_features.drop('Aspect', inplace=True, axis=1) ``` ## 1-5. Dummify categorical variables In the case of linear modeling without regularization, the first or last column should be dropped (to prevent linear dependency), but here, for the convenience of using the factorization model, one-hot encoding method is used that does not drop any columns. ``` data_set = pd.get_dummies(all_features, drop_first=False) ``` ## 1-6. Scaling continuous variables The float variables 'Age' and 'Fare' were measured in different units. MinMaxScaling maps all variables from 0 to 1 in order to consider only relative information, not absolute magnitudes of values. Besides, it is known that scaling is often more stable in parameter optimization when training a model. ``` from sklearn.preprocessing import MinMaxScaler scaler = MinMaxScaler() data_set = scaler.fit_transform(data_set) ``` ## 1-7. Split Train & Test set ``` n_train = train.shape[0] X_train = data_set[:n_train].astype(np.float32) X_test = data_set[n_train:].astype(np.float32) y_train = train['Cover_Type'].values.astype(np.int64) ``` ## 1-8. Outlier Detection on Training data (*optional*) Detect and remove outlier observations that exist in the train-set. - Methodology: [Isolation Forest](https://ieeexplore.ieee.org/abstract/document/4781136/?casa_token=V7U3M1UIykoAAAAA:kww9pojtMeJtXaBcNmw0eVlJaXEGGICi1ogmeHUFMpgJ2h_XCbSd2yBU5mRgd7zEJrXZ01z2) - How it works - Isolation Forest applies a decision tree that repeats splits based on the 'random criterion' for the given data unitl only one observation remains in every terminal node (this is defined as 'isolation'). - Based on the number of splits used for isolation, 'normality' is defined. A smaller value means a higher degree of outlierness. - By applying this decision tree several times, the average of the measured 'normality' values ​​is derived as the final 'normality' value. - Assumptions - Outliers require relatively few splits to be isolated. - For normal data, the number of splits required to be isolated is relatively large. - Outlier determination - Determines whether it is an outlier or not based on the measured 'normality' value. - sklearn's IsolationForest package determines based on '0' - I, personally, think it is better to set the discriminant criterion by considering the 'distribution' of the 'normality' values. - The details of the method is given below. ``` from sklearn.ensemble import IsolationForest clf = IsolationForest( n_estimators=100, max_samples='auto', n_jobs=-1, random_state=config['random_state']) clf.fit(X_train) normality_df = pd.DataFrame(clf.decision_function(X_train), columns=['normality']) ``` The discriminant value (threshold) is defined by calculating the 1st quartile ($q_1$) and 3rd quartile ($q_3$) on the distribution of the measured normality values. $threshold = q_1 - k*(q_3 - q_1)$ - In this case, set $k=1.5$. This discriminant method is adapted from Tukey's boxplot idea. In the distribution of any continuous variable, Tukey designates observations smaller than that value or larger than q_3 + k*(q_3 - q_1) as outliers. Our methodology does not apply the above method to a specific variable, but applies the method to the obtained normality. That is, it is based on the assumption that an outlier will be far left from the other observations in the measured normality distribution. ``` def outlier_threshold(normality, k=1.5): q1 = np.quantile(normality, 0.25) q3 = np.quantile(normality, 0.75) threshold = q1 - k*(q3-q1) return threshold threshold = outlier_threshold(normality_df['normality'].values, k=1.5) import plotly.express as px fig = px.histogram(normality_df, x='normality', width=400, height=400) fig.add_vline(x=threshold, line_width=3, line_dash="dash", line_color="red") fig.show() import plotly.express as px px.box(normality_df, x='normality', orientation='h', width=400, height=400) X_train = X_train[normality_df['normality'].values>=threshold] y_train = y_train[normality_df['normality'].values>=threshold] print('{} observations are removed from train_set'.format(train.shape[0] - X_train.shape[0])) ``` ## 1-9. Output variable transformation PyTorch module supports labels starting from 0. Since our output variable values vary from 1 to 7, we convert these to 0 to 7. ``` np.unique(y_train) y_train_trans = y_train - 1 ``` # 2. Model Selection Our goal is to build a model that predicts the forest cover type given the cartographic informations of the forest. The formula can be expressed as: $\hat{y} = \underset{k \in \{1,\cdots,K\}}{\operatorname{argmax}}f_{k}(x)$ where, - $y \in \{1,\cdots,K\} $: labels - $x$: an input observation - $f_{k}(x)$: a function of $x$ that outputs predicted value for each $k$ This is a typical multiclass classification problem, and various machine learning models can be obtained. This notebook uses the following models. - Logistic regression - Support vector machine - Random forest - Xgboost - Multi-layer perceptron - Factorization However, we have to "choose" one final methodology to make predictions on the test set. To do this, a “fair evaluation” of the models is essential. "Fair evaluation" must satisfy the following two conditions. 1. Select optimal hyperparameters for each model - If hyperparameter search is not performed, the difference in model performance may occur due to incorrect hyperparameter values. 2. same evaluation method - If the same evaluation method is not applied, comparison between models itself is impossible. When comparing models through an evaluation method that satisfies the above two conditions, Only then can the final model be selected. ### > Install Packages ``` !pip install tune_sklearn ray[tune] skorch ``` ## 2-1. Hyper parameter tuning by using Tune_SKlearn (Ray Tune) - Package: tune_sklearn - This package makes it easy to apply [Ray Tune](https://docs.ray.io/en/latest/tune/index.html) to sklearn models. - Ray Tune is a python package that provides various hyperparameter tuning algorithms (HyperOpt, BayesianOptimization, ...). - Tuning procedure - Define an appropriate search space for each model's hyperparameters. - 5-fold CV (Cross Validation) is performed for each specific hyper-parameter value combination of the search space by using the hyper-parameter tuning algorithm (HyperOpt) - Training: Training by using Scikit-Learn and Skorch packages - Validation: Evaluate the model using an appropriate evaluation metric - The hyperparameter with the highest average score of the CV result is designated as the optimal hyperparameter of the model. - Save this CV result and use for model comparison ### > Make a dataframe for containing CV results ``` model_list = [] for name in ['linear', 'svm', 'rf', 'xgb', 'mlp', 'fm']: model_list.append(np.full(5, name)) best_cv_df = pd.DataFrame({'model': np.hstack((model_list)), 'log_loss':None, 'accuracy':None, 'best_hyper_param':None}) ``` ### > Logistic regression ``` from tune_sklearn import TuneSearchCV from sklearn.linear_model import SGDClassifier # Define a search space parameters = { 'max_iter': [1000], 'loss': ['log'], 'penalty': ['l2'], 'random_state': [config['random_state']], 'alpha': list(np.geomspace(1e-6, 1e-3, 4)), 'tol': list(np.geomspace(1e-4, 1e-1, 4)) } # Specify the hyper parameter tuning algorithm tune_search = TuneSearchCV( SGDClassifier(), parameters, search_optimization='hyperopt', n_trials=10, n_jobs=-1, scoring=['neg_log_loss', 'accuracy'], cv=5, refit='accuracy', # target metric of competition verbose=1, random_state=config['random_state'] ) # Run hyper parameter tuning X = X_train y = y_train_trans tune_search.fit(X, y) # Save the tuning results model_name = 'linear' ## Save the optimal hyper parmater values best_cv_df.loc[best_cv_df['model']==model_name, 'best_hyper_param'] = str(tune_search.best_params_) ## Save the CV results cv_df = pd.DataFrame(tune_search.cv_results_) cv_values = cv_df.loc[tune_search.best_index_, cv_df.columns.str.startswith('split')].values best_cv_df.loc[best_cv_df['model']==model_name, 'log_loss'] = cv_values[:5] best_cv_df.loc[best_cv_df['model']==model_name, 'accuracy'] = cv_values[5:10] # Visualize the tuning results with parallel coordinate plot tune_result_df = pd.concat([pd.DataFrame(tune_search.cv_results_['params']), cv_df.loc[:,cv_df.columns.str.startswith('mean')] ], axis=1) import plotly.express as px fig = px.parallel_coordinates(tune_result_df, color='mean_test_accuracy') fig.show() ``` ### > Support vector machine ``` from tune_sklearn import TuneSearchCV from sklearn.linear_model import SGDClassifier # Define a search space parameters = { 'alpha': list(np.geomspace(1e-7, 1e-3, 3)), 'epsilon': list(np.geomspace(1e-5, 1e-1, 3)), 'loss': ['hinge'], 'tol': list(np.geomspace(1e-7, 1e-1, 4)), 'max_iter': [1000], 'penalty': ['l2'], 'random_state': [config['random_state']] } # Specify the hyper parameter tuning algorithm tune_search = TuneSearchCV( SGDClassifier(), parameters, search_optimization='hyperopt', n_trials=10, n_jobs=-1, scoring=['accuracy'], cv=5, refit='accuracy', # target metric of competition verbose=1, random_state=config['random_state'] ) # Run hyper parameter tuning X = X_train y = y_train_trans tune_search.fit(X, y) # Save the tuning results model_name = 'svm' ## Save the optimal hyper parmater values best_cv_df.loc[best_cv_df['model']==model_name, 'best_hyper_param'] = str(tune_search.best_params_) ## Save the CV results cv_df = pd.DataFrame(tune_search.cv_results_) cv_values = cv_df.loc[tune_search.best_index_, cv_df.columns.str.startswith('split')].values best_cv_df.loc[best_cv_df['model']==model_name, 'accuracy'] = cv_values[:5] # Visualize the tuning results with parallel coordinate plot tune_result_df = pd.concat([pd.DataFrame(tune_search.cv_results_['params']), cv_df.loc[:,cv_df.columns.str.startswith('mean')] ], axis=1) import plotly.express as px fig = px.parallel_coordinates(tune_result_df, color='mean_test_accuracy') fig.show() ``` ### > Random forest ``` from tune_sklearn import TuneSearchCV from sklearn.ensemble import RandomForestClassifier # Define a search space parameters = { 'n_estimators': [100, 500, 1000], 'criterion': ['gini', 'entropy'], 'max_depth': [20, 25, 30], 'max_features': ['auto'], 'random_state': [config['random_state']] } # Specify the hyper parameter tuning algorithm tune_search = TuneSearchCV( RandomForestClassifier(), parameters, search_optimization='hyperopt', n_trials=10, n_jobs=-1, scoring=['neg_log_loss', 'accuracy'], cv=5, refit='accuracy', verbose=1, random_state=config['random_state'] ) # Run hyper parameter tuning X = X_train y = y_train_trans tune_search.fit(X, y) # Save the tuning results model_name = 'rf' ## Save the optimal hyper parmater values best_cv_df.loc[best_cv_df['model']==model_name, 'best_hyper_param'] = str(tune_search.best_params_) ## Save the CV results cv_df = pd.DataFrame(tune_search.cv_results_) cv_values = cv_df.loc[tune_search.best_index_, cv_df.columns.str.startswith('split')].values best_cv_df.loc[best_cv_df['model']==model_name, 'log_loss'] = cv_values[:5] best_cv_df.loc[best_cv_df['model']==model_name, 'accuracy'] = cv_values[5:10] # Visualize the tuning results with parallel coordinate plot tune_result_df = pd.concat([pd.DataFrame(tune_search.cv_results_['params']), cv_df.loc[:,cv_df.columns.str.startswith('mean')] ], axis=1) import plotly.express as px fig = px.parallel_coordinates(tune_result_df, color='mean_test_accuracy') fig.show() ``` ### > XGBoost ``` from tune_sklearn import TuneSearchCV from xgboost import XGBClassifier # Define a search space parameters = { 'n_estimators': [50, 100, 200], 'learning_rate': list(np.geomspace(1e-2, 1, 3)), 'min_child_weight': [10, 15, 20], 'gamma': [0.5, 2], 'subsample': [0.6, 1.0], 'colsample_bytree': [0.6, 1.0], 'max_depth': [5, 10, 15], 'objective': ['multi:softmax'], 'random_state': [config['random_state']] } # Specify the hyper parameter tuning algorithm tune_search = TuneSearchCV( XGBClassifier(), parameters, search_optimization='hyperopt', n_trials=10, n_jobs=-1, scoring=['neg_log_loss', 'accuracy'], cv=5, refit='accuracy', verbose=1, random_state=config['random_state'] ) # Run hyper parameter tuning X = X_train y = y_train_trans tune_search.fit(X, y) # Save the tuning results model_name = 'xgb' ## Save the optimal hyper parmater values best_cv_df.loc[best_cv_df['model']==model_name, 'best_hyper_param'] = str(tune_search.best_params_) ## Save the CV results cv_df = pd.DataFrame(tune_search.cv_results_) cv_values = cv_df.loc[tune_search.best_index_, cv_df.columns.str.startswith('split')].values best_cv_df.loc[best_cv_df['model']==model_name, 'log_loss'] = cv_values[:5] best_cv_df.loc[best_cv_df['model']==model_name, 'accuracy'] = cv_values[5:10] # Visualize the tuning results with parallel coordinate plot tune_result_df = pd.concat([pd.DataFrame(tune_search.cv_results_['params']), cv_df.loc[:,cv_df.columns.str.startswith('mean')] ], axis=1) import plotly.express as px fig = px.parallel_coordinates(tune_result_df, color='mean_test_accuracy') fig.show() ``` ### > Multi-layer perceptron ``` import torch from torch import nn from skorch import NeuralNetClassifier from skorch.callbacks import EarlyStopping from skorch.callbacks import Checkpoint from tune_sklearn import TuneSearchCV # Define a model structure class MLP(nn.Module): def __init__(self, num_inputs=X_train.shape[1], num_outputs=len(np.unique(y_train)), layer1=512, layer2=256, dropout1=0, dropout2=0): super(MLP, self).__init__() self.linear_relu_stack = nn.Sequential( nn.Linear(num_inputs, layer1), nn.LeakyReLU(), nn.Dropout(dropout1), nn.Linear(layer1, layer2), nn.LeakyReLU(), nn.Dropout(dropout2), nn.Linear(layer2, num_outputs) ) def forward(self, x): x = self.linear_relu_stack(x) return x def try_gpu(i=0): return f'cuda:{i}' if torch.cuda.device_count() >= i + 1 else 'cpu' # Set model configurations mlp = NeuralNetClassifier( MLP(num_inputs=X_train.shape[1], num_outputs=len(np.unique(y_train))), optimizer=torch.optim.Adam, criterion=nn.CrossEntropyLoss(), iterator_train__shuffle=True, device=try_gpu(), verbose=0, callbacks=[EarlyStopping(monitor='valid_loss', patience=5, threshold=1e-4, lower_is_better=True), Checkpoint(monitor='valid_loss_best')] ) # Define a search space parameters = { 'lr': list(np.geomspace(1e-4, 1e-1, 4)), 'module__layer1': [128, 256, 512], 'module__layer2': [128, 256, 512], 'module__dropout1': [0, 0.1], 'module__dropout2': [0, 0.1], 'optimizer__weight_decay': list(np.append(0, np.geomspace(1e-5, 1e-3, 3))), 'max_epochs': [1000], 'batch_size': [32, 128], 'callbacks__EarlyStopping__threshold': list(np.geomspace(1e-4, 1e-2, 3)) } def use_gpu(device): return True if not device == 'cpu' else False # Specify the hyper parameter tuning algorithm tune_search = TuneSearchCV( mlp, parameters, search_optimization='hyperopt', n_trials=10, n_jobs=-1, scoring=['neg_log_loss', 'accuracy'], cv=5, refit='accuracy', verbose=1, random_state=config['random_state'] ) # Run hyper parameter tuning X = X_train y = y_train_trans tune_search.fit(X, y) # Save the tuning results model_name = 'mlp' ## Save the optimal hyper parmater values best_cv_df.loc[best_cv_df['model']==model_name, 'best_hyper_param'] = str(tune_search.best_params_) ## Save the CV results cv_df = pd.DataFrame(tune_search.cv_results_) cv_values = cv_df.loc[tune_search.best_index_, cv_df.columns.str.startswith('split')].values best_cv_df.loc[best_cv_df['model']==model_name, 'log_loss'] = cv_values[:5] best_cv_df.loc[best_cv_df['model']==model_name, 'accuracy'] = cv_values[5:10] # Visualize the tuning results with parallel coordinate plot tune_result_df = pd.concat([pd.DataFrame(tune_search.cv_results_['params']), cv_df.loc[:,cv_df.columns.str.startswith('mean')] ], axis=1) tune_result_df.rename({ 'callbacks__EarlyStopping__threshold':'Earlystoping_threshold', 'optimizer__weight_decay': 'weight_decay' }, axis=1, inplace=True) import plotly.express as px fig = px.parallel_coordinates(tune_result_df, color='mean_test_accuracy') fig.show() ``` ### > Factorization Machine [Factorization Machines](https://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=5694074&casa_token=WNncod4Fzy0AAAAA:06BUH6Q3Mh-HhboU-WV9p4h5AykMCWcYedWlcFDLtNw4tIkNWZg9oadIz32UuMx9rFDyqOTGY1w&tag=1), proposed by Steffen Rendle in 2010, is a supervised algorithm that can be used for classification, regression, and ranking tasks. It quickly took notice and became a popular and impactful method for making predictions and recommendations. #### >> Preprocessing Data for implementing Factorization Machine Since the factorization machine uses an embedding layer, it requires that the data type of all input variables be 'int'. To take this into account, 'float' type variables are divided into several sections according to their values, and values ​​belonging to a specific section are transformed into interger values ​​of the section. ``` def prepro_for_fm(X_train, X_test, bin_method='sturges'): n_train = X_train.shape[0] all = np.vstack((X_train, X_test)) col_num_uniq = np.apply_along_axis(lambda x: len(np.unique(x)), 0, all) remain_iidx = (col_num_uniq<=2) to_bin_iidx = (col_num_uniq>2) all_remain = all[:,remain_iidx] all_to_bin = all[:,to_bin_iidx] for iter in range(all_to_bin.shape[1]): bin_size = len(np.histogram(all_to_bin[:,iter], bins=bin_method)[0]) all_to_bin[:,iter] = pd.cut(all_to_bin[:,iter], bins=bin_size, labels=False) all_to_bin_df = pd.DataFrame(all_to_bin).astype('object') all_to_bin_array = pd.get_dummies(all_to_bin_df, drop_first=False).to_numpy() all_array = np.hstack((all_to_bin_array, all_remain)).astype(np.int64) field_dims = all_array.shape[1] all_fm = np.vstack((np.apply_along_axis(lambda x: np.where(x==1), 1, all_array))) return all_fm[:n_train], all_fm[n_train:], field_dims X_train_fm, X_test_fm, field_dims = prepro_for_fm(X_train, X_test, bin_method='sturges') import torch from torch import nn from skorch import NeuralNetClassifier from skorch.callbacks import EarlyStopping from skorch.callbacks import Checkpoint from tune_sklearn import TuneSearchCV # Define a model structure class FM(nn.Module): def __init__(self, num_inputs=field_dims, num_factors=20, output_dim=7): super(FM, self).__init__() self.output_dim = output_dim for i in range(output_dim): setattr(self, f'embedding_{i}', nn.Embedding(num_inputs, num_factors)) self.fc = nn.Embedding(num_inputs, output_dim) self.bias = nn.Parameter(torch.zeros((output_dim,))) def forward(self, x): square_of_sum_list = [] sum_of_square_list = [] for i in range(self.output_dim): square_of_sum_list.append(torch.sum(getattr(self, f'embedding_{i}')(x), dim=1)**2) sum_of_square_list.append(torch.sum(getattr(self, f'embedding_{i}')(x)**2, dim=1)) square_of_sum = torch.stack(square_of_sum_list, dim=1) sum_of_square = torch.stack(sum_of_square_list, dim=1) x = self.bias + self.fc(x).sum(dim=1) + 0.5 * (square_of_sum - sum_of_square).sum(dim=2) return x def try_gpu(i=0): return f'cuda:{i}' if torch.cuda.device_count() >= i + 1 else 'cpu' # Set model configurations fm = NeuralNetClassifier( FM(num_inputs=field_dims, output_dim=len(np.unique(y_train_trans))), optimizer=torch.optim.Adam, criterion=nn.CrossEntropyLoss(), iterator_train__shuffle=True, device=try_gpu(), verbose=0, callbacks=[EarlyStopping(monitor='valid_loss', patience=5, threshold=1e-4, lower_is_better=True), Checkpoint(monitor='valid_loss_best')] ) # Define a search space parameters = { 'lr': list(np.geomspace(1e-4, 1e-2, 3)), 'module__num_factors': [50, 100, 150], 'optimizer__weight_decay': [1e-5, 1e-4, 1e-1], 'max_epochs': [1000], 'batch_size': [16, 32] } def use_gpu(device): return True if not device == 'cpu' else False # Specify the hyper parameter tuning algorithm tune_search = TuneSearchCV( fm, parameters, search_optimization='hyperopt', n_trials=10, n_jobs=-1, scoring=['neg_log_loss', 'accuracy'], cv=5, refit='accuracy', mode='max', use_gpu = use_gpu(try_gpu()), random_state=config['random_state'], verbose=1, ) # Run hyper parameter tuning X = X_train_fm y = y_train_trans tune_search.fit(X, y) # Save the tuning results model_name = 'fm' ## Save the optimal hyper parmater values best_cv_df.loc[best_cv_df['model']==model_name, 'best_hyper_param'] = str(tune_search.best_params_) ## Save the CV results cv_df = pd.DataFrame(tune_search.cv_results_) cv_values = cv_df.loc[tune_search.best_index_, cv_df.columns.str.startswith('split')].values best_cv_df.loc[best_cv_df['model']==model_name, 'log_loss'] = cv_values[:5] best_cv_df.loc[best_cv_df['model']==model_name, 'accuracy'] = cv_values[5:10] # Visualize the tuning results with parallel coordinate plot tune_result_df = pd.concat([pd.DataFrame(tune_search.cv_results_['params']), cv_df.loc[:,cv_df.columns.str.startswith('mean')] ], axis=1) tune_result_df.rename({ 'callbacks__EarlyStopping__threshold':'Earlystoping_threshold', 'optimizer__weight_decay': 'weight_decay' }, axis=1, inplace=True) import plotly.express as px fig = px.parallel_coordinates(tune_result_df, color='mean_test_accuracy') fig.show() import os save_path = '/content/drive/MyDrive/Work/Kaggle/{}/Result'.format(config['data_name']) if not os.path.exists(save_path): os.makedirs(save_path) file_path = os.path.join(save_path, 'best_cv_results.csv') best_cv_df.to_csv(file_path, index=False) ``` ## 2-2. Model Comparison based on CV results Compare the CV results (measured using the best hyper parameter values) \\ The figure below shows that \\ rf > xgb >> fm > mlp >> linear > svm ``` best_cv_df = pd.read_csv('/content/drive/MyDrive/Work/Kaggle/{}/Result/best_cv_results.csv'.format(config['data_name'])) fig = px.box(best_cv_df, x='model', y='accuracy', color='model', width=600) fig.show() ``` ## 2-3. Model Combination Although it is possible to select a final model based on the above results, it has been observed that in many cases the combination of predicted values ​​from multiple models leads to improve prediction performance. ([Can multi-model combination really enhance the prediction skill of probabilistic ensemble forecasts?](https://rmets.onlinelibrary.wiley.com/doi/abs/10.1002/qj.210?casa_token=OwyF2RbEywAAAAAA:gahpwGRdOWzLXyafYQQt_voHOF8MedTBLd1SBv4vkdT3ZTLVoKZQj3zl-KbrhSkX5x8CndeCxwBoL_-S)) For classification problems, the final probabilities are derived by combining the predicted 'probabilities' for each class in a 'proper way'. This notebook uses following two model combination methods. 1. Simple Average 2. Stacked Generalization (Stacking) Model comparison needs to be done with single models (e.g., rf, xgb,...). So model performance are measured by applying the same CV method as above. ### > Simple Average The simple average method derives the final probability value by 'averaging' the predicted probability values ​​for each class of multiple models. The top 3 models (rf, xgb, fm) of the above CV results are selected as base estimators used for the combination of predicted values. For example, - Base Estimations - $P_{rf}(Y=1|X=x)$ = 0.75 - $P_{xgb}(Y=1|X=x)$ = 0.80 - $P_{fm}(Y=1|X=x)$ = 0.80 - Final Estimation - $P_{average}(Y=1|X=x)$ = 0.8 (= 0.75 + 0.80 + 0.85 + 0.80 / 4) ``` from sklearn.model_selection import KFold from tqdm import notebook from sklearn.metrics import accuracy_score from sklearn.metrics import log_loss from sklearn.metrics import roc_auc_score def CV_ensemble(ensemble_name, ensemble_func, estimators, X_train, y_train, n_folds=5, shuffle=True, random_state=2022): kf = KFold(n_splits=5, random_state=random_state, shuffle=True) res_list = [] for train_idx, valid_idx in notebook.tqdm(kf.split(X_train), total=kf.get_n_splits(), desc='Eval_CV'): X_train_train, X_valid = X_train[train_idx], X_train[valid_idx] y_train_train, y_valid = y_train[train_idx], y_train[valid_idx] ensemble_pred_proba = ensemble_func(estimators, X_train_train, y_train_train, X_valid) neg_log_loss = np.negative(log_loss(y_valid, ensemble_pred_proba)) accuracy = accuracy_score(y_valid, ensemble_pred_proba.argmax(axis=1)) res_list.append([ensemble_name, neg_log_loss, accuracy]) res_df = pd.DataFrame(np.vstack((res_list))) res_df.columns = ['model', 'log_loss', 'accuracy'] return res_df def ensemble_average(estimators, X_train, y_train, X_test): preds = [] num_estimators = len(estimators) num_class = len(np.unique(y_train)) for iter in range(num_estimators): try: estimators[iter].module__num_factors except: # for other models estimators[iter].fit(X_train, y_train) preds.append(estimators[iter].predict_proba(X_test)) else: # for factorization machine X_train_fm, X_test_fm, _ = prepro_for_fm(X_train, X_test) estimators[iter].fit(X_train_fm, y_train) preds.append(estimators[iter].predict_proba(X_test_fm)) preds_stack = np.hstack((preds)) preds_mean = [] for iter in range(num_class): col_idx = np.arange(iter, num_estimators * num_class, num_class) preds_mean.append(np.mean(preds_stack[:,col_idx], axis=1)) return np.vstack((preds_mean)).transpose() from sklearn.linear_model import SGDClassifier from sklearn.ensemble import RandomForestClassifier from xgboost import XGBClassifier linear = SGDClassifier(**eval(best_cv_df.loc[best_cv_df['model']=='linear', 'best_hyper_param'].values[0])) svm = SGDClassifier(**eval(best_cv_df.loc[best_cv_df['model']=='svm', 'best_hyper_param'].values[0])) rf = RandomForestClassifier(**eval(best_cv_df.loc[best_cv_df['model']=='rf', 'best_hyper_param'].values[0])) xgb = XGBClassifier(**eval(best_cv_df.loc[best_cv_df['model']=='xgb', 'best_hyper_param'].values[0])) mlp = mlp.set_params(**eval(best_cv_df.loc[best_cv_df['model']=='mlp', 'best_hyper_param'].values[0])) fm = fm.set_params(**eval(best_cv_df.loc[best_cv_df['model']=='fm', 'best_hyper_param'].values[0])) estimators = [rf, xgb, mlp] estimators_name = 'rf_xgb_mlp' ensemble_name = 'average' + '_by_' + estimators_name X = X_train y = y_train_trans res_df = CV_ensemble(ensemble_name, ensemble_average, estimators, X, y, n_folds=5, shuffle=True, random_state=config['random_state']) best_cv_df = best_cv_df.append(res_df).reset_index(drop=True) fig = px.box(best_cv_df, x='model', y='accuracy', color='model', width=800) fig.show() import os save_path = '/content/drive/MyDrive/Work/Kaggle/{}/Result'.format(config['data_name']) if not os.path.exists(save_path): os.makedirs(save_path) file_path = os.path.join(save_path, 'best_cv_results.csv') best_cv_df.to_csv(file_path, index=False) ``` ### > Stacked generalization (Stacking) In the [Stacked generalization](https://www.jair.org/index.php/jair/article/view/10228), the predicted probabilities of base estimators are treated as the 'input data', and y (Cover_Type) of each row is treated as the 'output variable'. The 'Meta Learner' is learned with these data and the predicted probablities of this model are derived as the final prediction probabilities. - The 'Meta Learner' can be optained among any of the classification models. However, this notebook uses a ridge model (logistic regression with ridge penalty) to prevent overfitting. - As input data for 'Meta Learner', prediction probabilities for validation data in cv of base estimators are obtained. - Trained meta-learner predicts the final predicted probabilities for the test-set by using the predicted probabilites of baes estimators for the test-set as input data. The total process, in order, is as follows: 1. (Base estimators) Run CV on Train-set 2. (Meta Learner) Train on CV predictions (predicted probabilities on validation data of CV) with corresponding y values 3. (Base estimators) Train on Train-set 4. (Base estimators) Predict on Test-set 5. (Meta Learner) Predict on predictions on Test-set <img align='top' src='https://drive.google.com/uc?export=view&id=1uDxSIIFt8rUJkuIwRYU4lALvOPqlXPG5' width='600' height='400'> For example, - Assume that - $Y \in \{0, 1, 2\}$ - Base Estimatiors - rf - $P_{rf}(Y=0|X=x)$ = 0.75 - $P_{rf}(Y=1|X=x)$ = 0.10 - $P_{rf}(Y=2|X=x)$ = 0.15 - xgb - $P_{xgb}(Y=0|X=x)$ = 0.80 - $P_{xgb}(Y=1|X=x)$ = 0.10 - $P_{xgb}(Y=2|X=x)$ = 0.10 - Meta Learner (logistic regression with ridge (l2) penalty) - when Y=0: - intercept = 0.1 - coefficient = [0.8, 0.1, -0.1, 0.9, 0.2, -0.05] - predicted probabilities - $P_{stack}(Y=0|X=x)$ = 0.8069 = sigmoid(0.1 + 0.8*0.75 + 0.1*0.1 -0.1*0.15 + 0.9*0.8 + 0.2*0.1 - 0.05*0.1)$ **Warnings**: - the set of predicted probabilities $[P_{rf}(Y=1|X=x), \cdots, P_{xgb}(Y=2|X=x)]$ is a **linearly dependent ** matrix. - Thus, as a final estimator, linear model with penalty or not a linear model is recommended. - If you want to apply plain linear model with no penalty, please remove the first or last class probabilities of each base estimators (e.g., remove $P_{rf}(Y=2|X=x)$ and $P_{xgb}(Y=2|X=x)$) ``` from sklearn.model_selection import KFold from tqdm import notebook def stack_clf(estimators, X_train, y_train, X_test, n_folds=5, shuffle=True, random_state=2022): final_estimator = estimators[-1] num_estimators = len(estimators)-1 kf = KFold(n_splits=n_folds, random_state=random_state, shuffle=shuffle) preds = [] y_valid_list = [] for train_idx, valid_idx in notebook.tqdm(kf.split(X_train), total=kf.get_n_splits(), desc='Stack_CV'): X_train_train, X_valid = X_train[train_idx], X_train[valid_idx] y_train_train, y_valid = y_train[train_idx], y_train[valid_idx] valid_preds = [] for iter in range(num_estimators): try: estimators[iter].module__num_factors except: # for other models estimators[iter].fit(X_train_train, y_train_train) valid_preds.append(estimators[iter].predict_proba(X_valid)) else: # for factorization machine X_train_train_fm, X_valid_fm, _ = prepro_for_fm(X_train_train, X_valid) estimators[iter].fit(X_train_train_fm, y_train_train) valid_preds.append(estimators[iter].predict_proba(X_valid_fm)) preds.append(np.hstack((valid_preds))) # warning: this matrix is linearly dependent. If you want to ge linearly independent matrix, drop first column y_valid_list.append(y_valid) cv_preds = np.vstack((preds)) cv_y = np.hstack((y_valid_list)) final_estimator.fit(cv_preds, cv_y) print(' Train score: {}'.format(final_estimator.score(cv_preds, cv_y))) print(' Estimated coefficients: {} \n intercept: {}'.format(final_estimator.coef_, final_estimator.intercept_)) test_preds =[] for iter in range(num_estimators): try: estimators[iter].module__num_factors except: # for other models estimators[iter].fit(X_train, y_train) test_preds.append(estimators[iter].predict_proba(X_test)) else: # for factorization machine X_train_fm, X_test_fm, _ = prepro_for_fm(X_train, X_test) estimators[iter].fit(X_train_fm, y_train) test_preds.append(estimators[iter].predict_proba(X_test_fm)) test_preds_mat = np.hstack((test_preds)) # warning: this matrix is linearly dependent. If you want to ge linearly independent matrix, drop first column pred_fin = final_estimator.predict_proba(test_preds_mat) return pred_fin from sklearn.linear_model import SGDClassifier from sklearn.ensemble import RandomForestClassifier from xgboost import XGBClassifier from sklearn.linear_model import LogisticRegression # Base estimators linear = SGDClassifier(**eval(best_cv_df.loc[best_cv_df['model']=='linear', 'best_hyper_param'].values[0])) svm = SGDClassifier(**eval(best_cv_df.loc[best_cv_df['model']=='svm', 'best_hyper_param'].values[0])) rf = RandomForestClassifier(**eval(best_cv_df.loc[best_cv_df['model']=='rf', 'best_hyper_param'].values[0])) xgb = XGBClassifier(**eval(best_cv_df.loc[best_cv_df['model']=='xgb', 'best_hyper_param'].values[0])) mlp = mlp.set_params(**eval(best_cv_df.loc[best_cv_df['model']=='mlp', 'best_hyper_param'].values[0])) fm = fm.set_params(**eval(best_cv_df.loc[best_cv_df['model']=='fm', 'best_hyper_param'].values[0])) estimators = [rf, xgb, mlp] estimators_name = 'rf_xgb_mlp' # Final estimator clf = LogisticRegression(penalty='l2', max_iter=1000, random_state=config['random_state']) estimators.append(clf) ensemble_func = stack_clf ensemble_name = 'stack_ridge' + '_by_' + estimators_name # Run CV X = X_train y = y_train_trans res_df = CV_ensemble(ensemble_name, ensemble_func, estimators, X, y, n_folds=5, shuffle=True, random_state=config['random_state']) best_cv_df = best_cv_df.append(res_df) fig = px.box(best_cv_df, x='model', y='accuracy', color='model', width=800) fig.show() import os save_path = '/content/drive/MyDrive/Work/Kaggle/{}/Result'.format(config['data_name']) if not os.path.exists(save_path): os.makedirs(save_path) file_path = os.path.join(save_path, 'best_cv_results.csv') best_cv_df.to_csv(file_path, index=False) ``` ## 2-4. Model Comparison based on CV results including model combination methods From the figure below, 'xgb' shows the best performance among single models. Among the model combination methodologies, it can be seen that the 'stack_ridge_by_rf_xgb_mlp_fm' method shows the best performance. ``` fig = px.box(best_cv_df, x='model', y='accuracy', color='model', width=800 ) fig.show() import os save_path = '/content/drive/MyDrive/Work/Kaggle/{}/Result'.format(config['data_name']) if not os.path.exists(save_path): os.makedirs(save_path) file_path = os.path.join(save_path, 'best_cv_results.csv') best_cv_df.to_csv(file_path, index=False) ``` # 3. Make a prediction with the best model ``` from sklearn.linear_model import SGDClassifier from sklearn.ensemble import RandomForestClassifier from xgboost import XGBClassifier from sklearn.linear_model import LogisticRegression # Base estimators linear = SGDClassifier(**eval(best_cv_df.loc[best_cv_df['model']=='linear', 'best_hyper_param'].values[0])) svm = SGDClassifier(**eval(best_cv_df.loc[best_cv_df['model']=='svm', 'best_hyper_param'].values[0])) rf = RandomForestClassifier(**eval(best_cv_df.loc[best_cv_df['model']=='rf', 'best_hyper_param'].values[0])) xgb = XGBClassifier(**eval(best_cv_df.loc[best_cv_df['model']=='xgb', 'best_hyper_param'].values[0])) mlp = mlp.set_params(**eval(best_cv_df.loc[best_cv_df['model']=='mlp', 'best_hyper_param'].values[0])) fm = fm.set_params(**eval(best_cv_df.loc[best_cv_df['model']=='fm', 'best_hyper_param'].values[0])) estimators = [rf, xgb, mlp] estimators_name = 'rf_xgb_mlp' # Final estimator clf = LogisticRegression(penalty='l2', max_iter=1000, random_state=config['random_state']) estimators.append(clf) ensemble_func = stack_clf ensemble_name = 'stack_ridge' + '_by_' + estimators_name # Run CV X = X_train y = y_train_trans pred_proba = stack_clf(estimators, X, y, X_test, n_folds=5, shuffle=True, random_state=config['random_state']) pred = pred_proba.argmax(axis=1) pred_trans = pred + 1 res_df = pd.DataFrame({'Id': test['Id'], 'Cover_Type': pred_trans}) res_df.to_csv(ensemble_name+'.csv', index=False) ```
github_jupyter
<a href="https://colab.research.google.com/github/omdena/WRI/blob/master/omdena_wri/demo_omdena_wri.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Install Dependencies ``` # uninstall default version & install 2.1.0 !pip uninstall spacy !pip install spacy==2.1.0 # download pretrained english model !python -m spacy download en # install neuralcoref !pip install neuralcoref # install ktrain on Google Colab !pip3 install ktrain !pip install stellargraph # Topic Modeling !pip3 install corextopic ``` # Clone Repo ``` !git clone https://github.com/omdena/WRI.git WRI %cd WRI ``` # Load document classifier It will download 1.2 gb bert model trained on coref data. It'll take some time in first time, but every other operation will be faster. ``` # don't worry about the deprecration warrnings from omdena_wri import document_classifier ``` # Example: Positive ``` text_positive = 'File photo GURUGRAM: PWD minister Rao Narbir Singh on Sunday announced that work on the stalled Greater Southern Peripheral Road (G-SPR) project, to connect Delhi-Gurugram border to IMT Manesar, should gain pace, now that Punjab and Haryana high court has vacated a stay order on land acquisition that it had imposed in 2016.Huda had started acquisition for the 40km-long GSPR in 2016, but faced a challenge from a land owner. Some villagers had filed a case before the high court, challenging the acquisition in Naurangpur village and nearby areas, and got a stay from court.With the stay now vacated, the state will have to issue a fresh notification for acquisition, but Huda is raring to start the process.“The high court has vacated the stay over acquisition by dismissing the case filed by land owners, paving the way for construction of G-SPR as per the Master Plan,” said the PWD minister, adding that once complete, this road would offer an alternative route between Delhi-Gurugram border and IMT Manesar, which are connected only through Delhi-Gurugram expressway (NH-8) at present, and thus reduce congestion on the NH-8.The minister added the road will branch out from NH-8 at IMT Manesar, pass through Badshapur as it proceeds towards Gurugram-Faridabad road, cross MG Road and again merge with NH-8 near Sirhaul on the Delhi-Gurugram border from behind Ambience mall. The road is supposed to be constructed as per Gurugram-Manesar Plan 2031.“This road will be more like an ‘outer ring road’ for the city,” he said, adding they are trying to convince NHAI to build it, for which, he has already met Union minister Nitin Gadkari . The road is expected to benefit villages along the road, while also reducing congestion on NH-8, and thereby pollution in the city.As per sources, NHAI is not keen on building the road, due to high cost of land acquisition. “The initial survey had indicated the project was not viable due to high cost of land acquisition. That’s why a fresh feasibility study is now being carried out, in view of Haryana’s new policy, announced in late 2017, of transit oriented development (TOD), under which land along the road will get additional FAR,” said the source.Around 395 acres has to be acquired in eight villages for G-SPR. They are — Aklimpur (5.95 acre), Tekliki (62.95 acre), Sakatpur (68.90 acre), Sikohour (15.92 acre), Naurangpur (49.40 acre), Bar Gujjar (99.13 acre), Nainwal (59.92 acre) and Manesar (33.15 acre). The road will be 90m-wide with a 30m-green belt on either side. The land will be acquired by Huda and handed over to the developer — which could be NHAI — for construction.' # simply give article/text as str document_classifier(text_positive) is_conflict, tpoics, matched_policy, cosine_similarity_score = document_classifier(text_positive) print(f'Env/Land Conflict:{is_conflict}\nTpoics:{tpoics}\nMatched Policy:{matched_policy}\nCosine Similarity Score:{cosine_similarity_score}') ``` # Example: Negative Text ``` document_classifier('Life is good') text_negetive = 'The reports of attacks on Dalits in Bhima-Koregaon on the 200th anniversary of the battle between the Mahars and Peshwa army also spread in Surat on Wednesday, which has a sizable population of Marathis. Dalits in Udhna locality came out on streets, seeking justice to the perpetrators of violence against Dalits. Dalits in Udhna locality marched to the office of the District Collector and raised slogans near the office of the District Collector. The protesters also forced the local shopkeepers to shut The protesters business for the day. Messages about a Surat Bandh by Samta Sainik Dal, an organisation of Dalits, also spread on the social media. However, SSD President Raosaheb Dhepe said unless the messages are not attributed to any office bearer the messages are not authentic. There are reports of protests in southern Gujarat cities of Vapi and Valsad, where protesters burnt effigies. Gujarat State Road Transport Corporation (GSRTC) buses from Vapi and Valsad going on about a dozen routes in Maharashtra have been cancelled. These mostly include Aurangabad, Pune and Nashik among others. The railway services and the traffic were affected between Gujarat and Maharashtra. ""However, there are no reports of movement of trucks getting affected. We are carrying goods without any hassle,"" said Mukesh Dave, honorary secretary of Akhil Gujarat Truck Transport Association. Meanwhile, Gujarat had called a meeting with key officials to monitor the situation in Surat. Chief Minister Vijay Rupani headed the meeting with Minister of State for Home Pradipsinh Jadeja and in-charge DGP Pramodkumar.' document_classifier(text_negetive) ```
github_jupyter
# Predicting Customer Spending Behavior ## Data Preparation Notebook Business Scenario Making predictions is one of the primary goals in marketing data science. For some problems we are asked to predict customer spend or future sales for a company or make sales forecasts for product lines. Let us suppose that the business would like to predict the customer spending behavior. Data We have some historical transaction data from 2010 and 2011.We want to predict the spend for the year 2012. So, we could use 2010 data to predict 2011 spending behavior in advance, unless the market or business has changed significantly since the time period the data was used to fit the model. ### Load Packages ``` import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns sns.set() import os ``` ### Load data ``` transactions_dat = pd.read_csv(os.getcwd()+'/retail_transactions.csv') ``` ### Data Exploration_1 - Exploring the data structure and Columns ``` transactions_dat.head() transactions_dat.columns transactions_dat.shape transactions_dat.dtypes ``` ### Hypothesis #### Notes for data wrangling 1. Convert InvoiceDate to date 2. Calculate customer_spend by multiplying Quantity and UnitPrice 3. Perform groupby on Invoice number so that the we have each transaction on a single row 4. Add year column as we need to segregate the data for training and prediction 5. We will also need when the customer did last transaction in last year and first transaction in the year. 6. After grouping by invoice, we group them by customer 7. We would also need average spend by order 8. sum of revenue for 2010 to predict sum of revenue for 2011 9. dropping NAN customers 10. outliers ### Data Preparation #### Convert InvoiceDate to date ``` # Convert InvoiceDate to pd datetime format transactions_dat['OrderDate'] = pd.to_datetime(transactions_dat['OrderDate']) ``` #### Calculate customer_spend by multiplying Quantity and UnitPrice ``` # Calculate customer_spend by multiplying Quantity and UnitPrice transactions_dat['CustomerSpend'] = transactions_dat['Quantity']*transactions_dat['UnitPrice'] transactions_dat.shape ``` #### Perform groupby on Invoice number so that the we have each transaction on a single row ``` # Perform groupby on Invoice number so that the we have each transaction on a single row operations = {'CustomerSpend':'sum', 'OrderDate':'first', 'CustomerID':'first'} transactions_dat = transactions_dat.groupby('OrderNo').agg(operations) transactions_dat.shape ``` #### Add year column as we need to segregate the data for training and prediction ``` # Add year column as we need to segregate the data for training and prediction transactions_dat['year'] = transactions_dat['OrderDate'].dt.year ``` #### Calculate recency - when the customer did last transaction in last year ``` # when the customer did last transaction in last year? # difference between the last date of the year that is dec 31 and the invoice date transactions_dat['days_since'] = (pd.datetime(year = 2010, month = 12, day = 31)-transactions_dat['OrderDate']).dt.days transactions_dat.shape ``` #### Group by CustomerID ``` # Group the data by customer operations = {'CustomerSpend':'sum', 'days_since':['max','min','nunique']} train = transactions_dat[transactions_dat['year']==2010].groupby('CustomerID').agg(operations) train.columns train.head() train.columns = ['_'.join(col) for col in train.columns] train.head() ``` #### Calculate average spend by order ``` # Average spend per order train['average_spend_per_order'] = train['CustomerSpend_sum']/train['days_since_nunique'] ``` #### Sum of revenue for 2010 to predict sum of revenue for 2011 ``` y = transactions_dat[transactions_dat['year']==2011].groupby('CustomerID')['CustomerSpend'].sum() train.shape, y.shape ``` #### New df with all the required columns ``` df_prepared = pd.concat([train,y], axis = 1) df_prepared.columns = ['2010_customer_spend','days_since_first_purchase','days_since_last_purchase', 'number_of_purchases','avg_spend_per_order','2011_customer_spend'] df_prepared.head() df_prepared.shape ``` #### Address missing values and inf values if any ``` checks = pd.DataFrame(df_prepared.isnull().sum()).T checks = checks.append(pd.DataFrame(df_prepared.isnull().sum()/df_prepared.shape[0]*100).T) checks = checks.append(pd.DataFrame(df_prepared.isin([np.inf,-np.inf]).sum()).T) checks['names'] = ['nulls','%nulls','inf_values'] checks = checks.set_index('names') checks df_prepared = df_prepared[~df_prepared['2010_customer_spend'].isnull()] df_prepared = df_prepared[~df_prepared['2011_customer_spend'].isnull()] checks = pd.DataFrame(df_prepared.isnull().sum()).T checks = checks.append(pd.DataFrame(df_prepared.isnull().sum()/df_prepared.shape[0]*100).T) checks = checks.append(pd.DataFrame(df_prepared.isin([np.inf,-np.inf]).sum()).T) checks df_prepared.shape ``` #### Address Outliers if any ``` # Outliers df_prepared['2010_customer_spend'].plot.hist() max(df_prepared['2010_customer_spend']), min(df_prepared['2010_customer_spend']) # Remove outliers # use median instead of mean # any value out of 3 standard deviations is outlier df_prepared = df_prepared[df_prepared['2011_customer_spend'] < (df_prepared['2011_customer_spend'].median() + df_prepared['2011_customer_spend'].std()*3)] df_prepared = df_prepared[df_prepared['2010_customer_spend'] < (df_prepared['2010_customer_spend'].median() + df_prepared['2010_customer_spend'].std()*3)] df_prepared.head() df_prepared.shape ``` ### Create a new csv file for wrangled data ``` df_prepared.to_csv('df_wrangled.csv') ```
github_jupyter
``` # Add submodule paths import sys import os sys.path += ['./normalizing_flows', './baselines', './climdex'] # Optionally disable GPU #os.environ['CUDA_VISIBLE_DEVICES'] = '-1' import matplotlib.pyplot as plt import tensorflow as tf import numpy as np import pandas as pd import utils.data as data_util import utils.nn_util as nn import xarray as xr import gcsfs import shutil import os import climdex.temperature as tdex import climdex.precipitation as pdex import logging import tensorflow_probability as tfp import seaborn as sns import experiments.maxt_experiment_base as maxt import experiments.prcp_experiment_base as prcp import utils.metrics as metrics from experiments.common import upsample from models.glow import build_jflvm from baselines.dscnn import create_bmd_cnn10 from tensorflow.keras.models import load_model from normalizing_flows.models import VariationalModel from regions import southeast_us, pacific_nw from datasource import EraiRasDataLoader from utils.data import create_time_series_train_test_generator_v2 from utils.plot import image_map_factory, prcp_cmap from utils.preprocessing import remove_monthly_means from utils.distributions import normal, bernoulli_gamma from tqdm import tqdm correlation = metrics.correlation_metric() gcs = gcsfs.GCSFileSystem(project='thesis-research-255223', token='gcs.secret.json') logging.basicConfig(stream=sys.stdout, level=logging.INFO) #tf.autograph.set_verbosity(1) #tf.config.experimental_run_functions_eagerly(True) #tf.debugging.set_log_device_placement(True) data = EraiRasDataLoader(gcs_bucket='erai-rasmussen', gcs_project='thesis-research-255223', auth='gcs.secret.json') # era-interim erai_deg1 = xr.open_zarr(data.erai('daily-1deg'), consolidated=True).clip(min=0.0, max=np.inf) # 1-degree regridded rasmussen ras_deg1 = xr.open_zarr(data.rasmussen('daily-1deg'), consolidated=True).clip(min=0.0, max=np.inf) # 1/2-degree regridded rasmussen ras_deg12 = xr.open_zarr(data.rasmussen('daily-1-2deg'), consolidated=True).clip(min=0.0, max=np.inf) ras_deg14 = xr.open_zarr(data.rasmussen('daily-1-4deg'), consolidated=True).clip(min=0.0, max=np.inf) ras_deg18 = xr.open_zarr(data.rasmussen('daily-1-8deg'), consolidated=True).clip(min=0.0, max=np.inf) ras_deg116 = xr.open_zarr(data.rasmussen('daily-1-16deg'), consolidated=True) def get_train_test_splits(data_lo, data_hi, region_fn, scale, cv=False): data_lo = region_fn(data_lo) data_hi = region_fn(data_hi, scale_factor=scale) if cv: split_fn = create_time_series_train_test_generator_v2(n_splits=5, test_size=146) folds = list(split_fn(data_lo, data_hi)) return folds else: lr_train = data_lo.isel(Time=slice(0,data_lo.Time.size-2*365)) lr_test = data_lo.isel(Time=slice(data_lo.Time.size-2*365, data_lo.Time.size+1)) hr_train = data_hi.isel(Time=slice(0,data_lo.Time.size-2*365)) hr_test = data_hi.isel(Time=slice(data_lo.Time.size-2*365, data_lo.Time.size+1)) return lr_train, lr_test, hr_train, hr_test def download_jflvm(run_id, dirname, out_dir, fold=0, epoch=50, ckpt_num=10): os.makedirs(out_dir, exist_ok=True) filenames = [f'ckpt-{ckpt_num}.index', f'ckpt-{ckpt_num}.data-00000-of-00002', f'ckpt-{ckpt_num}.data-00001-of-00002'] for filename in filenames: with gcs.open(f'gs://generative-downscaling-artifact-store/glow-jflvm-final/{run_id}/artifacts/model/{dirname}/{filename}') as src: with open(f'{out_dir}/{filename}', 'wb') as dst: shutil.copyfileobj(src, dst) def download_bmd(run_id, out_dir, epoch=50): os.makedirs(out_dir, exist_ok=True) filename = f'bmd-epoch{epoch}.h5' with gcs.open(f'gs://generative-downscaling-artifact-store/bmd-final/{run_id}/artifacts/model/{filename}') as src: with open(f'{out_dir}/{filename}', 'wb') as dst: shutil.copyfileobj(src, dst) return load_model(f'{out_dir}/{filename}') def slerp(z1, z2, steps=4): assert z1.shape[0] == 1 and z2.shape[0] == 1, 'slerp only supported for one sample at a time' shape = z1.shape t = np.linspace(0.,1.,steps).reshape((steps,1)) z1, z2 = tf.reshape(z1, (z1.shape[0],-1)), tf.reshape(z2, (z2.shape[0],-1)) omega = tf.math.acos(tf.math.reduce_sum(z1/tf.norm(z1)*z2/tf.norm(z2))) sin_omega = tf.math.sin(omega) interpolated = tf.math.sin((1.0-t)*omega) / sin_omega * z1 + tf.math.sin(t*omega)/sin_omega * z2 return tf.reshape(interpolated, (steps, *shape[1:])) def sample_prediction(x, model, sigma=0.5, n=100): z, p_x = model.encode_x(x, return_log_prob=True) _, p_y = model.decode_y(z, return_log_prob=True) eps = tf.random.normal((n,*z.shape[1:]), stddev=sigma) x_, p_zx = model.decode_x(z+eps, return_log_prob=True) y_, p_zy = model.decode_y(z+eps, return_log_prob=True) return x_, y_, (p_zx, p_zy, p_x, p_y) ``` #### Max temperature ``` erai_deg1_arr = erai_deg1[['MAXT']].to_array('chan').transpose('Time','lat','lon','chan') ras_deg14_arr = ras_deg14[['MAXT']].to_array('chan').transpose('Time','lat','lon','chan') lr_train, lr_test, hr_train, hr_test = get_train_test_splits(erai_deg1_arr, ras_deg14_arr, southeast_us, scale=4) data_fold = maxt.preprocess_fold_maxt(((lr_train, hr_train),(lr_test, hr_test))) train_lo, train_hi = data_fold.train test_lo, test_hi = data_fold.test N_train, N_test = train_lo.Time.size, test_lo.Time.size (wt, ht), (wt_hi, ht_hi) = train_lo.shape[1:3], train_hi.shape[1:3] monthly_means_lo, monthly_means_hi = data_fold.monthly_means test_ds = data_fold.test_dataset(batch_size=100, buffer_size=200, map_fn_lo=upsample(wt_hi, ht_hi, tf.image.ResizeMethod.NEAREST_NEIGHBOR), mode='test') model_joint = build_jflvm((None,wt_hi,ht_hi,1), scale=4, layers=3, depth=8, min_filters=32, max_filters=256, dnet_layers=3, dnet_filters=64) model_joint.load('data/saved_models/glow-jflvm/maxt-seus/ckpt', 8) model_vars = model_joint.trainable_variables param_count = sum([tf.math.reduce_prod(var.shape) for var in model_vars]).numpy() print(f'Loaded JFLVM with {param_count} trainable parameters') x, y = next(test_ds.__iter__()) y_pred = model_joint.predict_y(x) (x_, p_x), (y_, p_y) = model_joint.sample(n=1000, return_log_prob=True) (z_x, p_zx), (z_y, p_zy) = model_joint.encode_x(x, return_log_prob=True), model_joint.encode_y(y, return_log_prob=True) plt.figure(figsize=(9,5)) sns.jointplot(x=p_x, y=p_y, kind='hex').set_axis_labels('$\\log p(x)$', '$\\log p(y)$') p_xs = [] p_ys = [] for x, y in tqdm(test_ds, total=hr_test.Time.size//100+1): y_, _, p_x = model_joint.predict_y(x, return_log_prob=True) x_, _, p_y = model_joint.predict_x(y, return_log_prob=True) p_xs.append(p_x) p_ys.append(p_y) p_xs = tf.concat(p_xs, axis=0) p_ys = tf.concat(p_ys, axis=0) plt.figure(figsize=(9,5)) sns.jointplot(x=p_xs, y=p_ys, kind='hex').set_axis_labels('$\\log p(x)$', '$\\log p(y)$') ax = plt.gca() x_samples, y_samples, (p_sx, p_sy, p_x, p_y) = sample_prediction(x[:1], model_joint, sigma=1.0, n=1000) print(p_x, p_y) sns.jointplot(x=p_sx, y=p_sy, kind='hex').set_axis_labels('$\\log p(x)$', '$\\log p(y)$') z_x, log_prob_x = model_joint.encode_x(x, return_log_prob=True) z_y, log_prob_y = model_joint.encode_y(y, return_log_prob=True) z_yp, log_prob_yp = model_joint.encode_y(y_samples, return_log_prob=True) plt.figure(figsize=(3*8,6)) plt.subplot(1,3,1) plt.imshow(tf.squeeze(tf.image.resize(x[0], (wt,ht), method='nearest')).numpy(), origin='lower') plt.subplot(1,3,2) plt.imshow(tf.squeeze(y[0]).numpy(), origin='lower') plt.subplot(1,3,3) plt.imshow(tf.squeeze(y_pred[0]).numpy(), origin='lower') zs = slerp(z_y[:1], z_y[9:10], steps=5) x_interp, p_xi = model_joint.decode_x(zs, return_log_prob=True) y_interp, p_yi = model_joint.decode_y(zs, return_log_prob=True) x_interp = tf.image.resize(x_interp, (wt, ht), method='nearest') fig, axs, plot_fn = image_map_factory(2, 5, figsize=(5,3)) plot_fn(axs[0,0], y_interp[0].numpy().squeeze(), hr_test.lat, hr_test.lon, cmap='viridis') plot_fn(axs[0,1], y_interp[1].numpy().squeeze(), hr_test.lat, hr_test.lon, cmap='viridis') plot_fn(axs[0,2], y_interp[2].numpy().squeeze(), hr_test.lat, hr_test.lon, cmap='viridis') plot_fn(axs[0,3], y_interp[3].numpy().squeeze(), hr_test.lat, hr_test.lon, cmap='viridis') plot_fn(axs[0,4], y_interp[4].numpy().squeeze(), hr_test.lat, hr_test.lon, cmap='viridis') plot_fn(axs[1,0], x_interp[0].numpy().squeeze(), lr_test.lat, lr_test.lon, cmap='viridis') plot_fn(axs[1,1], x_interp[1].numpy().squeeze(), lr_test.lat, lr_test.lon, cmap='viridis') plot_fn(axs[1,2], x_interp[2].numpy().squeeze(), lr_test.lat, lr_test.lon, cmap='viridis') plot_fn(axs[1,3], x_interp[3].numpy().squeeze(), lr_test.lat, lr_test.lon, cmap='viridis') cs = plot_fn(axs[1,4], x_interp[4].numpy().squeeze(), lr_test.lat, lr_test.lon, cmap='viridis') fig.colorbar(cs, ax=axs.ravel().tolist(), orientation='vertical', shrink=0.6, pad=0.01).set_label('daily max temperature anomalies (K)') plt.show() ``` #### Precipitation ``` erai_deg1_arr = prcp.preprocess_dataset(erai_deg1[['PRCP']], erai_deg1['PRCP'].shape) erai_deg1_arr = erai_deg1_arr.to_array('chan').transpose('Time','lat','lon','chan') ras_deg14_arr = prcp.preprocess_dataset(ras_deg14[['PRCP']], ras_deg14['PRCP'].shape) ras_deg14_arr = ras_deg14_arr.to_array('chan').transpose('Time','lat','lon','chan') lr_train, lr_test, hr_train, hr_test = get_train_test_splits(erai_deg1_arr, ras_deg14_arr, southeast_us, scale=4) data_fold = prcp.preprocess_fold_prcp(((lr_train, hr_train),(lr_test, hr_test))) train_lo_prcp, train_hi_prcp = data_fold.train test_lo_prcp, test_hi_prcp = data_fold.test N_train, N_test = train_lo_prcp.Time.size, test_lo_prcp.Time.size (wt, ht), (wt_hi, ht_hi) = train_lo_prcp.shape[1:3], train_hi_prcp.shape[1:3] test_ds_prcp = data_fold.test_dataset(batch_size=1, buffer_size=1000, map_fn_lo=upsample(wt_hi, ht_hi, tf.image.ResizeMethod.NEAREST_NEIGHBOR), mode='test') model_joint_prcp = build_jflvm((None,wt_hi,ht_hi,1), scale=4, layers=3, depth=4, min_filters=32, max_filters=256, dnet_layers=3, dnet_filters=64) model_joint_prcp.load('data/saved_models/glow-jflvm/prcp-seus/ckpt', 10) model_vars = model_joint_prcp.trainable_variables param_count = sum([tf.math.reduce_prod(var.shape) for var in model_vars]).numpy() print(f'Loaded JFLVM with {param_count} trainable parameters') for var in model_vars: print(f'{var.name}: {var.shape} {tf.math.reduce_mean(var):.3f} +/- {tf.math.reduce_std(var):.2f}') t = 229 #np.random.choice(range(hr_test.Time.size)) print(t, hr_test.Time[t].values) x, y = next(test_ds_prcp.skip(t).__iter__()) y_pred = model_joint_prcp.predict_y(x[:1]) y_samples,_ = model_joint_prcp.sample_predict_y(x[:1], temperature=0.7, n=10) y_samples = y_samples**3 y_samples = tf.where(y_samples > 5.0, y_samples, 0.0) x = tf.where(x > 1.0, x**3, 0.0) y = tf.where(y > 1.0, y**3, 0.0) y_pred = tf.where(y_pred > 1.0, y_pred**3, 0.0) x = tf.image.resize(x, (wt,ht), method='nearest') fig, axs, plot_fn = image_map_factory(2, 4, figsize=(6,3)) pmap = prcp_cmap() axs[0,0].set_visible(False) axs[0,-1].set_visible(False) plot_fn(axs[0,1], x[0].numpy().squeeze(), lr_test.lat, lr_test.lon, title='ERA-I', cmap=pmap) plot_fn(axs[0,2], y[0].numpy().squeeze(), hr_test.lat, hr_test.lon, title='WRF-4', cmap=pmap) plot_fn(axs[1,0], y_pred[0].numpy().squeeze(), hr_test.lat, hr_test.lon, title='Predicted', cmap=pmap) plot_fn(axs[1,1], y_samples[0,0].numpy().squeeze(), hr_test.lat, hr_test.lon, title='Sample 1', cmap=pmap) plot_fn(axs[1,2], y_samples[0,1].numpy().squeeze(), hr_test.lat, hr_test.lon, title='Sample 2', cmap=pmap) cs = plot_fn(axs[1,3], y_samples[0,2].numpy().squeeze(), hr_test.lat, hr_test.lon, title='Sample 3', cmap=pmap) fig.colorbar(cs, ax=axs.ravel().tolist(), orientation='vertical', shrink=0.75, pad=0.01).set_label('daily precipitation (mm)') t = 208 print(hr_test.Time[t].values) x, y = next(test_ds_prcp.skip(t).unbatch().batch(10).__iter__()) z_x, log_prob_x = model_joint_prcp.encode_x(x, return_log_prob=True) z_y, log_prob_y = model_joint_prcp.encode_y(y, return_log_prob=True) zs = slerp(z_y[:1], z_y[9:10], steps=5) x_interp, p_xi = model_joint_prcp.decode_x(zs, return_log_prob=True) y_interp, p_yi = model_joint_prcp.decode_y(zs, return_log_prob=True) x_interp = tf.where(x_interp > 1.0, x_interp**3, 0.0) y_interp = tf.where(y_interp > 1.0, y_interp**3, 0.0) x_interp = tf.image.resize(x_interp, (wt,ht), method='nearest') fig, axs, plot_fn = image_map_factory(2, 5, figsize=(5,3)) plot_fn(axs[0,0], y_interp[0].numpy().squeeze(), hr_test.lat, hr_test.lon, cmap=pmap) plot_fn(axs[0,1], y_interp[1].numpy().squeeze(), hr_test.lat, hr_test.lon, cmap=pmap) plot_fn(axs[0,2], y_interp[2].numpy().squeeze(), hr_test.lat, hr_test.lon, cmap=pmap) plot_fn(axs[0,3], y_interp[3].numpy().squeeze(), hr_test.lat, hr_test.lon, cmap=pmap) plot_fn(axs[0,4], y_interp[4].numpy().squeeze(), hr_test.lat, hr_test.lon, cmap=pmap) plot_fn(axs[1,0], x_interp[0].numpy().squeeze(), lr_test.lat, lr_test.lon, cmap=pmap) plot_fn(axs[1,1], x_interp[1].numpy().squeeze(), lr_test.lat, lr_test.lon, cmap=pmap) plot_fn(axs[1,2], x_interp[2].numpy().squeeze(), lr_test.lat, lr_test.lon, cmap=pmap) plot_fn(axs[1,3], x_interp[3].numpy().squeeze(), lr_test.lat, lr_test.lon, cmap=pmap) cs = plot_fn(axs[1,4], x_interp[4].numpy().squeeze(), lr_test.lat, lr_test.lon, cmap=pmap) fig.colorbar(cs, ax=axs.ravel().tolist(), orientation='vertical', shrink=0.6, pad=0.01).set_label('daily precipitation (mm)') plt.show() ``` #### Anomaly likelihood analysis ``` upper_quartile = test_hi.chunk({'Time': -1}).quantile(0.75, dim='Time') lower_quartile = test_hi.chunk({'Time': -1}).quantile(0.25, dim='Time') out_iqr_counts = xr.ufuncs.logical_or(test_hi > upper_quartile, test_hi < lower_quartile).sum(dim=['lat','lon']).compute() inds = out_iqr_counts.squeeze().argsort(axis=0) lr_sorted = test_lo[inds.values] lr_vals = tf.image.resize(lr_sorted.values.astype(np.float32), (wt_hi,ht_hi), method='nearest') zp, p_x_maxt = model_joint.encode_x(lr_vals, return_log_prob=True) _, p_y_maxt = model_joint.decode_y(zp, return_log_prob=True) prcp_data = xr.where(test_hi_prcp > 1.0, test_hi_prcp**3, 0.0) upper_quartile = prcp_data.chunk({'Time': -1}).quantile(0.75, dim='Time') lower_quartile = prcp_data.chunk({'Time': -1}).quantile(0.25, dim='Time') out_iqr_counts_prcp = xr.ufuncs.logical_or(prcp_data > upper_quartile, prcp_data < lower_quartile).sum(dim=['lat','lon']).compute() inds_prcp = out_iqr_counts_prcp.squeeze().argsort(axis=0) lr_sorted = test_lo_prcp[inds_prcp.values] lr_vals = tf.image.resize(lr_sorted.values.astype(np.float32), (wt_hi,ht_hi), method='nearest') zp, p_x_prcp = model_joint.encode_x(lr_vals, return_log_prob=True) _, p_y_prcp = model_joint.decode_y(zp, return_log_prob=True) anomaly_counts_maxt = out_iqr_counts[inds.values].squeeze() anomaly_counts_prcp = out_iqr_counts_prcp[inds_prcp.values].squeeze() fig, axs = plt.subplots(1,2,figsize=(2*6,4)) fig.add_subplot(111, frameon=False) # hide tick and tick label of the big axis plt.tick_params(labelcolor='none', top=False, bottom=False, left=False, right=False) plt.xlabel("Spatial anomaly count") sns.scatterplot(x=anomaly_counts_maxt.values, y=p_y_maxt, ax=axs[0], alpha=0.75) axs[0].set(ylabel='Log likelihood', title='Max temperature') axs[1].set(title='Precipitation') sns.scatterplot(x=anomaly_counts_prcp.values, y=p_y_prcp, ax=axs[1], alpha=0.75) plt.tight_layout() ``` Preciptation WRF-8 ($\frac{1}{8}^{\circ}$) ``` erai_deg1_pnw = pacific_nw(erai_deg1[['PRCP']]) ras_deg18_pnw = pacific_nw(ras_deg18[['PRCP']], scale_factor=8) erai_deg1_pnw = prcp.preprocess_dataset(erai_deg1_pnw, erai_deg1_pnw['PRCP'].shape) erai_deg1_arr = erai_deg1_pnw.to_array('chan').transpose('Time','lat','lon','chan') ras_deg18_arr = prcp.preprocess_dataset(ras_deg18_pnw, ras_deg18_pnw['PRCP'].shape) ras_deg18_arr = ras_deg18_arr.to_array('chan').transpose('Time','lat','lon','chan') lr_train = erai_deg1_arr.isel(Time=slice(0,erai_deg1_arr.Time.size-2*365+146)) lr_test = erai_deg1_arr.isel(Time=slice(erai_deg1_arr.Time.size-2*365+146, erai_deg1_arr.Time.size+1)) hr_train = ras_deg18_arr.isel(Time=slice(0,ras_deg18_arr.Time.size-2*365+146)) hr_test = ras_deg18_arr.isel(Time=slice(ras_deg18_arr.Time.size-2*365+146, ras_deg18_arr.Time.size+1)) data_fold = prcp.preprocess_fold_prcp(((lr_train, hr_train),(lr_test, hr_test))) train_lo_prcp, train_hi_prcp = data_fold.train test_lo_prcp, test_hi_prcp = data_fold.test N_train, N_test = train_lo_prcp.Time.size, test_lo_prcp.Time.size (wt, ht), (wt_hi, ht_hi) = train_lo_prcp.shape[1:3], train_hi_prcp.shape[1:3] test_ds_prcp = data_fold.test_dataset(batch_size=1, buffer_size=100, map_fn_lo=upsample(wt_hi, ht_hi, tf.image.ResizeMethod.NEAREST_NEIGHBOR), mode='test') model_joint_prcp = build_jflvm((None,wt_hi,ht_hi,1), scale=8, layers=4, depth=4, min_filters=32, max_filters=256, dnet_layers=3, dnet_filters=64) model_joint_prcp.load('data/saved_models/glow-jflvm/prcp-pnw/8x/ckpt', 5) t = 573 #np.random.choice(range(147, hr_test.Time.size)) print(t, hr_test.Time[t].values) x, y = next(test_ds_prcp.skip(t).__iter__()) y_pred = model_joint_prcp.predict_y(x[:1]) y_samples,_ = model_joint_prcp.sample_predict_y(x[:1], temperature=0.7, n=10) y_samples = y_samples**3 y_samples = tf.where(y_samples > 2.0, y_samples, 0.0) x = tf.where(x > 1.0, x**3, 0.0) y = tf.where(y > 1.0, y**3, 0.0) y_pred = y_pred**3 y_pred = tf.where(y_pred > 2.0, y_pred, 0.0) x = tf.image.resize(x, (wt,ht), method='nearest') fig, axs, plot_fn = image_map_factory(2, 3, figsize=(6,3)) pmap = prcp_cmap() plot_fn(axs[0,0], x[0].numpy().squeeze(), lr_test.lat, lr_test.lon, title='ERA-I', cmap=pmap) plot_fn(axs[0,1], y[0].numpy().squeeze(), hr_test.lat, hr_test.lon, title='WRF-8', cmap=pmap) plot_fn(axs[0,2], y_pred[0].numpy().squeeze(), hr_test.lat, hr_test.lon, title='Predicted', cmap=pmap) plot_fn(axs[1,0], y_samples[0,0].numpy().squeeze(), hr_test.lat, hr_test.lon, title='Sample 1', cmap=pmap) plot_fn(axs[1,1], y_samples[0,1].numpy().squeeze(), hr_test.lat, hr_test.lon, title='Sample 2', cmap=pmap) cs = plot_fn(axs[1,2], y_samples[0,2].numpy().squeeze(), hr_test.lat, hr_test.lon, title='Sample 3', cmap=pmap) fig.colorbar(cs, ax=axs.ravel().tolist(), orientation='vertical', shrink=0.75, pad=0.01).set_label('daily precipitation (mm)') ```
github_jupyter
# Word Embeddings: Ungraded Practice Notebook In this ungraded notebook, you'll try out all the individual techniques that you learned about in the lecture. Practicing on small examples will prepare you for the graded assignment, where you will combine the techniques in more advanced ways to create word embeddings from a real-life corpus. This notebook is made of two main parts: data preparation, and the continuous bag-of-words (CBOW) model. To get started, import and initialize all the libraries you will need. ``` import sys !{sys.executable} -m pip install emoji import re import nltk from nltk.tokenize import word_tokenize import emoji import numpy as np from utils2 import get_dict nltk.download('punkt') # download pre-trained Punkt tokenizer for English ``` # Data preparation In the data preparation phase, starting with a corpus of text, you will: - Clean and tokenize the corpus. - Extract the pairs of context words and center word that will make up the training data set for the CBOW model. The context words are the features that will be fed into the model, and the center words are the target values that the model will learn to predict. - Create simple vector representations of the context words (features) and center words (targets) that can be used by the neural network of the CBOW model. ## Cleaning and tokenization To demonstrate the cleaning and tokenization process, consider a corpus that contains emojis and various punctuation signs. ``` corpus = 'Who ❤️ "word embeddings" in 2020? I do!!!' ``` First, replace all interrupting punctuation signs — such as commas and exclamation marks — with periods. ``` print(f'Corpus: {corpus}') data = re.sub(r'[,!?;-]+', '.', corpus) print(f'After cleaning punctuation: {data}') ``` Next, use NLTK's tokenization engine to split the corpus into individual tokens. ``` print(f'Initial string: {data}') data = nltk.word_tokenize(data) print(f'After tokenization: {data}') ``` Finally, as you saw in the lecture, get rid of numbers and punctuation other than periods, and convert all the remaining tokens to lowercase. ``` print(f'Initial list of tokens: {data}') data = [ ch.lower() for ch in data if ch.isalpha() or ch == '.' or emoji.get_emoji_regexp().search(ch) ] print(f'After cleaning: {data}') ``` Note that the heart emoji is considered as a token just like any normal word. Now let's streamline the cleaning and tokenization process by wrapping the previous steps in a function. ``` def tokenize(corpus): data = re.sub(r'[,!?;-]+', '.', corpus) data = nltk.word_tokenize(data) # tokenize string to words data = [ ch.lower() for ch in data if ch.isalpha() or ch == '.' or emoji.get_emoji_regexp().search(ch) ] return data ``` Apply this function to the corpus that you'll be working on in the rest of this notebook: "I am happy because I am learning" ``` corpus = 'I am happy because I am learning' print(f'Corpus: {corpus}') words = tokenize(corpus) print(f'Words (tokens): {words}') ``` **Now try it out yourself with your own sentence.** ``` tokenize("Now it's your turn: try with your own sentence!") ``` ## Sliding window of words Now that you have transformed the corpus into a list of clean tokens, you can slide a window of words across this list. For each window you can extract a center word and the context words. The `get_windows` function in the next cell was introduced in the lecture. ``` def get_windows(words, C): i = C while i < len(words) - C: center_word = words[i] context_words = words[(i - C):i] + words[(i+1):(i+C+1)] yield context_words, center_word i += 1 ``` The first argument of this function is a list of words (or tokens). The second argument, `C`, is the context half-size. Recall that for a given center word, the context words are made of `C` words to the left and `C` words to the right of the center word. Here is how you can use this function to extract context words and center words from a list of tokens. These context and center words will make up the training set that you will use to train the CBOW model. ``` for x, y in get_windows( ['i', 'am', 'happy', 'because', 'i', 'am', 'learning'], 2 ): print(f'{x}\t{y}') ``` The first example of the training set is made of: - the context words "i", "am", "because", "i", - and the center word to be predicted: "happy". **Now try it out yourself. In the next cell, you can change both the sentence and the context half-size.** ``` for x, y in get_windows(tokenize("Now it's your turn: try with your own sentence!"), 1): print(f'{x}\t{y}') ``` ## Transforming words into vectors for the training set To finish preparing the training set, you need to transform the context words and center words into vectors. ### Mapping words to indices and indices to words The center words will be represented as one-hot vectors, and the vectors that represent context words are also based on one-hot vectors. To create one-hot word vectors, you can start by mapping each unique word to a unique integer (or index). We have provided a helper function, `get_dict`, that creates a Python dictionary that maps words to integers and back. ``` word2Ind, Ind2word = get_dict(words) ``` Here's the dictionary that maps words to numeric indices. ``` word2Ind ``` You can use this dictionary to get the index of a word. ``` print("Index of the word 'i': ",word2Ind['i']) ``` And conversely, here's the dictionary that maps indices to words. ``` Ind2word print("Word which has index 2: ",Ind2word[2] ) ``` Finally, get the length of either of these dictionaries to get the size of the vocabulary of your corpus, in other words the number of different words making up the corpus. ``` V = len(word2Ind) print("Size of vocabulary: ", V) ``` ### Getting one-hot word vectors Recall from the lecture that you can easily convert an integer, $n$, into a one-hot vector. Consider the word "happy". First, retrieve its numeric index. ``` n = word2Ind['happy'] n ``` Now create a vector with the size of the vocabulary, and fill it with zeros. ``` center_word_vector = np.zeros(V) center_word_vector ``` You can confirm that the vector has the right size. ``` len(center_word_vector) == V ``` Next, replace the 0 of the $n$-th element with a 1. ``` center_word_vector[n] = 1 ``` And you have your one-hot word vector. ``` center_word_vector ``` **You can now group all of these steps in a convenient function, which takes as parameters: a word to be encoded, a dictionary that maps words to indices, and the size of the vocabulary.** ``` def word_to_one_hot_vector(word, word2Ind, V): # BEGIN your code here one_hot_vector = np.zeros(V) one_hot_vector[word2Ind[word]] = 1 # END your code here return one_hot_vector ``` Check that it works as intended. ``` word_to_one_hot_vector('happy', word2Ind, V) ``` **What is the word vector for "learning"?** ``` # BEGIN your code here word_to_one_hot_vector('learning', word2Ind, V) # END your code here ``` Expected output: array([0., 0., 0., 0., 1.]) ### Getting context word vectors To create the vectors that represent context words, you will calculate the average of the one-hot vectors representing the individual words. Let's start with a list of context words. ``` context_words = ['i', 'am', 'because', 'i'] ``` Using Python's list comprehension construct and the `word_to_one_hot_vector` function that you created in the previous section, you can create a list of one-hot vectors representing each of the context words. ``` context_words_vectors = [word_to_one_hot_vector(w, word2Ind, V) for w in context_words] context_words_vectors ``` And you can now simply get the average of these vectors using numpy's `mean` function, to get the vector representation of the context words. ``` np.mean(context_words_vectors, axis=0) ``` Note the `axis=0` parameter that tells `mean` to calculate the average of the rows (if you had wanted the average of the columns, you would have used `axis=1`). **Now create the `context_words_to_vector` function that takes in a list of context words, a word-to-index dictionary, and a vocabulary size, and outputs the vector representation of the context words.** ``` def context_words_to_vector(context_words, word2Ind, V): # BEGIN your code here context_words_vectors = [word_to_one_hot_vector(w, word2Ind, V) for w in context_words] context_words_vectors = np.mean(context_words_vectors, axis=0) # END your code here return context_words_vectors ``` And check that you obtain the same output as the manual approach above. ``` context_words_to_vector(['i', 'am', 'because', 'i'], word2Ind, V) ``` **What is the vector representation of the context words "am happy i am"?** ``` # BEGIN your code here context_words_to_vector(['am', 'happy', 'i', 'am'], word2Ind, V) # END your code here ``` Expected output: array([0.5 , 0. , 0.25, 0.25, 0. ]) ## Building the training set You can now combine the functions that you created in the previous sections, to build a training set for the CBOW model, starting from the following tokenized corpus. ``` words ``` To do this you need to use the sliding window function (`get_windows`) to extract the context words and center words, and you then convert these sets of words into a basic vector representation using `word_to_one_hot_vector` and `context_words_to_vector`. ``` for context_words, center_word in get_windows(words, 2): # reminder: 2 is the context half-size print(f'Context words: {context_words} -> {context_words_to_vector(context_words, word2Ind, V)}') print(f'Center word: {center_word} -> {word_to_one_hot_vector(center_word, word2Ind, V)}') print() ``` In this practice notebook you'll be performing a single iteration of training using a single example, but in this week's assignment you'll train the CBOW model using several iterations and batches of example. Here is how you would use a Python generator function (remember the `yield` keyword from the lecture?) to make it easier to iterate over a set of examples. ``` def get_training_example(words, C, word2Ind, V): for context_words, center_word in get_windows(words, C): yield context_words_to_vector(context_words, word2Ind, V), word_to_one_hot_vector(center_word, word2Ind, V) ``` The output of this function can be iterated on to get successive context word vectors and center word vectors, as demonstrated in the next cell. ``` for context_words_vector, center_word_vector in get_training_example(words, 2, word2Ind, V): print(f'Context words vector: {context_words_vector}') print(f'Center word vector: {center_word_vector}') print() ``` Your training set is ready, you can now move on to the CBOW model itself. # The continuous bag-of-words model The CBOW model is based on a neural network, the architecture of which looks like the figure below, as you'll recall from the lecture. <div style="width:image width px; font-size:100%; text-align:center;"><img src='cbow_model_architecture.png?1' alt="alternate text" width="width" height="height" style="width:917;height:337;" /> Figure 1 </div> This part of the notebook will walk you through: - The two activation functions used in the neural network. - Forward propagation. - Cross-entropy loss. - Backpropagation. - Gradient descent. - Extracting the word embedding vectors from the weight matrices once the neural network has been trained. ## Activation functions Let's start by implementing the activation functions, ReLU and softmax. ### ReLU ReLU is used to calculate the values of the hidden layer, in the following formulas: \begin{align} \mathbf{z_1} &= \mathbf{W_1}\mathbf{x} + \mathbf{b_1} \tag{1} \\ \mathbf{h} &= \mathrm{ReLU}(\mathbf{z_1}) \tag{2} \\ \end{align} Let's fix a value for $\mathbf{z_1}$ as a working example. ``` np.random.seed(10) z_1 = 10*np.random.rand(5, 1)-5 z_1 ``` To get the ReLU of this vector, you want all the negative values to become zeros. First create a copy of this vector. ``` h = z_1.copy() ``` Now determine which of its values are negative. ``` h < 0 ``` You can now simply set all of the values which are negative to 0. ``` h[h < 0] = 0 ``` And that's it: you have the ReLU of $\mathbf{z_1}$! ``` h ``` **Now implement ReLU as a function.** ``` def relu(z): # BEGIN your code here result = z.copy() result[result < 0] = 0 # END your code here return result ``` **And check that it's working.** ``` z = np.array([[-1.25459881], [ 4.50714306], [ 2.31993942], [ 0.98658484], [-3.4398136 ]]) relu(z) ``` Expected output: array([[0. ], [4.50714306], [2.31993942], [0.98658484], [0. ]]) ### Softmax The second activation function that you need is softmax. This function is used to calculate the values of the output layer of the neural network, using the following formulas: \begin{align} \mathbf{z_2} &= \mathbf{W_2}\mathbf{h} + \mathbf{b_2} \tag{3} \\ \mathbf{\hat y} &= \mathrm{softmax}(\mathbf{z_2}) \tag{4} \\ \end{align} To calculate softmax of a vector $\mathbf{z}$, the $i$-th component of the resulting vector is given by: $$ \textrm{softmax}(\textbf{z})_i = \frac{e^{z_i} }{\sum\limits_{j=1}^{V} e^{z_j} } \tag{5} $$ Let's work through an example. ``` z = np.array([9, 8, 11, 10, 8.5]) z ``` You'll need to calculate the exponentials of each element, both for the numerator and for the denominator. ``` e_z = np.exp(z) e_z ``` The denominator is equal to the sum of these exponentials. ``` sum_e_z = np.sum(e_z) sum_e_z ``` And the value of the first element of $\textrm{softmax}(\textbf{z})$ is given by: ``` e_z[0]/sum_e_z ``` This is for one element. You can use numpy's vectorized operations to calculate the values of all the elements of the $\textrm{softmax}(\textbf{z})$ vector in one go. **Implement the softmax function.** ``` def softmax(z): # BEGIN your code here e_z = np.exp(z) sum_e_z = np.sum(e_z) return e_z / sum_e_z # END your code here ``` **Now check that it works.** ``` softmax([9, 8, 11, 10, 8.5]) ``` Expected output: array([0.08276948, 0.03044919, 0.61158833, 0.22499077, 0.05020223]) ## Dimensions: 1-D arrays vs 2-D column vectors Before moving on to implement forward propagation, backpropagation, and gradient descent, let's have a look at the dimensions of the vectors you've been handling until now. Create a vector of length $V$ filled with zeros. ``` x_array = np.zeros(V) x_array ``` This is a 1-dimensional array, as revealed by the `.shape` property of the array. ``` x_array.shape ``` To perform matrix multiplication in the next steps, you actually need your column vectors to be represented as a matrix with one column. In numpy, this matrix is represented as a 2-dimensional array. The easiest way to convert a 1D vector to a 2D column matrix is to set its `.shape` property to the number of rows and one column, as shown in the next cell. ``` x_column_vector = x_array.copy() x_column_vector.shape = (V, 1) # alternatively ... = (x_array.shape[0], 1) x_column_vector ``` The shape of the resulting "vector" is: ``` x_column_vector.shape ``` So you now have a 5x1 matrix that you can use to perform standard matrix multiplication. ## Forward propagation Let's dive into the neural network itself, which is shown below with all the dimensions and formulas you'll need. <div style="width:image width px; font-size:100%; text-align:center;"><img src='cbow_model_dimensions_single_input.png?2' alt="alternate text" width="width" height="height" style="width:839;height:349;" /> Figure 2 </div> Set $N$ equal to 3. Remember that $N$ is a hyperparameter of the CBOW model that represents the size of the word embedding vectors, as well as the size of the hidden layer. ``` N = 3 ``` ### Initialization of the weights and biases Before you start training the neural network, you need to initialize the weight matrices and bias vectors with random values. In the assignment you will implement a function to do this yourself using `numpy.random.rand`. In this notebook, we've pre-populated these matrices and vectors for you. ``` W1 = np.array([[ 0.41687358, 0.08854191, -0.23495225, 0.28320538, 0.41800106], [ 0.32735501, 0.22795148, -0.23951958, 0.4117634 , -0.23924344], [ 0.26637602, -0.23846886, -0.37770863, -0.11399446, 0.34008124]]) W2 = np.array([[-0.22182064, -0.43008631, 0.13310965], [ 0.08476603, 0.08123194, 0.1772054 ], [ 0.1871551 , -0.06107263, -0.1790735 ], [ 0.07055222, -0.02015138, 0.36107434], [ 0.33480474, -0.39423389, -0.43959196]]) b1 = np.array([[ 0.09688219], [ 0.29239497], [-0.27364426]]) b2 = np.array([[ 0.0352008 ], [-0.36393384], [-0.12775555], [-0.34802326], [-0.07017815]]) ``` **Check that the dimensions of these matrices match those shown in the figure above.** ``` # BEGIN your code here print(f'V (vocabulary size): {V}') print(f'N (embedding size / size of the hidden layer): {N}') print(f'size of W1: {W1.shape} (NxV)') print(f'size of b1: {b1.shape} (Nx1)') print(f'size of W2: {W1.shape} (VxN)') print(f'size of b2: {b2.shape} (Vx1)') # END your code here ``` ### Training example Run the next cells to get the first training example, made of the vector representing the context words "i am because i", and the target which is the one-hot vector representing the center word "happy". > You don't need to worry about the Python syntax, but there are some explanations below if you want to know what's happening behind the scenes. ``` training_examples = get_training_example(words, 2, word2Ind, V) ``` > `get_training_examples`, which uses the `yield` keyword, is known as a generator. When run, it builds an iterator, which is a special type of object that... you can iterate on (using a `for` loop for instance), to retrieve the successive values that the function generates. > > In this case `get_training_examples` `yield`s training examples, and iterating on `training_examples` will return the successive training examples. ``` x_array, y_array = next(training_examples) ``` > `next` is another special keyword, which gets the next available value from an iterator. Here, you'll get the very first value, which is the first training example. If you run this cell again, you'll get the next value, and so on until the iterator runs out of values to return. > > In this notebook `next` is used because you will only be performing one iteration of training. In this week's assignment with the full training over several iterations you'll use regular `for` loops with the iterator that supplies the training examples. The vector representing the context words, which will be fed into the neural network, is: ``` x_array ``` The one-hot vector representing the center word to be predicted is: ``` y_array ``` Now convert these vectors into matrices (or 2D arrays) to be able to perform matrix multiplication on the right types of objects, as explained above. ``` x = x_array.copy() x.shape = (V, 1) print('x') print(x) print() y = y_array.copy() y.shape = (V, 1) print('y') print(y) ``` ### Values of the hidden layer Now that you have initialized all the variables that you need for forward propagation, you can calculate the values of the hidden layer using the following formulas: \begin{align} \mathbf{z_1} = \mathbf{W_1}\mathbf{x} + \mathbf{b_1} \tag{1} \\ \mathbf{h} = \mathrm{ReLU}(\mathbf{z_1}) \tag{2} \\ \end{align} First, you can calculate the value of $\mathbf{z_1}$. ``` z1 = np.dot(W1, x) + b1 ``` > `np.dot` is numpy's function for matrix multiplication. As expected you get an $N$ by 1 matrix, or column vector with $N$ elements, where $N$ is equal to the embedding size, which is 3 in this example. ``` z1 ``` You can now take the ReLU of $\mathbf{z_1}$ to get $\mathbf{h}$, the vector with the values of the hidden layer. ``` h = relu(z1) h ``` Applying ReLU means that the negative element of $\mathbf{z_1}$ has been replaced with a zero. ### Values of the output layer Here are the formulas you need to calculate the values of the output layer, represented by the vector $\mathbf{\hat y}$: \begin{align} \mathbf{z_2} &= \mathbf{W_2}\mathbf{h} + \mathbf{b_2} \tag{3} \\ \mathbf{\hat y} &= \mathrm{softmax}(\mathbf{z_2}) \tag{4} \\ \end{align} **First, calculate $\mathbf{z_2}$.** ``` # BEGIN your code here z2 = np.dot(W2, h) + b2 # END your code here z2 ``` Expected output: array([[-0.31973737], [-0.28125477], [-0.09838369], [-0.33512159], [-0.19919612]]) This is a $V$ by 1 matrix, where $V$ is the size of the vocabulary, which is 5 in this example. **Now calculate the value of $\mathbf{\hat y}$.** ``` # BEGIN your code here y_hat = softmax(z2) # END your code here y_hat ``` Expected output: array([[0.18519074], [0.19245626], [0.23107446], [0.18236353], [0.20891502]]) As you've performed the calculations with random matrices and vectors (apart from the input vector), the output of the neural network is essentially random at this point. The learning process will adjust the weights and biases to match the actual targets better. **That being said, what word did the neural network predict?** <details> <summary> <font size="3" color="darkgreen"><b>Solution</b></font> </summary> <p>The neural network predicted the word "happy": the largest element of $\mathbf{\hat y}$ is the third one, and the third word of the vocabulary is "happy".</p> <p>Here's how you could implement this in Python:</p> <p><code>print(Ind2word[np.argmax(y_hat)])</code></p> Well done, you've completed the forward propagation phase! ## Cross-entropy loss Now that you have the network's prediction, you can calculate the cross-entropy loss to determine how accurate the prediction was compared to the actual target. > Remember that you are working on a single training example, not on a batch of examples, which is why you are using *loss* and not *cost*, which is the generalized form of loss. First let's recall what the prediction was. ``` y_hat ``` And the actual target value is: ``` y ``` The formula for cross-entropy loss is: $$ J=-\sum\limits_{k=1}^{V}y_k\log{\hat{y}_k} \tag{6}$$ **Implement the cross-entropy loss function.** Here are a some hints if you're stuck. <details> <summary> <font size="3" color="darkgreen"><b>Hint 1</b></font> </summary> <p>To multiply two numpy matrices (such as <code>y</code> and <code>y_hat</code>) element-wise, you can simply use the <code>*</code> operator.</p> <details> <summary> <font size="3" color="darkgreen"><b>Hint 2</b></font> </summary> <p>Once you have a vector equal to the element-wise multiplication of <code>y</code> and <code>y_hat</code>, you can use <code>np.sum</code> to calculate the sum of the elements of this vector.</p> ``` def cross_entropy_loss(y_predicted, y_actual): # BEGIN your code here loss = np.sum(-np.log(y_hat)*y) # END your code here return loss ``` **Now use this function to calculate the loss with the actual values of $\mathbf{y}$ and $\mathbf{\hat y}$.** ``` cross_entropy_loss(y_hat, y) ``` Expected output: 1.4650152923611106 This value is neither good nor bad, which is expected as the neural network hasn't learned anything yet. The actual learning will start during the next phase: backpropagation. ## Backpropagation The formulas that you will implement for backpropagation are the following. \begin{align} \frac{\partial J}{\partial \mathbf{W_1}} &= \rm{ReLU}\left ( \mathbf{W_2^\top} (\mathbf{\hat{y}} - \mathbf{y})\right )\mathbf{x}^\top \tag{7}\\ \frac{\partial J}{\partial \mathbf{W_2}} &= (\mathbf{\hat{y}} - \mathbf{y})\mathbf{h^\top} \tag{8}\\ \frac{\partial J}{\partial \mathbf{b_1}} &= \rm{ReLU}\left ( \mathbf{W_2^\top} (\mathbf{\hat{y}} - \mathbf{y})\right ) \tag{9}\\ \frac{\partial J}{\partial \mathbf{b_2}} &= \mathbf{\hat{y}} - \mathbf{y} \tag{10} \end{align} > Note: these formulas are slightly simplified compared to the ones in the lecture as you're working on a single training example, whereas the lecture provided the formulas for a batch of examples. In the assignment you'll be implementing the latter. Let's start with an easy one. **Calculate the partial derivative of the loss function with respect to $\mathbf{b_2}$, and store the result in `grad_b2`.** $$\frac{\partial J}{\partial \mathbf{b_2}} = \mathbf{\hat{y}} - \mathbf{y} \tag{10}$$ ``` # BEGIN your code here grad_b2 = y_hat - y # END your code here grad_b2 ``` Expected output: array([[ 0.18519074], [ 0.19245626], [-0.76892554], [ 0.18236353], [ 0.20891502]]) **Next, calculate the partial derivative of the loss function with respect to $\mathbf{W_2}$, and store the result in `grad_W2`.** $$\frac{\partial J}{\partial \mathbf{W_2}} = (\mathbf{\hat{y}} - \mathbf{y})\mathbf{h^\top} \tag{8}$$ > Hint: use `.T` to get a transposed matrix, e.g. `h.T` returns $\mathbf{h^\top}$. ``` # BEGIN your code here grad_W2 = np.dot(y_hat - y, h.T) # END your code here grad_W2 ``` Expected output: array([[ 0.06756476, 0.11798563, 0. ], [ 0.0702155 , 0.12261452, 0. ], [-0.28053384, -0.48988499, 0. ], [ 0.06653328, 0.1161844 , 0. ], [ 0.07622029, 0.13310045, 0. ]]) **Now calculate the partial derivative with respect to $\mathbf{b_1}$ and store the result in `grad_b1`.** $$\frac{\partial J}{\partial \mathbf{b_1}} = \rm{ReLU}\left ( \mathbf{W_2^\top} (\mathbf{\hat{y}} - \mathbf{y})\right ) \tag{9}$$ ``` # BEGIN your code here grad_b1 = relu(np.dot(W2.T, y_hat - y)) # END your code here grad_b1 ``` Expected output: array([[0. ], [0. ], [0.17045858]]) **Finally, calculate the partial derivative of the loss with respect to $\mathbf{W_1}$, and store it in `grad_W1`.** $$\frac{\partial J}{\partial \mathbf{W_1}} = \rm{ReLU}\left ( \mathbf{W_2^\top} (\mathbf{\hat{y}} - \mathbf{y})\right )\mathbf{x}^\top \tag{7}$$ ``` # BEGIN your code here grad_W1 = np.dot(relu(np.dot(W2.T, y_hat - y)), x.T) # END your code here grad_W1 ``` Expected output: array([[0. , 0. , 0. , 0. , 0. ], [0. , 0. , 0. , 0. , 0. ], [0.04261464, 0.04261464, 0. , 0.08522929, 0. ]]) Before moving on to gradient descent, double-check that all the matrices have the expected dimensions. ``` # BEGIN your code here print(f'V (vocabulary size): {V}') print(f'N (embedding size / size of the hidden layer): {N}') print(f'size of grad_W1: {grad_W1.shape} (NxV)') print(f'size of grad_b1: {grad_b1.shape} (Nx1)') print(f'size of grad_W2: {grad_W1.shape} (VxN)') print(f'size of grad_b2: {grad_b2.shape} (Vx1)') # END your code here ``` ## Gradient descent During the gradient descent phase, you will update the weights and biases by subtracting $\alpha$ times the gradient from the original matrices and vectors, using the following formulas. \begin{align} \mathbf{W_1} &:= \mathbf{W_1} - \alpha \frac{\partial J}{\partial \mathbf{W_1}} \tag{11}\\ \mathbf{W_2} &:= \mathbf{W_2} - \alpha \frac{\partial J}{\partial \mathbf{W_2}} \tag{12}\\ \mathbf{b_1} &:= \mathbf{b_1} - \alpha \frac{\partial J}{\partial \mathbf{b_1}} \tag{13}\\ \mathbf{b_2} &:= \mathbf{b_2} - \alpha \frac{\partial J}{\partial \mathbf{b_2}} \tag{14}\\ \end{align} First, let set a value for $\alpha$. ``` alpha = 0.03 ``` The updated weight matrix $\mathbf{W_1}$ will be: ``` W1_new = W1 - alpha * grad_W1 ``` Let's compare the previous and new values of $\mathbf{W_1}$: ``` print('old value of W1:') print(W1) print() print('new value of W1:') print(W1_new) ``` The difference is very subtle (hint: take a closer look at the last row), which is why it takes a fair amount of iterations to train the neural network until it reaches optimal weights and biases starting from random values. **Now calculate the new values of $\mathbf{W_2}$ (to be stored in `W2_new`), $\mathbf{b_1}$ (in `b1_new`), and $\mathbf{b_2}$ (in `b2_new`).** \begin{align} \mathbf{W_2} &:= \mathbf{W_2} - \alpha \frac{\partial J}{\partial \mathbf{W_2}} \tag{12}\\ \mathbf{b_1} &:= \mathbf{b_1} - \alpha \frac{\partial J}{\partial \mathbf{b_1}} \tag{13}\\ \mathbf{b_2} &:= \mathbf{b_2} - \alpha \frac{\partial J}{\partial \mathbf{b_2}} \tag{14}\\ \end{align} ``` # BEGIN your code here W2_new = W2 - alpha * grad_W2 b1_new = b1 - alpha * grad_b1 b2_new = b2 - alpha * grad_b2 # END your code here print('W2_new') print(W2_new) print() print('b1_new') print(b1_new) print() print('b2_new') print(b2_new) ``` Expected output: W2_new [[-0.22384758 -0.43362588 0.13310965] [ 0.08265956 0.0775535 0.1772054 ] [ 0.19557112 -0.04637608 -0.1790735 ] [ 0.06855622 -0.02363691 0.36107434] [ 0.33251813 -0.3982269 -0.43959196]] b1_new [[ 0.09688219] [ 0.29239497] [-0.27875802]] b2_new [[ 0.02964508] [-0.36970753] [-0.10468778] [-0.35349417] [-0.0764456 ]] Congratulations, you have completed one iteration of training using one training example! You'll need many more iterations to fully train the neural network, and you can optimize the learning process by training on batches of examples, as described in the lecture. You will get to do this during this week's assignment. ## Extracting word embedding vectors Once you have finished training the neural network, you have three options to get word embedding vectors for the words of your vocabulary, based on the weight matrices $\mathbf{W_1}$ and/or $\mathbf{W_2}$. ### Option 1: extract embedding vectors from $\mathbf{W_1}$ The first option is to take the columns of $\mathbf{W_1}$ as the embedding vectors of the words of the vocabulary, using the same order of the words as for the input and output vectors. > Note: in this practice notebook the values of the word embedding vectors are meaningless after a single iteration with just one training example, but here's how you would proceed after the training process is complete. For example $\mathbf{W_1}$ is this matrix: ``` W1 ``` The first column, which is a 3-element vector, is the embedding vector of the first word of your vocabulary. The second column is the word embedding vector for the second word, and so on. The first, second, etc. words are ordered as follows. ``` for i in range(V): print(Ind2word[i]) ``` So the word embedding vectors corresponding to each word are: ``` # loop through each word of the vocabulary for word in word2Ind: # extract the column corresponding to the index of the word in the vocabulary word_embedding_vector = W1[:, word2Ind[word]] print(f'{word}: {word_embedding_vector}') ``` ### Option 2: extract embedding vectors from $\mathbf{W_2}$ The second option is to take $\mathbf{W_2}$ transposed, and take its columns as the word embedding vectors just like you did for $\mathbf{W_1}$. ``` W2.T # loop through each word of the vocabulary for word in word2Ind: # extract the column corresponding to the index of the word in the vocabulary word_embedding_vector = W2.T[:, word2Ind[word]] print(f'{word}: {word_embedding_vector}') ``` ### Option 3: extract embedding vectors from $\mathbf{W_1}$ and $\mathbf{W_2}$ The third option, which is the one you will use in this week's assignment, uses the average of $\mathbf{W_1}$ and $\mathbf{W_2^\top}$. **Calculate the average of $\mathbf{W_1}$ and $\mathbf{W_2^\top}$, and store the result in `W3`.** ``` # BEGIN your code here W3 = (W1+W2.T)/2 # END your code here W3 ``` Expected output: array([[ 0.09752647, 0.08665397, -0.02389858, 0.1768788 , 0.3764029 ], [-0.05136565, 0.15459171, -0.15029611, 0.19580601, -0.31673866], [ 0.19974284, -0.03063173, -0.27839106, 0.12353994, -0.04975536]]) Extracting the word embedding vectors works just like the two previous options, by taking the columns of the matrix you've just created. ``` # loop through each word of the vocabulary for word in word2Ind: # extract the column corresponding to the index of the word in the vocabulary word_embedding_vector = W3[:, word2Ind[word]] print(f'{word}: {word_embedding_vector}') ``` You're now ready to take on this week's assignment! ### How this practice relates to and differs from the upcoming graded assignment - In the assignment, for each iteration of training you will use batches of examples instead of a single example. The formulas for forward propagation and backpropagation will be modified accordingly, and you will use cross-entropy cost instead of cross-entropy loss. - You will also complete several iterations of training, until you reach an acceptably low cross-entropy cost, at which point you can extract good word embeddings from the weight matrices. - After extracting the word embedding vectors, you will use principal component analysis (PCA) to visualize the vectors, which will enable you to perform an intrinsic evaluation of the quality of the vectors, as explained in the lecture.
github_jupyter
# X To A Combined Forced ``` import os import sys from pathlib import Path from IPython.display import display, HTML, Markdown import numpy as np import pandas as pd import matplotlib as mpl import matplotlib.pyplot as plt import seaborn as sns # Project level imports sys.path.insert(0, '../lib') from larval_gonad.notebook import Nb from larval_gonad.plotting import make_figs, TSNEPlot from larval_gonad.config import memory from larval_gonad.x_to_a import CHROMS_CHR, AUTOSOMES_CHR, commonly_expressed, multi_chrom_boxplot, get_gene_sets from larval_gonad.cell_selection import SOMA, EARLY_GERM, LATE_GERM # Setup notebook nbconfig = Nb.setup_notebook('2018-03-16_x2a_combined_forced', seurat_dir='../output/combined_testis_force') norm = nbconfig.seurat.get_normalized_read_counts() tsne = nbconfig.seurat.get_tsne() clusters = nbconfig.seurat.get_clusters() clus4 = clusters['res.0.4'] clus4.name = 'cluster' clus6 = clusters['res.0.6'] clus6.name = 'cluster' clus12 = clusters['res.1.2'] clus12.name = 'cluster' norm.shape TSNEPlot(data=tsne.join(clusters), hue='res.0.4', palette=sns.color_palette('tab20', n_colors=13), s=8) biomarkers = pd.read_csv(Path(nbconfig.seurat_dir, 'biomarkers_0.4.tsv'), sep='\t', index_col='primary_FBgn') biomarkers = biomarkers.query('p_val_adj <= 0.001').sort_values(['cluster', 'avg_logFC']) biomarkers.query(f'gene_symbol in {SOMA}') biomarkers.query(f'gene_symbol in {EARLY_GERM}') biomarkers.query(f'gene_symbol in {LATE_GERM}') header = [ 'FBgn', 'name', 'dbtype', 'description', ] gil = pd.read_csv('../data/external/fb_gene-anatomy/REXPOUT.txt', sep='|', skiprows=2, header=None, names=header, usecols=[0, 3]).fillna('') gil = gil.applymap(lambda x: x.strip()) gil.head() for g, dat in gil.groupby('description'): if ('sperm' not in g) & ('testis' not in g) & ('hub' not in g): continue FBgns = dat.FBgn.unique().tolist() clusters = biomarkers.query(f'primary_FBgn in {FBgns}').cluster.unique() gene_symbols = [nbconfig.fbgn2symbol[x] for x in biomarkers.query(f'primary_FBgn in {FBgns}').index.unique().tolist()] if len(clusters) > 0: print(g) print('\tCluster:', clusters) print('\tGenes:', gene_symbols) print('') biomarkers.head() biomarkers.query('primary_FBgn in ["FBgn0264383", ]') ``` # House Keeping ``` gene_sets = get_gene_sets() expressed = commonly_expressed(norm) data = norm.loc[expressed, :].T.join(clus4) dat = data.groupby('cluster').median().T.reset_index()\ .melt(id_vars='index')\ .merge(nbconfig.fbgn2chrom, left_on='index', right_index=True)\ .set_index('index') def _plot(dat): num_cells = data.groupby('cluster').count().iloc[:, 0].to_dict() g = sns.FacetGrid(dat, col='cluster', col_wrap=2, size=4) g.map_dataframe(multi_chrom_boxplot, 'chrom', 'value', num_cells=num_cells, palette=nbconfig.color_chrom, notch=True, flierprops=nbconfig.fliersprops) _plot(dat) data = norm.loc[expressed, :].T.join(clus4) late = data.loc[data.cluster.isin([6, 11])].median() late.name = 'late' early = data.loc[data.cluster.isin([4, 9])].median() early.name = 'early' soma = data.loc[data.cluster.isin([1, 7, 10])].median() soma.name = 'soma' late = data.loc[data.cluster.isin([6, 11])].sum() late.name = 'late' early = data.loc[data.cluster.isin([4, 9])].sum() early.name = 'early' soma = data.loc[data.cluster.isin([1, 7, 10])].sum() soma.name = 'soma' dat = pd.concat([late, early, soma], axis=1).reset_index().melt(id_vars='index').merge(nbconfig.fbgn2chrom, left_on='index', right_index=True).set_index('index') dat.rename({'variable': 'cluster'}, inplace=True, axis=1) dat.cluster = dat.cluster.replace({'soma': 0, 'early': 1, 'late': 2}) def _plot(dat): num_cells = data.groupby('cluster').count().iloc[:, 0].to_dict() g = sns.FacetGrid(dat, col='cluster', col_wrap=2, size=4, sharey=False) g.map_dataframe(multi_chrom_boxplot, 'chrom', 'value', num_cells=num_cells, palette=nbconfig.color_chrom, notch=True, flierprops=nbconfig.fliersprops) _plot(dat) fig = plt.gcf() ax = fig.axes[0] ax.set_title('Soma') ax = fig.axes[1] ax.set_title('Early Germ Cell') ax = fig.axes[2] ax.set_title('Late Germ Cell') Ydata = norm.join(nbconfig.fbgn2chrom).query('chrom == "chrY"').drop('chrom', axis=1) Ydata = Ydata.T.loc[clus4.sort_values().index] Ydata.columns = Ydata.columns.map(lambda x: nbconfig.fbgn2symbol[x]) levels = sorted(clus4.unique()) colors = sns.color_palette('tab20', n_colors=len(levels)) mapper = dict(zip(levels, colors)) cmap = clus4.sort_values().map(mapper) g = sns.clustermap(Ydata, row_cluster=False, col_cluster=True, yticklabels=False, row_colors=cmap, figsize=(20, 10)) g.ax_col_dendrogram.set_visible(False) for label in levels: g.ax_row_dendrogram.bar(0, 0, color=mapper[label], label=label, linewidth=0) g.ax_row_dendrogram.legend(loc="center", ncol=2) from larval_gonad.x_to_a import estimate_dcc, clean_pvalue from scipy.stats import mannwhitneyu def boxplot(data, expressed, mask, chrom, ax, name): _data = data.loc[expressed, mask] _data['median'] = _data.median(axis=1) _data = _data.join(chrom, how='inner') med_x, med_major, prop_dcc = estimate_dcc('chrom', 'median', _data) _data['chrom'] = _data['chrom'].map(lambda x: x.replace('chr', '')) ORDER = ['X', '2L', '2R', '3L', '3R', '4'] sns.boxplot(_data['chrom'], _data['median'], order=ORDER, notch=True, boxprops={"facecolor": 'w'}, ax=ax, flierprops={'alpha': .6}) ax.axhline(med_major, ls=':', lw=2, color=nbconfig.color_c1) ax.set_title(name) ax.set_xlabel('Chromosome') ax.set_ylabel('Median Normalized Expression') # Clean up the pvalue for plotting pvalues = {} iqr = 0 chromX = _data[_data.chrom == 'X'] for g, df in _data.groupby('chrom'): _iqr = sns.utils.iqr(df['median']) if _iqr > iqr: iqr = _iqr if g == 'X': continue if g == 'M': continue _, pval = mannwhitneyu(chromX['median'], df['median'], alternative='two-sided') if pval <= 0.001: pvalues[g] = '***' multiplier = .35 xloc = ORDER.index('X') for k, v in pvalues.items(): oloc = ORDER.index(k) pval = v y, h, col = iqr + iqr * multiplier, .1, 'k' plt.plot([xloc, xloc, oloc, oloc], [y, y+h, y+h, y], lw=1, c=col) plt.text((xloc+oloc)*.5, y+h+.01, f"{pval}", ha='center', va='bottom', color=col) multiplier += .2 fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(8.5, 3.3), sharex=True, sharey=True) chrom = nbconfig.fbgn2chrom boxplot(norm, expressed, soma, chrom, ax1, 'Somatic Cells') boxplot(norm, expressed, early, chrom, ax2, 'Early Germ Cells') boxplot(norm, expressed, late, chrom, ax3, 'Late Germ Cells') ax2.set_ylabel('') ax3.set_ylabel('') plt.savefig('../output/figures/2018-03-16_x2a_combined_forced_simple_boxplot.png', dpi=300) ```
github_jupyter
``` train_file = './data/tsd_train.csv' trial_file = './data/tsd_trial.csv' test_file = './data/tsd_test_spans.csv' all_files = [train_file,trial_file, test_file] import pandas as pd import numpy as np %cd .. from evaluation.fix_spans import _contiguous_ranges fil = all_files[0] spans = pd.read_csv(fil)['spans'].apply(eval) texts = pd.read_csv(fil)['text'] texts[205] _contiguous_ranges(spans[205]) texts[205][33:38] texts[205][76:84] dic = { "Num Contiguous Spans(Mean)":[], "Num Contiguous Spans(Std)":[], "Num Contiguous Spans(Max)":[], "Num Contiguous Spans(Min)":[], "Len Contiguous Spans(Mean)":[], "Len Contiguous Spans(Std)":[], "Len Contiguous Spans(Max)":[], "Len Contiguous Spans(Min)":[], "Per Contiguous Spans(Mean)":[], "Per Contiguous Spans(Std)":[], "Per Contiguous Spans(Max)":[], "Per Contiguous Spans(Min)":[], } for fil in all_files: print(fil) spans = pd.read_csv(fil)['spans'].apply(eval) texts = pd.read_csv(fil)['text'] num_contiguous_spans = [] len_contiguous_spans = [] per_contiguous_spans = [] #percentage of characters for j,contiguous_spans in enumerate(spans.apply(_contiguous_ranges)): ## contiguous_spans is like [(1,3),(4,5),(6,9)] num_contiguous_spans.append(len(contiguous_spans)) current = np.sum([end-start+1 for start,end in contiguous_spans])/len(texts[j]) len_contiguous_spans+=[end-start+1 for start,end in contiguous_spans] per_contiguous_spans.append(current) dic["Num Contiguous Spans(Mean)"].append('%.2f' %np.mean(num_contiguous_spans)) dic["Num Contiguous Spans(Std)"].append('%.2f' %np.std(num_contiguous_spans)) dic["Num Contiguous Spans(Max)"].append('%.2f' % np.max(num_contiguous_spans)) dic["Num Contiguous Spans(Min)"].append('%.2f' % np.min(num_contiguous_spans)) dic["Len Contiguous Spans(Mean)"].append('%.2f' %np.mean(len_contiguous_spans)) dic["Len Contiguous Spans(Std)"].append('%.2f' %np.std(len_contiguous_spans)) dic["Len Contiguous Spans(Max)"].append('%.2f' % np.max(len_contiguous_spans)) dic["Len Contiguous Spans(Min)"].append('%.2f' % np.min(len_contiguous_spans)) dic["Per Contiguous Spans(Mean)"].append('%.2f' %np.mean(per_contiguous_spans)) dic["Per Contiguous Spans(Std)"].append('%.2f' %np.std(per_contiguous_spans)) dic["Per Contiguous Spans(Max)"].append('%.2f' % np.max(per_contiguous_spans)) dic["Per Contiguous Spans(Min)"].append('%.2f' % np.min(per_contiguous_spans)) print(pd.DataFrame(dic).T.to_markdown()) ```
github_jupyter
# 7. Neural Machine Translation and Models with Attention I recommend you take a look at these material first. * http://web.stanford.edu/class/cs224n/lectures/cs224n-2017-lecture9.pdf * http://web.stanford.edu/class/cs224n/lectures/cs224n-2017-lecture10.pdf * http://web.stanford.edu/class/cs224n/lectures/cs224n-2017-lecture11.pdf * https://arxiv.org/pdf/1409.0473.pdf * https://github.com/spro/practical-pytorch/blob/master/seq2seq-translation/seq2seq-translation-batched.ipynb * https://medium.com/huggingface/understanding-emotions-from-keras-to-pytorch-3ccb61d5a983 * http://www.manythings.org/anki/ ``` import torch import torch.nn as nn from torch.autograd import Variable import torch.optim as optim import torch.nn.functional as F import nltk import random import numpy as np from collections import Counter, OrderedDict import nltk from copy import deepcopy import os import re import unicodedata flatten = lambda l: [item for sublist in l for item in sublist] from torch.nn.utils.rnn import PackedSequence,pack_padded_sequence import matplotlib.pyplot as plt import matplotlib.ticker as ticker %matplotlib inline USE_CUDA = torch.cuda.is_available() FloatTensor = torch.cuda.FloatTensor if USE_CUDA else torch.FloatTensor LongTensor = torch.cuda.LongTensor if USE_CUDA else torch.LongTensor ByteTensor = torch.cuda.ByteTensor if USE_CUDA else torch.ByteTensor def getBatch(batch_size,train_data): random.shuffle(train_data) sindex=0 eindex=batch_size while eindex < len(train_data): batch = train_data[sindex:eindex] temp = eindex eindex = eindex+batch_size sindex = temp yield batch if eindex >= len(train_data): batch = train_data[sindex:] yield batch ``` ### Padding <img src="../images/07.pad_to_sequence.png"> <center>borrowed image from https://medium.com/huggingface/understanding-emotions-from-keras-to-pytorch-3ccb61d5a983</center> ``` # It is for Sequence 2 Sequence format def pad_to_batch(batch,x_to_ix,y_to_ix): sorted_batch = sorted(batch, key=lambda b:b[0].size(1),reverse=True) # sort by len x,y = list(zip(*sorted_batch)) max_x = max([s.size(1) for s in x]) max_y = max([s.size(1) for s in y]) x_p,y_p=[],[] for i in range(len(batch)): if x[i].size(1)<max_x: x_p.append(torch.cat([x[i],Variable(LongTensor([x_to_ix['<PAD>']]*(max_x-x[i].size(1)))).view(1,-1)],1)) else: x_p.append(x[i]) if y[i].size(1)<max_y: y_p.append(torch.cat([y[i],Variable(LongTensor([y_to_ix['<PAD>']]*(max_y-y[i].size(1)))).view(1,-1)],1)) else: y_p.append(y[i]) input_var = torch.cat(x_p) target_var = torch.cat(y_p) input_len = [list(map(lambda s: s ==0, t.data)).count(False) for t in input_var] target_len = [list(map(lambda s: s ==0, t.data)).count(False) for t in target_var] return input_var, target_var, input_len, target_len def prepare_sequence(seq, to_index): idxs = list(map(lambda w: to_index[w] if w in to_index.keys() else to_index["<UNK>"], seq)) return Variable(LongTensor(idxs)) ``` ## Data load and Preprocessing Borrowed code from https://github.com/spro/practical-pytorch/blob/master/seq2seq-translation/seq2seq-translation-batched.ipynb ``` # Turn a Unicode string to plain ASCII, thanks to http://stackoverflow.com/a/518232/2809427 def unicode_to_ascii(s): return ''.join( c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn' ) # Lowercase, trim, and remove non-letter characters def normalize_string(s): s = unicode_to_ascii(s.lower().strip()) s = re.sub(r"([,.!?])", r" \1 ", s) s = re.sub(r"[^a-zA-Z,.!?]+", r" ", s) s = re.sub(r"\s+", r" ", s).strip() return s ``` <center><h3>French -> English</h3></center> ``` corpus = open('../dataset/eng-fra.txt','r',encoding='utf-8').readlines() len(corpus) corpus = corpus[:30000] # for practice MIN_LENGTH=3 MAX_LENGTH=25 %%time X_r,y_r=[],[] # raw for parallel in corpus: so,ta = parallel[:-1].split('\t') if so.strip()=="" or ta.strip()=="": continue normalized_so = normalize_string(so).split() normalized_ta = normalize_string(ta).split() if len(normalized_so)>=MIN_LENGTH and len(normalized_so)<=MAX_LENGTH \ and len(normalized_ta)>=MIN_LENGTH and len(normalized_ta)<=MAX_LENGTH: X_r.append(normalized_so) y_r.append(normalized_ta) print(len(X_r),len(y_r)) print(X_r[0],y_r[0]) ``` ### Build Vocab ``` source_vocab = list(set(flatten(X_r))) target_vocab = list(set(flatten(y_r))) print(len(source_vocab),len(target_vocab)) source2index = {'<PAD>':0,'<UNK>':1,'<s>':2,'</s>':3} for vo in source_vocab: if vo not in source2index.keys(): source2index[vo]=len(source2index) index2source = {v:k for k,v in source2index.items()} target2index = {'<PAD>':0,'<UNK>':1,'<s>':2,'</s>':3} for vo in target_vocab: if vo not in target2index.keys(): target2index[vo]=len(target2index) index2target = {v:k for k,v in target2index.items()} ``` ### Prepare train data ``` %%time X_p,y_p=[],[] for so,ta in zip(X_r,y_r): X_p.append(prepare_sequence(so+['</s>'],source2index).view(1,-1)) y_p.append(prepare_sequence(ta+['</s>'],target2index).view(1,-1)) train_data = list(zip(X_p,y_p)) ``` ## Modeling <img src="../images/07.seq2seq.png"> <center>borrowd image from http://web.stanford.edu/class/cs224n/lectures/cs224n-2017-lecture10.pdf</center> If you're not familier with <strong>pack_padded_sequence</strong> and <strong>pad_packed_sequence</strong>, check this <a href="https://medium.com/huggingface/understanding-emotions-from-keras-to-pytorch-3ccb61d5a983">post</a>. ``` class Encoder(nn.Module): def __init__(self, input_size, embedding_size,hidden_size, n_layers=1,bidirec=False): super(Encoder, self).__init__() self.input_size = input_size self.hidden_size = hidden_size self.n_layers = n_layers self.embedding = nn.Embedding(input_size, embedding_size) if bidirec: self.n_direction = 2 self.gru = nn.GRU(embedding_size, hidden_size, n_layers, batch_first=True,bidirectional=True) else: self.n_direction = 1 self.gru = nn.GRU(embedding_size, hidden_size, n_layers, batch_first=True) def init_hidden(self,inputs): hidden = Variable(torch.zeros(self.n_layers*self.n_direction,inputs.size(0),self.hidden_size)) return hidden.cuda() if USE_CUDA else hidden def init_weight(self): self.embedding.weight = nn.init.xavier_uniform(self.embedding.weight) self.gru.weight_hh_l0 = nn.init.xavier_uniform(self.gru.weight_hh_l0) self.gru.weight_ih_l0 = nn.init.xavier_uniform(self.gru.weight_ih_l0) def forward(self, inputs, input_lengths): """ inputs : B,T (LongTensor) input_lengths : real lengths of input batch (list) """ hidden = self.init_hidden(inputs) embedded = self.embedding(inputs) packed = pack_padded_sequence(embedded, input_lengths,batch_first=True) outputs, hidden = self.gru(packed, hidden) outputs, output_lengths = torch.nn.utils.rnn.pad_packed_sequence(outputs,batch_first=True) # unpack (back to padded) if self.n_layers>1: if self.n_direction==2: hidden = hidden[-2:] else: hidden = hidden[-1] return outputs, torch.cat(hidden,1).unsqueeze(1) ``` ### Attention Mechanism ( https://arxiv.org/pdf/1409.0473.pdf ) I used general-type for score function $h_t^TW_ah_s^-$ <img src="../images/07.attention-mechanism.png"> <center>borrowed image from http://web.stanford.edu/class/cs224n/lectures/cs224n-2017-lecture10.pdf</center> ``` class Decoder(nn.Module): def __init__(self, input_size, embedding_size, hidden_size, n_layers=1,dropout_p=0.1): super(Decoder, self).__init__() self.hidden_size = hidden_size self.n_layers = n_layers # Define the layers self.embedding = nn.Embedding(input_size, embedding_size) self.dropout = nn.Dropout(dropout_p) self.gru = nn.GRU(embedding_size+hidden_size, hidden_size, n_layers,batch_first=True) self.linear = nn.Linear(hidden_size*2, input_size) self.attn = nn.Linear(self.hidden_size,self.hidden_size) # Attention def init_hidden(self,inputs): hidden = Variable(torch.zeros(self.n_layers,inputs.size(0),self.hidden_size)) return hidden.cuda() if USE_CUDA else hidden def init_weight(self): self.embedding.weight = nn.init.xavier_uniform(self.embedding.weight) self.gru.weight_hh_l0 = nn.init.xavier_uniform(self.gru.weight_hh_l0) self.gru.weight_ih_l0 = nn.init.xavier_uniform(self.gru.weight_ih_l0) self.linear.weight = nn.init.xavier_uniform(self.linear.weight) self.attn.weight = nn.init.xavier_uniform(self.attn.weight) # self.attn.bias.data.fill_(0) def Attention(self, hidden, encoder_outputs, encoder_maskings): """ hidden : 1,B,D encoder_outputs : B,T,D encoder_maskings : B,T # ByteTensor """ hidden = hidden[0].unsqueeze(2) # (1,B,D) -> (B,D,1) batch_size = encoder_outputs.size(0) # B max_len = encoder_outputs.size(1) # T energies = self.attn(encoder_outputs.contiguous().view(batch_size*max_len,-1)) # B*T,D -> B*T,D energies = energies.view(batch_size,max_len,-1) # B,T,D attn_energies = energies.bmm(hidden).squeeze(2) # B,T,D * B,D,1 --> B,T # if isinstance(encoder_maskings,torch.autograd.variable.Variable): # attn_energies = attn_energies.masked_fill(encoder_maskings,float('-inf'))#-1e12) # PAD masking alpha = F.softmax(attn_energies) # B,T alpha = alpha.unsqueeze(1) # B,1,T context = alpha.bmm(encoder_outputs) # B,1,T * B,T,D => B,1,D return context, alpha def forward(self,inputs,context,max_length,encoder_outputs,encoder_maskings=None,is_training=False): """ inputs : B,1 (LongTensor, START SYMBOL) context : B,1,D (FloatTensor, Last encoder hidden state) max_length : int, max length to decode # for batch encoder_outputs : B,T,D encoder_maskings : B,T # ByteTensor is_training : bool, this is because adapt dropout only training step. """ # Get the embedding of the current input word embedded = self.embedding(inputs) hidden = self.init_hidden(inputs) if is_training: embedded = self.dropout(embedded) decode=[] # Apply GRU to the output so far for i in range(max_length): _, hidden = self.gru(torch.cat((embedded,context),2), hidden) # h_t = f(h_{t-1},y_{t-1},c) concated = torch.cat((hidden,context.transpose(0,1)),2) # y_t = g(h_t,y_{t-1},c) score = self.linear(concated.squeeze(0)) softmaxed = F.log_softmax(score) decode.append(softmaxed) decoded = softmaxed.max(1)[1] embedded = self.embedding(decoded).unsqueeze(1) # y_{t-1} if is_training: embedded = self.dropout(embedded) # compute next context vector using attention context, alpha = self.Attention(hidden, encoder_outputs,encoder_maskings) # column-wise concat, reshape!! scores = torch.cat(decode,1) return scores.view(inputs.size(0)*max_length,-1) def decode(self,context,encoder_outputs): start_decode = Variable(LongTensor([[target2index['<s>']]*1])).transpose(0,1) embedded = self.embedding(start_decode) hidden = self.init_hidden(start_decode) decodes=[] attentions=[] decoded = embedded while decoded.data.tolist()[0]!=target2index['</s>']: # until </s> _, hidden = self.gru(torch.cat((embedded,context),2), hidden) # h_t = f(h_{t-1},y_{t-1},c) concated = torch.cat((hidden,context.transpose(0,1)),2) # y_t = g(h_t,y_{t-1},c) score = self.linear(concated.squeeze(0)) softmaxed = F.log_softmax(score) decodes.append(softmaxed) decoded = softmaxed.max(1)[1] embedded = self.embedding(decoded).unsqueeze(1) # y_{t-1} context, alpha = self.Attention(hidden, encoder_outputs,None) attentions.append(alpha.squeeze(1)) return torch.cat(decodes).max(1)[1], torch.cat(attentions) ``` ## Train It takes for a while if you use just cpu.... ``` EPOCH=50 BATCH_SIZE = 64 EMBEDDING_SIZE = 300 HIDDEN_SIZE = 512 LR = 0.001 DECODER_LEARNING_RATIO=5.0 RESCHEDULED=False encoder = Encoder(len(source2index),EMBEDDING_SIZE,HIDDEN_SIZE,3,True) decoder = Decoder(len(target2index),EMBEDDING_SIZE,HIDDEN_SIZE*2) encoder.init_weight() decoder.init_weight() if USE_CUDA: encoder = encoder.cuda() decoder = decoder.cuda() loss_function = nn.CrossEntropyLoss(ignore_index=0) enc_optimizer = optim.Adam(encoder.parameters(),lr=LR) dec_optimizer = optim.Adam(decoder.parameters(),lr=LR*DECODER_LEARNING_RATIO) for epoch in range(EPOCH): losses=[] for i,batch in enumerate(getBatch(BATCH_SIZE,train_data)): inputs,targets,input_lengths,target_lengths = pad_to_batch(batch,source2index,target2index) input_masks = torch.cat([Variable(ByteTensor(tuple(map(lambda s: s ==0, t.data)))) for t in inputs]).view(inputs.size(0),-1) start_decode = Variable(LongTensor([[target2index['<s>']]*targets.size(0)])).transpose(0,1) encoder.zero_grad() decoder.zero_grad() output, hidden_c = encoder(inputs,input_lengths) preds = decoder(start_decode,hidden_c,targets.size(1),output,input_masks,True) loss = loss_function(preds,targets.view(-1)) losses.append(loss.data.tolist()[0] ) loss.backward() torch.nn.utils.clip_grad_norm(encoder.parameters(), 50.0) # gradient clipping torch.nn.utils.clip_grad_norm(decoder.parameters(), 50.0) # gradient clipping enc_optimizer.step() dec_optimizer.step() if i % 200==0: print("[%02d/%d] [%03d/%d] mean_loss : %0.2f" %(epoch,EPOCH,i,len(train_data)//BATCH_SIZE,np.mean(losses))) losses=[] # You can use http://pytorch.org/docs/master/optim.html#how-to-adjust-learning-rate if RESCHEDULED==False and epoch == EPOCH//2: LR = LR*0.01 enc_optimizer = optim.Adam(encoder.parameters(),lr=LR) dec_optimizer = optim.Adam(decoder.parameters(),lr=LR*DECODER_LEARNING_RATIO) RESCHEDULED=True ``` ## Test ### Visualize Attention ``` # borrowed code from https://github.com/spro/practical-pytorch/blob/master/seq2seq-translation/seq2seq-translation-batched.ipynb def show_attention(input_words, output_words, attentions): # Set up figure with colorbar fig = plt.figure() ax = fig.add_subplot(111) cax = ax.matshow(attentions.numpy(), cmap='bone') fig.colorbar(cax) # Set up axes ax.set_xticklabels([''] + input_words, rotation=90) ax.set_yticklabels([''] + output_words) # Show label at every tick ax.xaxis.set_major_locator(ticker.MultipleLocator(1)) ax.yaxis.set_major_locator(ticker.MultipleLocator(1)) # show_plot_visdom() plt.show() plt.close() test = random.choice(train_data) input_ = test[0] truth = test[1] output, hidden = encoder(input_,[input_.size(1)]) pred,attn = decoder.decode(hidden,output) input_ = [index2source[i] for i in input_.data.tolist()[0]] pred = [index2target[i] for i in pred.data.tolist()] print('Source : ',' '.join([i for i in input_ if i not in ['</s>']])) print('Truth : ',' '.join([index2target[i] for i in truth.data.tolist()[0] if i not in [2,3]])) print('Prediction : ',' '.join([i for i in pred if i not in ['</s>']])) if USE_CUDA: attn = attn.cpu() show_attention(input_,pred,attn.data) ``` # TODO * BLEU * Beam Search * <a href="http://www.aclweb.org/anthology/P15-1001">Sampled Softmax</a> ## Further topics * <a href="https://s3.amazonaws.com/fairseq/papers/convolutional-sequence-to-sequence-learning.pdf">Convolutional Sequence to Sequence learning</a> * <a href="https://arxiv.org/abs/1706.03762">Attention is all you need</a> * <a href="https://arxiv.org/abs/1711.00043">Unsupervised Machine Translation Using Monolingual Corpora Only</a> ## Suggested Reading * <a href="https://arxiv.org/pdf/1709.07809.pdf">SMT chapter13. Neural Machine Translation</a>
github_jupyter
``` import pandas as pd cj = pd.read_csv('bks_cjxx1.csv') #cj为Dateframe结构,将学号提取出来之后转换为list类型 yuanshi_xuehao = cj['xh'].tolist() yuanshi_xuehao =yuanshi_xuehao[0:100000] #通过set消去重复元素 xuehao = set(yuanshi_xuehao) xuehao = list(xuehao)#30000 l_chang=len(yuanshi_xuehao)#1000000 l_duan=len(xuehao)#30000 import numpy as np #print(index_1) chengji = cj['kccj']#成绩 chengji = chengji[0:100000] kecheng = cj['kch']#上的课程 kecheng = kecheng[0:100000] xn = cj['xn']#学年 xn=xn[0:100000] xqm = cj['xqm']#学期码 xqm=xqm[0:100000] list_chengji=list(chengji) list_kecheng=list(kecheng) All_X_chengji_one=[] All_X_chengji_two=[] All_X_chengji_three=[] All_y_chengji_four=[] count = 0 for i in range(len(xuehao)): #对于每轮循环,student_grade,都将被重新赋值。 student_grade = xuehao[i-1] xueqi=[] student_grade_chengji=[] ruxue_nianfen = int(student_grade/100000) #把这个学号的所有成绩索引出来:index2为一个列表,但对于一个列表不可以直接索引另外一个列表 index_1 = [x for x in range(l_chang) if yuanshi_xuehao[x] == student_grade] student_grade_one=[] student_grade_two=[] student_grade_three=[] student_grade_four=[] for j in index_1: kecheng_xn = xn[j] kecheng_xn = int(kecheng_xn[0:4]) kecheng_xqm = int(xqm[i]) kecheng_xueqi =(kecheng_xn-ruxue_nianfen)*2+kecheng_xqm xueqi.append(kecheng_xueqi) a=max(xueqi) if a>4: for k in index_1: kecheng_xn = xn[k] kecheng_xn = int(kecheng_xn[:4]) kecheng_xqm = int(xqm[k]) kecheng_xueqi =(kecheng_xn-ruxue_nianfen)*2+kecheng_xqm if kecheng_xueqi == 1: student_grade_one.append(list_chengji[k]) if kecheng_xueqi == 2: student_grade_two.append(list_chengji[k]) if kecheng_xueqi == 3: student_grade_three.append(list_chengji[k]) if kecheng_xueqi == 4: student_grade_four.append(list_chengji[k]) if len(student_grade_four)*len(student_grade_three)*len(student_grade_two)*len(student_grade_one)==0: continue grade_one_mean = sum(student_grade_one)/len(student_grade_one) grade_two_mean = sum(student_grade_two)/len(student_grade_two) grade_three_mean = sum(student_grade_three)/len(student_grade_three) grade_four_mean = sum(student_grade_four)/len(student_grade_four) All_X_chengji_one.append(grade_three_mean) All_X_chengji_two.append(grade_three_mean) All_X_chengji_three.append(grade_three_mean) All_y_chengji_four.append(grade_four_mean) count=count+1 print(count) print(All_X_chengji_one) print(All_X_chengji_two) print(All_X_chengji_three) print(All_y_chengji_four) #对于第一个线性相关的数据处理 X=np.array(All_X_chengji_three) y=np.array(All_y_chengji_four) gama = 0.9 train_number = int(gama*count) index_train = np.random.choice(count,train_number,replace=False) X_train=[] y_train=[] for i in index_train: X_train.append([All_X_chengji_three[i]]) y_train.append(All_y_chengji_four[i]) X_train=np.array(X_train) y_train=np.array(y_train) gama = 0.1 train_number = int(gama*count) index_text = np.random.choice(count,train_number,replace=False) X_text=[] y_text=[] for i in index_text: X_text.append([All_X_chengji_three[i]]) if All_y_chengji_four[i]>=60: y_text.append([1]) else: y_text.append([0]) X_text=np.array(X_text) y_text=np.array(y_text) l_text=len(X_text) import matplotlib.pyplot as plt from sklearn.metrics import mean_squared_error from sklearn.model_selection import train_test_split def plot_learning_curves(model, X, y): X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2) train_errors, val_errors = [], [] for m in range(1, len(X_train)): model.fit(X_train[:m], y_train[:m]) y_train_predict = model.predict(X_train[:m]) y_val_predict = model.predict(X_val) train_errors.append(mean_squared_error(y_train_predict, y_train[:m])) val_errors.append(mean_squared_error(y_val_predict, y_val)) plt.plot(np.sqrt(train_errors), "r-+", linewidth=2, label="train") plt.plot(np.sqrt(val_errors), "b-", linewidth=3, label="val") #线性回归部分 #闭式解算出来的线性回归 from sklearn.linear_model import LinearRegression lin_reg = LinearRegression() lin_reg.fit(X_train, y_train) #print(lin_reg.intercept_, lin_reg.coef_) #多项式回归::: from sklearn.preprocessing import PolynomialFeatures poly_features = PolynomialFeatures(degree=2, include_bias=False) X_poly = poly_features.fit_transform(X_train) X[0]#表示之前的特征集 X_poly[0]#表示二次特征集,下面将用二次特征集作为线性函数的输入去拟合 lin_reg = LinearRegression() lin_reg.fit(X_poly, y_train) lin_reg.intercept_, lin_reg.coef_ plot_learning_curves(lin_reg, X_train, y_train) text_success=0 for i in range(l_text): a=0 if lin_reg.predict([X_text[i-1]])>=60: a=1 if a==y_text[i-1]: text_success=text_success+1 Accuracy = text_success/l_text print(Accuracy) #对于第一个线性相关的数据处理 X=np.array(All_X_chengji_three) y=np.array(All_y_chengji_four) gama = 0.9 train_number = int(gama*count) index_train = np.random.choice(count,train_number,replace=False) X_train=[] y_train=[] for i in index_train: X_train.append([All_X_chengji_three[i],All_X_chengji_two[i],All_X_chengji_one[i]]) y_train.append(All_y_chengji_four[i]) X_train=np.array(X_train) y_train=np.array(y_train) #决策树 from sklearn.tree import DecisionTreeRegressor tree_reg = DecisionTreeRegressor(max_depth=2) tree_reg.fit(X_train, y_train) tree_reg.predict([[55, 65,79]]) plot_learning_curves(tree_reg, X_train, y_train) from sklearn.svm import LinearSVR svm_reg = LinearSVR(epsilon=1.5) svm_reg.fit(X_train, y_train) svm_reg.predict([[84,84,78]]) plot_learning_curves(svm_reg, X_train, y_train) X_train=[] y_train=[] for i in index_train: X_train.append([All_X_chengji_three[i],All_X_chengji_two[i],All_X_chengji_one[i]]) if All_y_chengji_four[i]>60: y_train.append([1]) else: y_train.append([0]) X_train=np.array(X_train) y_train=np.array(y_train) gama = 0.1 train_number = int(gama*count) index_text = np.random.choice(count,train_number,replace=False) X_text=[] y_text=[] for i in index_text: X_text.append([All_X_chengji_three[i],All_X_chengji_two[i],All_X_chengji_one[i]]) if All_y_chengji_four[i]>60: y_text.append([1]) else: y_text.append([0]) X_text=np.array(X_text) y_text=np.array(y_text) l_text=len(X_text) from sklearn.datasets import make_moons from sklearn.pipeline import Pipeline from sklearn.preprocessing import PolynomialFeatures from sklearn.preprocessing import StandardScaler from sklearn.svm import LinearSVC polynomial_svm_clf = Pipeline(( ("poly_features", PolynomialFeatures(degree=3)), ("scaler", StandardScaler()), ("svm_clf", LinearSVC(C=10, loss="hinge")) )) polynomial_svm_clf.fit(X_train, y_train) #polynomial_svm_clf.predict([[91,82,75]]) count_success=0 for i in range(l_text): if polynomial_svm_clf.predict([X_text[i-1]])==y_text[i-1]: count_success=count_success+1 Accuracy = count_success/l_text print(Accuracy) from sklearn.ensemble import RandomForestClassifier rnd_clf = RandomForestClassifier(n_estimators=500, max_leaf_nodes=16, n_jobs=-1) rnd_clf.fit(X_train, y_train) count_success=0 for i in range(l_text): if rnd_clf.predict([X_text[i-1]])==y_text[i-1]: count_success=count_success+1 Accuracy = count_success/l_text print(Accuracy) from sklearn.ensemble import BaggingClassifier from sklearn.tree import DecisionTreeClassifier bag_clf = BaggingClassifier( DecisionTreeClassifier(), n_estimators=500, max_samples=100, bootstrap=True, n_jobs=-1 ) bag_clf.fit(X_train, y_train) #bag_clf.predict([[91,72,84]]) count_success=0 for i in range(l_text): if bag_clf.predict([X_text[i-1]])==y_text[i-1]: count_success=count_success+1 Accuracy = count_success/l_text print(Accuracy) ```
github_jupyter
``` import pandas as pd import spacy from string import punctuation from spacy.lang.en import English from nltk.stem import WordNetLemmatizer from nltk.corpus import stopwords df = pd.read_csv('Preprocessed_produced_new.csv') eng = spacy.load('en') stop_words = list(punctuation) + ["'s","'m","n't","'re","-","'ll",'...'] + stopwords.words('english') parser = English() lemmatizer = WordNetLemmatizer() def word_tokenize(line): line_tokens = [] tokens = parser(line) for token in tokens: token_str = str(token) if token.orth_.isspace(): continue elif str(token) not in stop_words: line_tokens.append(lemmatizer.lemmatize(token.lower_)) return line_tokens df_non_argumentative = df.loc[df['is_non_argumentative'] == True] df_argumentative = df.loc[df['is_non_argumentative'] == False] df_against = df_argumentative.loc[df_argumentative['is_against'] == True] df_support = df_argumentative.loc[df_argumentative['is_against'] == False] df_claim = df_argumentative.loc[df_argumentative['argu_part'] == 1] df_warrant = df_argumentative.loc[df_argumentative['argu_part'] == 2] df_ground = df_argumentative.loc[df_argumentative['argu_part'] == 3] non_argumentative_str = df_non_argumentative["Text Content"].str.cat(sep=' ') argumentative_str = df_argumentative["Text Content"].str.cat(sep=' ') against_str = df_against["Text Content"].str.cat(sep=' ') support_str = df_support["Text Content"].str.cat(sep=' ') claim_str = df_claim["Text Content"].str.cat(sep=' ') warrant_str = df_warrant["Text Content"].str.cat(sep=' ') ground_str = df_ground["Text Content"].str.cat(sep=' ') display(len(non_argumentative_str)) display(len(argumentative_str)) display(len(against_str)) display(len(support_str)) display(len(claim_str)) display(len(warrant_str)) display(len(ground_str)) from sklearn.feature_extraction.text import TfidfVectorizer tfidfer = TfidfVectorizer(tokenizer=word_tokenize, ngram_range=(1, 2), analyzer='word', norm='l2') tfidf_result = tfidfer.fit_transform([non_argumentative_str, argumentative_str, against_str, support_str, claim_str, warrant_str, ground_str ]) non_argumentative_tfidf = tfidf_result.toarray()[0] argumentative_tfidf = tfidf_result.toarray()[1] against_tfidf = tfidf_result.toarray()[2] support_tfidf = tfidf_result.toarray()[3] claim_tfidf = tfidf_result.toarray()[4] warrant_tfidf = tfidf_result.toarray()[5] ground_tfidf = tfidf_result.toarray()[6] nlarge_idx_non_argumentative = non_argumentative_tfidf.argsort()[-20:][::-1] nlarge_idx_argumentative = argumentative_tfidf.argsort()[-20:][::-1] nlarge_idx_against = against_tfidf.argsort()[-20:][::-1] nlarge_idx_support = support_tfidf.argsort()[-20:][::-1] nlarge_idx_claim = claim_tfidf.argsort()[-20:][::-1] nlarge_idx_warrant = warrant_tfidf.argsort()[-20:][::-1] nlarge_idx_ground = ground_tfidf.argsort()[-20:][::-1] feature_names = tfidfer.get_feature_names() len(feature_names) ``` # 1. non-argumentative ``` for idx in nlarge_idx_non_argumentative: print(feature_names[idx] + ": " + str(non_argumentative_tfidf[idx])) ``` # 2. Argumentative ``` for idx in nlarge_idx_argumentative: print(feature_names[idx] + ": " + str(argumentative_tfidf[idx])) ``` # 3. Claim ``` for idx in nlarge_idx_claim: print(feature_names[idx] + ": " + str(claim_tfidf[idx])) ``` # 4. Warrant ``` for idx in nlarge_idx_warrant: print(feature_names[idx] + ": " + str(warrant_tfidf[idx])) ``` # 5. Ground ``` for idx in nlarge_idx_ground: print(feature_names[idx] + ": " + str(ground_tfidf[idx])) ``` # 6. Support ``` for idx in nlarge_idx_support: print(feature_names[idx] + ": " + str(support_tfidf[idx])) ``` # 7. Against ``` for idx in nlarge_idx_against: print(feature_names[idx] + ": " + str(against_tfidf[idx])) ```
github_jupyter
# Multi step model (vector output approach) In this notebook, we demonstrate how to: - prepare time series data for training a RNN forecasting model - get data in the required shape for the keras API - implement a RNN model in keras to predict the next 3 steps ahead (time *t+1* to *t+3*) in the time series. This model uses recent values of temperature and load as the model input. The model will be trained to output a vector, the elements of which are ordered predictions for future time steps. - enable early stopping to reduce the likelihood of model overfitting - evaluate the model on a test dataset The data in this example is taken from the GEFCom2014 forecasting competition<sup>1</sup>. It consists of 3 years of hourly electricity load and temperature values between 2012 and 2014. The task is to forecast future values of electricity load. <sup>1</sup>Tao Hong, Pierre Pinson, Shu Fan, Hamidreza Zareipour, Alberto Troccoli and Rob J. Hyndman, "Probabilistic energy forecasting: Global Energy Forecasting Competition 2014 and beyond", International Journal of Forecasting, vol.32, no.3, pp 896-913, July-September, 2016. ``` import os import warnings import matplotlib.pyplot as plt import numpy as np import pandas as pd import datetime as dt from collections import UserDict from IPython.display import Image %matplotlib inline from common.utils import load_data, mape, TimeSeriesTensor, create_evaluation_df pd.options.display.float_format = '{:,.2f}'.format np.set_printoptions(precision=2) warnings.filterwarnings("ignore") ``` Load data into Pandas dataframe ``` energy = load_data('data/') energy.head() valid_start_dt = '2014-09-01 00:00:00' test_start_dt = '2014-11-01 00:00:00' T = 6 HORIZON = 3 train = energy.copy()[energy.index < valid_start_dt][['load', 'temp']] from sklearn.preprocessing import MinMaxScaler y_scaler = MinMaxScaler() y_scaler.fit(train[['load']]) X_scaler = MinMaxScaler() train[['load', 'temp']] = X_scaler.fit_transform(train) ``` Use the TimeSeriesTensor convenience class to: 1. Shift the values of the time series to create a Pandas dataframe containing all the data for a single training example 2. Discard any samples with missing values 3. Transform this Pandas dataframe into a numpy array of shape (samples, time steps, features) for input into Keras The class takes the following parameters: - **dataset**: original time series - **H**: the forecast horizon - **tensor_structure**: a dictionary discribing the tensor structure in the form { 'tensor_name' : (range(max_backward_shift, max_forward_shift), [feature, feature, ...] ) } - **freq**: time series frequency - **drop_incomplete**: (Boolean) whether to drop incomplete samples ``` tensor_structure = {'X':(range(-T+1, 1), ['load', 'temp'])} train_inputs = TimeSeriesTensor(train, 'load', HORIZON, tensor_structure) train_inputs.dataframe.head(3) train_inputs['X'][:3] train_inputs['target'][:3] ``` Construct validation set (keeping T hours from the training set in order to construct initial features) ``` look_back_dt = dt.datetime.strptime(valid_start_dt, '%Y-%m-%d %H:%M:%S') - dt.timedelta(hours=T-1) valid = energy.copy()[(energy.index >=look_back_dt) & (energy.index < test_start_dt)][['load', 'temp']] valid[['load', 'temp']] = X_scaler.transform(valid) valid_inputs = TimeSeriesTensor(valid, 'load', HORIZON, tensor_structure) ``` ## Implement the RNN We will implement a RNN forecasting model with the following structure: ``` Image('./images/multi_step_vector_output.png') from keras.models import Model, Sequential from keras.layers import GRU, Dense from keras.callbacks import EarlyStopping LATENT_DIM = 5 BATCH_SIZE = 32 EPOCHS = 10 model = Sequential() model.add(GRU(LATENT_DIM, input_shape=(T, 2))) model.add(Dense(HORIZON)) model.compile(optimizer='RMSprop', loss='mse') model.summary() earlystop = EarlyStopping(monitor='val_loss', min_delta=0, patience=5) model.fit(train_inputs['X'], train_inputs['target'], batch_size=BATCH_SIZE, epochs=EPOCHS, validation_data=(valid_inputs['X'], valid_inputs['target']), callbacks=[earlystop], verbose=1) ``` ## Evaluate the model ``` look_back_dt = dt.datetime.strptime(test_start_dt, '%Y-%m-%d %H:%M:%S') - dt.timedelta(hours=T-1) test = energy.copy()[test_start_dt:][['load', 'temp']] test[['load', 'temp']] = X_scaler.transform(test) test_inputs = TimeSeriesTensor(test, 'load', HORIZON, tensor_structure) predictions = model.predict(test_inputs['X']) predictions eval_df = create_evaluation_df(predictions, test_inputs, HORIZON, y_scaler) eval_df.head() ``` Compute MAPE for each forecast horizon ``` eval_df['APE'] = (eval_df['prediction'] - eval_df['actual']).abs() / eval_df['actual'] eval_df.groupby('h')['APE'].mean() ``` Compute MAPE across all predictions ``` mape(eval_df['prediction'], eval_df['actual']) ``` Plot actuals vs predictions at each horizon for first week of the test period. As is to be expected, predictions for one step ahead (*t+1*) are more accurate than those for 2 or 3 steps ahead ``` plot_df = eval_df[(eval_df.timestamp<'2014-11-08') & (eval_df.h=='t+1')][['timestamp', 'actual']] for t in range(1, HORIZON+1): plot_df['t+'+str(t)] = eval_df[(eval_df.timestamp<'2014-11-08') & (eval_df.h=='t+'+str(t))]['prediction'].values fig = plt.figure(figsize=(15, 8)) ax = plt.plot(plot_df['timestamp'], plot_df['actual'], color='red', linewidth=4.0) ax = fig.add_subplot(111) ax.plot(plot_df['timestamp'], plot_df['t+1'], color='blue', linewidth=4.0, alpha=0.75) ax.plot(plot_df['timestamp'], plot_df['t+2'], color='blue', linewidth=3.0, alpha=0.5) ax.plot(plot_df['timestamp'], plot_df['t+3'], color='blue', linewidth=2.0, alpha=0.25) plt.xlabel('timestamp', fontsize=12) plt.ylabel('load', fontsize=12) ax.legend(loc='best') plt.show() ```
github_jupyter
## Arken - Wikidata version 1.1 WD egenskap [Property:P8899](https://www.wikidata.org/wiki/Property:P8899) * this [notebook](https://github.com/salgo60/open-data-examples/blob/master/Arken.ipynb) * Task [T269064](https://phabricator.wikimedia.org/T269064) ---- #### Other sources we sync * [Arken](https://github.com/salgo60/open-data-examples/blob/master/Arken.ipynb) * WD [Property:P8899](https://www.wikidata.org/wiki/Property:P8899) * [Kulturpersoner Uppsalakyrkogård](https://github.com/salgo60/open-data-examples/blob/master/Check%20WD%20kulturpersoner%20uppsalakyrkogardar.ipynb) * [Litteraturbanken](https://github.com/salgo60/open-data-examples/blob/master/Litteraturbanken%20Author.ipynb) * WD property [P5101](https://www.wikidata.org/wiki/Property_talk:P5101) [P5123](https://www.wikidata.org/wiki/Property_talk:P5123) * [Nobelprize.org](https://github.com/salgo60/open-data-examples/blob/master/Nobel%20API.ipynb) * WD [property 8024](https://www.wikidata.org/wiki/Property:P8024) * [SBL](https://github.com/salgo60/open-data-examples/blob/master/SBL.ipynb) * WD [property 3217](https://www.wikidata.org/wiki/Property:P3217) * [SKBL](https://github.com/salgo60/open-data-examples/blob/master/Svenskt%20Kvinnobiografiskt%20lexikon%20part%203.ipynb) * WD [property 4963](https://www.wikidata.org/wiki/Property:P4963) * [Svenska Akademien](https://github.com/salgo60/open-data-examples/blob/master/Svenska%20Akademien.ipynb) * WD [property 5325](https://www.wikidata.org/wiki/Property:P5325) ``` from datetime import datetime now = datetime.now() print("Last run: ", now) import urllib3, json import pandas as pd from bs4 import BeautifulSoup import sys import pprint from SPARQLWrapper import SPARQLWrapper, JSON from tqdm.notebook import trange from wikidataintegrator import wdi_core, wdi_login endpoint_url = "https://query.wikidata.org/sparql" SparqlQuery = """SELECT ?item ?arkid WHERE { ?item wdt:P8899 ?arkid }""" http = urllib3.PoolManager() # Query https://w.wiki/Vo5 def get_results(endpoint_url, query): user_agent = "user salgo60/%s.%s" % (sys.version_info[0], sys.version_info[1]) sparql = SPARQLWrapper(endpoint_url, agent=user_agent) sparql.setQuery(query) sparql.setReturnFormat(JSON) return sparql.query().convert() SparQlResults = get_results(endpoint_url, SparqlQuery) length = len (SparQlResults["results"]["bindings"]) dfWikidata = pd.DataFrame(columns=['WD', 'arkid']) for r in trange(0,length): resultSparql = SparQlResults["results"]["bindings"][r] wd = resultSparql["item"]["value"].replace("http://www.wikidata.org/entity/","") try: wdArkid= resultSparql["arkid"]["value"] except: wdArkid = "" dfWikidata = dfWikidata.append({'WD': wd, 'arkid': wdArkid}, ignore_index=True) dfWikidata.info() dfWikidata.head(200) import urllib.parse urlbase = "https://arken.kb.se/actor/browse?sort=alphabetic&sortDir=asc&page=" urlbase_entry = "https://arken.kb.se" dfArken = pd.DataFrame(columns=['nameAuth', 'urlAuth', 'Auktoriserad', 'Datum', 'Auktoritetspost']) #for i in range(1,80): for i in range(1,90): url = urlbase + str(i) print(url) r = http.request('GET', url) soup = BeautifulSoup(r.data, "html.parser") for link in soup.select('div.search-result-description a[href]'): nameAuth = link.string urlAuth = urllib.parse.unquote(link['href'].split("/")[1]) #print ("\t",urlAuth, nameAuth) urlentry = urlbase_entry + link['href'] #print ("\t\t",urlentry) try: r_entry = http.request('GET', urlentry) soup_entry = BeautifulSoup(r_entry.data, "html.parser") Auktoriserad = "" Datum = "" Auktoritetspost = "" fields = soup_entry.select('div.field') for f in fields: h3 = f.select("h3") divText = f.select("div") if len(h3) > 0: if "Auktoriserad" in h3[0].getText(): #print("\t\tAuktoriserad: " + divText[0].getText().strip()) Auktoriserad = divText[0].getText().strip() if "Datum för verksamhetstid" in h3[0].text: #print("\t\t\tDatum: " + divText[0].getText().strip()) Datum = divText[0].getText().strip() if "Auktoritetspost" in h3[0].text: Auktoritetspost = divText[0].getText().strip() #print("\t\t\tAuktoritetspost: " + divText[0].getText().strip()) dfArken = dfArken.append({'nameAuth': nameAuth, 'urlAuth': urlAuth, 'Auktoriserad': Auktoriserad, 'Datum': Datum, 'Auktoritetspost': Auktoritetspost}, ignore_index=True) except: print("Error") dfArken.info() dfArken.head(10) dfArken.to_csv(r'Arken.csv') ``` ## Check diff Wikidata * dfArken * dfWikidata * see also ``` dfWikidata.info() dfArken.info() dfArken.sample() # Merge plotPublishedAuthor WDSKBLtot mergeArkenWD = pd.merge(dfWikidata, dfArken,how='outer', left_on='arkid',right_on='urlAuth',indicator=True) mergeArkenWD.rename(columns={"_merge": "WD_Arken"},inplace = True) mergeArkenWD['WD_Arken'] = mergeArkenWD['WD_Arken'].str.replace('left_only','WD_only').str.replace('right_only','Arken_only') mergeArkenWD["WD_Arken"].value_counts() Arken_only = mergeArkenWD[mergeArkenWD["WD_Arken"] == "Arken_only"].copy() WD_only = mergeArkenWD[mergeArkenWD["WD_Arken"] == "WD_only"].copy() # could be places etc.... WD_only.head(10) pd.set_option('display.max_rows', None) Arken_only.sample(10) mergewithLibris = Arken_only[Arken_only["Auktoritetspost"].notnull()].copy() mergewithLibris.sample(10) #mergewithLibris = Arken_only[Arken_only["Auktoritetspost"].notnull()].copy() ArkenOnlyWithAuthrec = Arken_only[Arken_only["Auktoritetspost"] != ''].copy() ArkenOnlyWithAuthrec.to_csv(r'ArkenOnlyWithAuthrec.csv') ArkenOnlyWithAuthrec mergewithLibris mergewithLibris.info() ``` ## Places TBD ``` urlbase = "https://arken.kb.se/taxonomy/index/id/42?sort=alphabetic&sortDir=asc&page=" dfp = pd.DataFrame(columns=['nameAuth', 'urlAuth', 'Auktoriserad', 'Datum', 'Auktoritetspost']) def check_Taxonomy(url): r_entry = http.request('GET', url) soup_entry = BeautifulSoup(r_entry.data, "html.parser") fields = soup_entry.select('div.field') for f in fields: h3 = f.select("h3") divText = f.select("div") if len(h3) > 0: if "Taxonomi" in h3[0].getText(): #print("\tTaxonomi: " + divText[0].getText().strip()) Taxonomi = divText[0].getText().strip() return True for i in range(1,10): url = urlbase + str(i) #print(url) r = http.request('GET', url) soup = BeautifulSoup(r.data, "html.parser") for link in soup.select('table a[href]'): nameAuth = link.string urlAuth = urllib.parse.unquote(link['href'].split("/")[1]) #print ("\t",urlAuth, nameAuth) urlentry = urlbase_entry + link['href'] #print ("\t\t",urlentry) if check_Taxonomy(urlentry): #print("True") pass ```
github_jupyter
``` # This example is for demonstration purposes # It shows how to pre-train BERT from scratch using your own tokenizer model # To build tokenizer model do: # python tests/data/create_vocab.py --train_path wikitext-2/train.txt # Please refer to the corresponding NLP tutorial on NeMo documentation import math import os import nemo from nemo.utils.lr_policies import CosineAnnealing import nemo_nlp from nemo_nlp import NemoBertTokenizer, SentencePieceTokenizer from nemo_nlp.utils.callbacks.bert_pretraining import eval_iter_callback, \ eval_epochs_done_callback BATCHES_PER_STEP = 1 BATCH_SIZE = 64 BATCH_SIZE_EVAL = 16 CHECKPOINT_DIR = "bert_pretraining_checkpoints" D_MODEL = 768 D_INNER = 3072 HIDDEN_ACT = "gelu" LEARNING_RATE = 1e-2 LR_WARMUP_PROPORTION = 0.05 MASK_PROBABILITY = 0.15 MAX_SEQ_LENGTH = 128 NUM_EPOCHS = 10 NUM_HEADS = 12 NUM_LAYERS = 12 OPTIMIZER = "novograd" WEIGHT_DECAY = 0 # Instantiate neural factory with supported backend neural_factory = nemo.core.NeuralModuleFactory( backend=nemo.core.Backend.PyTorch, # If you're training with multiple GPUs, you should handle this value with # something like argparse. See examples/nlp/bert_pretraining.py for an example. local_rank=None, # If you're training with mixed precision, this should be set to mxprO1 or mxprO2. # See https://nvidia.github.io/apex/amp.html#opt-levels for more details. optimization_level=nemo.core.Optimization.mxprO0, # If you're training with multiple GPUs, this should be set to # nemo.core.DeviceType.AllGpu placement=nemo.core.DeviceType.GPU) tokenizer = SentencePieceTokenizer(model_path="data/lm/wikitext-2/bert/tokenizer.model") tokenizer.add_special_tokens(["[MASK]", "[CLS]", "[SEP]"]) bert_model = nemo_nlp.huggingface.BERT( vocab_size=tokenizer.vocab_size, num_hidden_layers=NUM_LAYERS, hidden_size=D_MODEL, num_attention_heads=NUM_HEADS, intermediate_size=D_INNER, max_position_embeddings=MAX_SEQ_LENGTH, hidden_act=HIDDEN_ACT, factory=neural_factory) mlm_log_softmax = nemo_nlp.TransformerLogSoftmaxNM( vocab_size=tokenizer.vocab_size, d_model=D_MODEL, factory=neural_factory) mlm_loss = nemo_nlp.MaskedLanguageModelingLossNM(factory=neural_factory) mlm_log_softmax.log_softmax.dense.weight = \ bert_model.bert.embeddings.word_embeddings.weight nsp_log_softmax = nemo_nlp.SentenceClassificationLogSoftmaxNM( d_model=D_MODEL, num_classes=2, factory=neural_factory) nsp_loss = nemo_nlp.NextSentencePredictionLossNM(factory=neural_factory) bert_loss = nemo_nlp.LossAggregatorNM( num_inputs=2, factory=neural_factory) train_data_layer = nemo_nlp.BertPretrainingDataLayer( tokenizer=tokenizer, dataset=os.path.join("data/lm/wikitext-2", "train.txt"), name="train", max_seq_length=MAX_SEQ_LENGTH, mask_probability=MASK_PROBABILITY, batch_size=BATCH_SIZE, factory=neural_factory) test_data_layer = nemo_nlp.BertPretrainingDataLayer( tokenizer=tokenizer, dataset=os.path.join("data/lm/wikitext-2", "test.txt"), name="test", max_seq_length=MAX_SEQ_LENGTH, mask_probability=MASK_PROBABILITY, batch_size=BATCH_SIZE_EVAL, factory=neural_factory) input_ids, input_type_ids, input_mask, \ output_ids, output_mask, nsp_labels = train_data_layer() hidden_states = bert_model(input_ids=input_ids, token_type_ids=input_type_ids, attention_mask=input_mask) train_mlm_log_probs = mlm_log_softmax(hidden_states=hidden_states) train_mlm_loss = mlm_loss(log_probs=train_mlm_log_probs, output_ids=output_ids, output_mask=output_mask) train_nsp_log_probs = nsp_log_softmax(hidden_states=hidden_states) train_nsp_loss = nsp_loss(log_probs=train_nsp_log_probs, labels=nsp_labels) train_loss = bert_loss(loss_1=train_mlm_loss, loss_2=train_nsp_loss) input_ids_, input_type_ids_, input_mask_, \ output_ids_, output_mask_, nsp_labels_ = test_data_layer() hidden_states_ = bert_model(input_ids=input_ids_, token_type_ids=input_type_ids_, attention_mask=input_mask_) test_mlm_log_probs = mlm_log_softmax(hidden_states=hidden_states_) test_mlm_loss = mlm_loss(log_probs=test_mlm_log_probs, output_ids=output_ids_, output_mask=output_mask_) test_nsp_log_probs = nsp_log_softmax(hidden_states=hidden_states_) test_nsp_loss = nsp_loss(log_probs=test_nsp_log_probs, labels=nsp_labels_) callback_loss = nemo.core.SimpleLossLoggerCallback( tensors=[train_loss], print_func=lambda x: print("Loss: {:.3f}".format(x[0].item()))) train_data_size = len(train_data_layer) # If you're training on multiple GPUs, this should be # train_data_size / (batch_size * batches_per_step * num_gpus) steps_per_epoch = int(train_data_size / (BATCHES_PER_STEP * BATCH_SIZE)) callback_test = nemo.core.EvaluatorCallback( eval_tensors=[test_mlm_loss, test_nsp_loss], user_iter_callback=eval_iter_callback, user_epochs_done_callback=eval_epochs_done_callback, eval_step=steps_per_epoch) lr_policy = CosineAnnealing(NUM_EPOCHS * steps_per_epoch, warmup_ratio=LR_WARMUP_PROPORTION) neural_factory.train(tensors_to_optimize=[train_loss], lr_policy=lr_policy, callbacks=[callback_loss, callback_test], #callbacks=[callback_loss], batches_per_step=BATCHES_PER_STEP, optimizer=OPTIMIZER, optimization_params={ "batch_size": BATCH_SIZE, "num_epochs": NUM_EPOCHS, "lr": LEARNING_RATE, "weight_decay": WEIGHT_DECAY, "betas": (0.95, 0.98), "grad_norm_clip": None }) ```
github_jupyter
# Example 11 - Multi-objective optimization for plug flow reactor In [Example 7](07_PFR_MOO.ipynb), we demonstrated how Bayesian Optimization can perform multi-objective optimization (MOO) and create a Pareto front using weighted objectives. In this example we will demonstrate how to use the acquisition function, Expected Hypervolume Improvement (EHVI) and its Monte Carlo variant (q-EHVI),[[1]](https://arxiv.org/abs/2006.05078) to perform the MOO. The interested reader is referred to reference 1-3 for more information. We will use the same PFR model. Two output variables will be generated from the model: yield (`y1`) and selectivity (`y2`). Unfortunately, these two variables cannot be maximized simultaneously. An increase in yield would lead to a decrease in selectivity, and vice versa. The details of this example is summarized in the table below: | Key Item | Description | | :----------------- | :----------------- | | Goal | Maximization, two objectives | | Objective function | PFR model | | Input (X) dimension | 3 | | Output (Y) dimension | 2 | | Analytical form available? | Yes | | Acqucision function | q-Expected Hypervolume improvement (qEHVI) | | Initial Sampling | Latin hypercube | Next, we will go through each step in Bayesian Optimization. ## 1. Import `nextorch` and other packages ## 2. Define the objective function and the design space We import the PFR model, and wrap it in a Python function called `PFR` as the objective function `objective_func`. The ranges of the input X are specified. ``` import os import sys import time from IPython.display import display project_path = os.path.abspath(os.path.join(os.getcwd(), '../..')) sys.path.insert(0, project_path) # Set the path for objective function objective_path = os.path.join(project_path, 'examples', 'PFR') sys.path.insert(0, objective_path) import numpy as np from nextorch import plotting, bo, doe, utils, io #%% Define the objective function from fructose_pfr_model_function import Reactor def PFR(X_real): """PFR model Parameters ---------- X_real : numpy matrix reactor parameters: T, pH and tf in real scales Returns ------- Y_real: numpy matrix reactor yield and selectivity """ if len(X_real.shape) < 2: X_real = np.expand_dims(X_real, axis=1) #If 1D, make it 2D array Y_real = [] for i, xi in enumerate(X_real): Conditions = {'T_degC (C)': xi[0], 'pH': xi[1], 'tf (min)' : 10**xi[2]} yi = Reactor(**Conditions) Y_real.append(yi) Y_real = np.array(Y_real) return Y_real # yield, selectivity # Objective function objective_func = PFR #%% Define the design space # Three input temperature C, pH, log10(residence time) X_name_list = ['T', 'pH', r'$\rm log_{10}(tf_{min})$'] X_units = [r'$\rm ^{o}C $', '', ''] # Add the units X_name_with_unit = [] for i, var in enumerate(X_name_list): if not X_units[i] == '': var = var + ' ('+ X_units[i] + ')' X_name_with_unit.append(var) # two outputs Y_name_with_unit = ['Yield %', 'Selectivity %'] # combine X and Y names var_names = X_name_with_unit + Y_name_with_unit # Set the operating range for each parameter X_ranges = [[140, 200], # Temperature ranges from 140-200 degree C [0, 1], # pH values ranges from 0-1 [-2, 2]] # log10(residence time) ranges from -2-2 # Get the information of the design space n_dim = len(X_name_list) # the dimension of inputs n_objective = len(Y_name_with_unit) # the dimension of outputs ``` ## 3. Define the initial sampling plan Here we use LHC design with 10 points for the initial sampling. The initial reponse in a real scale `Y_init_real` is computed from the objective function. ``` #%% Initial Sampling # Latin hypercube design with 10 initial points n_init_lhc = 10 X_init_lhc = doe.latin_hypercube(n_dim = n_dim, n_points = n_init_lhc, seed= 1) # Get the initial responses Y_init_lhc = bo.eval_objective_func(X_init_lhc, X_ranges, objective_func) # Compare the two sampling plans plotting.sampling_3d(X_init_lhc, X_names = X_name_with_unit, X_ranges = X_ranges, design_names = 'LHC') ``` ## 4. Initialize an `Experiment` object In this example, we use an `EHVIMOOExperiment` object, a class designed for multi-objective optimization using `Expected Hypervolume Improvement` as aquisition funciton. It can handle multiple weight combinations, perform the scalarized objective optimization automatically, and construct the entire Pareto front. An `EHVIMOOExperiment` is a subclass of `Experiment`. It requires all key components as `Experiment`. Additionally, `ref_point` is required for `EHVIMOOExperiment.set_ref_point` function. It defines a list of values that are slightly worse than the lower bound of objective values, where the lower bound is the minimum acceptable value of interest for each objective. It would be helpful if the user know the rough values using domain knowledge prior to optimization. ``` #%% Initialize an multi-objective Experiment object # Set its name, the files will be saved under the folder with the same name Exp_lhc = bo.EHVIMOOExperiment('PFR_yield_MOO_EHVI') # Import the initial data Exp_lhc.input_data(X_init_lhc, Y_init_lhc, X_ranges = X_ranges, X_names = X_name_with_unit, Y_names = Y_name_with_unit, unit_flag = True) # Set the optimization specifications # here we set the reference point ref_point = [10.0, 10.0] # Set a timer start_time = time.time() Exp_lhc.set_ref_point(ref_point) Exp_lhc.set_optim_specs(objective_func = objective_func, maximize = True) end_time = time.time() print('Initializing the experiment takes {:.2f} minutes.'.format((end_time-start_time)/60)) ``` ## 5. Run trials `EHVIMOOExperiment.run_trials_auto` can run these tasks automatically by specifying the acqucision function, q-Expected Hypervolume Improvement (`qEHVI`). In this way, we generate one point per iteration in default. Alternatively, we can manually specify the number of next points we would like to obtain. Some progress status will be printed out during the training. It takes 0.2 miuntes to obtain the whole front, much shorter than the 12.9 minutes in the weighted method. ``` # Set the number of iterations for each experiments n_trials_lhc = 30 # run trials # Exp_lhc.run_trials_auto(n_trials_lhc, 'qEHVI') for i in range(n_trials_lhc): # Generate the next experiment point X_new, X_new_real, acq_func = Exp_lhc.generate_next_point(n_candidates=4) # Get the reponse at this point Y_new_real = objective_func(X_new_real) # or # Y_new_real = bo.eval_objective_func(X_new, X_ranges, objective_func) # Retrain the model by input the next point into Exp object Exp_lhc.run_trial(X_new, X_new_real, Y_new_real) end_time = time.time() print('Optimizing the experiment takes {:.2f} minutes.'.format((end_time-start_time)/60)) ``` ## 6. Visualize the Pareto front We can get the Pareto set directly from the `EHVIMOOExperiment` object by using `EHVIMOOExperiment.get_optim`. To visualize the Pareto front, `y1` values are plotted against `y2` values. The region below $ y=x $ is infeasible for the PFR model and we have no Pareto points fall below the line, incidating the method is validate. Besides, all sampling points are shown as well. ``` Y_real_opts, X_real_opts = Exp_lhc.get_optim() # Parse the optimum into a table data_opt = io.np_to_dataframe([X_real_opts, Y_real_opts], var_names) display(data_opt.round(decimals=2)) # Make the pareto front plotting.pareto_front(Y_real_opts[:, 0], Y_real_opts[:, 1], Y_names=Y_name_with_unit, fill=False) # All sampling points plotting.pareto_front(Exp_lhc.Y_real[:, 0], Exp_lhc.Y_real[:, 1], Y_names=Y_name_with_unit, fill=False) ``` ## References: 1. Daulton, S.; Balandat, M.; Bakshy, E. Differentiable Expected Hypervolume Improvement for Parallel Multi-Objective Bayesian Optimization. arXiv 2020, No. 1, 1–30. 2. BoTorch tutorials using qHVI: https://botorch.org/tutorials/multi_objective_bo; https://botorch.org/tutorials/constrained_multi_objective_bo 3. Ax tutorial using qHVI: https://ax.dev/versions/latest/tutorials/multiobjective_optimization.html 4. Desir, P.; Saha, B.; Vlachos, D. G. Energy Environ. Sci. 2019. 5. Swift, T. D.; Bagia, C.; Choudhary, V.; Peklaris, G.; Nikolakis, V.; Vlachos, D. G. ACS Catal. 2014, 4 (1), 259–267 6. The PFR model can be found on GitHub: https://github.com/VlachosGroup/Fructose-HMF-Model [Thumbnail](_images/11.png) of this notebook
github_jupyter
``` %matplotlib inline ``` # Datasets and Dataloaders Code for processing data samples can get messy and hard to maintain; we ideally want our dataset code to be decoupled from our model training code for better readability and modularity. PyTorch provides two data primitives: ``torch.utils.data.DataLoader`` and ``torch.utils.data.Dataset`` that allow you to use pre-loaded datasets as well as your own data. ``Dataset`` stores the samples and their corresponding labels, and ``DataLoader`` wraps an iterable around the ``Dataset`` to enable easy access to the samples. PyTorch domain libraries provide a number of pre-loaded datasets (such as FashionMNIST) that subclass ``torch.utils.data.Dataset`` and implement functions specific to the particular data. They can be used to prototype and benchmark your model. You can find them here: [Image Datasets](https://pytorch.org/vision/stable/datasets.html), [Text Datasets](https://pytorch.org/text/stable/datasets.html), and [Audio Datasets](https://pytorch.org/audio/stable/datasets.html) ## Loading a dataset Here is an example of how to load the [Fashion-MNIST](https://research.zalando.com/welcome/mission/research-projects/fashion-mnist/) dataset from TorchVision. Fashion-MNIST is a dataset of Zalando’s article images consisting of of 60,000 training examples and 10,000 test examples. Each example comprises a 28×28 grayscale image and an associated label from one of 10 classes. We load the [FashionMNIST Dataset](https://pytorch.org/vision/stable/datasets.html#fashion-mnist) with the following parameters: - `root` is the path where the train/test data is stored, - `train` specifies training or test dataset, - `download=True` downloads the data from the Internet if it's not available at `root`. - `transform` and `target_transform` specify the feature and label transformations ``` import torch from torch.utils.data import Dataset from torchvision import datasets from torchvision.transforms import ToTensor, Lambda import matplotlib.pyplot as plt training_data = datasets.FashionMNIST( root="data", train=True, download=True, transform=ToTensor() ) test_data = datasets.FashionMNIST( root="data", train=False, download=True, transform=ToTensor() ) ``` Iterating and Visualizing the Dataset ----------------- We can index ``Datasets`` manually like a list: ``training_data[index]``. We use ``matplotlib`` to visualize some samples in our training data. ``` labels_map = { 0: "T-Shirt", 1: "Trouser", 2: "Pullover", 3: "Dress", 4: "Coat", 5: "Sandal", 6: "Shirt", 7: "Sneaker", 8: "Bag", 9: "Ankle Boot", } figure = plt.figure(figsize=(8, 8)) cols, rows = 3, 3 for i in range(1, cols * rows + 1): sample_idx = torch.randint(len(training_data), size=(1,)).item() img, label = training_data[sample_idx] figure.add_subplot(rows, cols, i) plt.title(labels_map[label]) plt.axis("off") plt.imshow(img.squeeze(), cmap="gray") plt.show() ``` Creating a Custom Dataset for your files --------------------------------------------------- A custom Dataset class must implement three functions: `__init__`, `__len__`, and `__getitem__`. Take a look at this implementation; the FashionMNIST images are stored in a directory ``img_dir``, and their labels are stored separately in a CSV file ``annotations_file``. In the next sections, we'll break down what's happening in each of these functions. ``` import os import pandas as pd import torchvision.io as tvio class CustomImageDataset(Dataset): def __init__(self, annotations_file, img_dir, transform=None, target_transform=None): self.img_labels = pd.read_csv(annotations_file) self.img_dir = img_dir self.transform = transform self.target_transform = target_transform def __len__(self): return len(self.img_labels) def __getitem__(self, idx): img_path = os.path.join(self.img_dir, self.img_labels.iloc[idx, 0]) image = tvio.read_image(img_path) label = self.img_labels.iloc[idx, 1] if self.transform: image = self.transform(image) if self.target_transform: label = self.target_transform(label) sample = {"image": image, "label": label} return sample ``` ## init The `__init__` function is run once when instantiating the Dataset object. We initialize the directory containing the images, the annotations file, and both transforms (covered in more detail in the next section). The labels.csv file looks like: ``` tshirt1.jpg, 0 tshirt2.jpg, 0 ...... ankleboot999.jpg, 9 ``` Example: ``` def __init__(self, annotations_file, img_dir, transform=None, target_transform=None): self.img_labels = pd.read_csv(annotations_file) self.img_dir = img_dir self.transform = transform self.target_transform = target_transform ``` ## len The `__len__` function returns the number of samples in our dataset. Example: ``` def __len__(self): return len(self.img_labels) ``` ## getitem The `__getitem__` function loads and returns a sample from the dataset at the given index `idx`. Based on the index, it identifies the image's location on disk, converts that to a tensor using `read_image`, retrieves the corresponding label from the csv data in `self.img_labels`, calls the transform functions on them (if applicable), and returns the tensor image and corresponding label in a Python `dict`. Example: ``` def __getitem__(self, idx): img_path = os.path.join(self.img_dir, self.img_labels.iloc[idx, 0]) image = read_image(img_path) label = self.img_labels.iloc[idx, 1] if self.transform: image = self.transform(image) if self.target_transform: label = self.target_transform(label) sample = {"image": image, "label": label} return sample ``` Preparing your data for training with DataLoaders ------------------------------------------------- The ``Dataset`` retrieves our dataset's features and labels one sample at a time. While training a model, we typically want to pass samples in "minibatches", reshuffle the data at every epoch to reduce model overfitting, and use Python's ``multiprocessing`` to speed up data retrieval. ``DataLoader`` is an iterable that abstracts this complexity for us in an easy API. ``` from torch.utils.data import DataLoader train_dataloader = DataLoader(training_data, batch_size=64, shuffle=True) test_dataloader = DataLoader(test_data, batch_size=64, shuffle=True) ``` ## Iterate through the DataLoader We have loaded that dataset into the `Dataloader` and can iterate through the dataset as needed. Each iteration below returns a batch of `train_features` and `train_labels`(containing `batch_size=64` features and labels respectively). Because we specified `shuffle=True`, after we iterate over all batches the data is shuffled (for finer-grained control over the data loading order, take a look at [Samplers](https://pytorch.org/docs/stable/data.html#data-loading-order-and-sampler>). ``` # Display image and label. train_features, train_labels = next(iter(train_dataloader)) print(f"Feature batch shape: {train_features.size()}") print(f"Labels batch shape: {train_labels.size()}") img = train_features[0].squeeze() label = train_labels[0] plt.imshow(img, cmap="gray") plt.show() print(f"Label: {label}") ```
github_jupyter
## Appendix D: Constructing MetaShift from COCO Dataset The notebook `dataset/extend_to_COCO/coco_MetaShift.ipynb` reproduces the COCO subpopulation shift dataset in paper Appendix D. Executing the notebook would construct a “Cat vs. Dog” task based on COCO images, where the “indoor/outdoor” contexts are spuriously correlated with the class labels. ### Install COCO Dependencies Install pycocotools (for evaluation on COCO): ``` conda install cython scipy pip install -U 'git+https://github.com/cocodataset/cocoapi.git#subdirectory=PythonAPI' ``` ### COCO Data preparation [2017 Train/Val annotations [241MB]](http://images.cocodataset.org/annotations/annotations_trainval2017.zip) [2017 Train images [118K/18GB]](http://images.cocodataset.org/zips/train2017.zip) Download and extract COCO 2017 train and val images with annotations from [http://cocodataset.org](http://cocodataset.org/#download). We expect the directory structure to be the following: ``` /home/ubuntu/data/coco/ annotations/ # annotation json files train2017/ # train images val2017/ # val images ``` ### Output files The following files will be generated by executing the notebook. ```plain /data/MetaShift/COCO-Cat-Dog-indoor-outdoor ├── imageID_to_group.pkl ├── train/ ├── cat/ ├── dog/ ├── val_out_of_domain/ ├── cat/ ├── dog/ ``` where `imageID_to_group.pkl` is a dictionary with 4 keys : `'cat(outdoor)'`, `'cat(outdoor)'`, `'dog(outdoor)'`, `'dog(outdoor)'`. The corresponding value of each key is the list of the names of the images that belongs to that subset. ### Cat vs. Dog Task with indoor/outdoor contexts We construct a “Cat vs. Dog” task, where the “indoor/outdoor” contexts are spuriously correlated with the class labels. The “indoor” context is constructed by merging the following super-categories: 'indoor', 'kitchen', 'electronic', 'appliance', 'furniture'. Similarly, the “outdoor” context is constructed by merging the following super-categories: 'outdoor', 'vehicle', 'sports'. In addition, in the training data, cat(ourdoor) and dog(indoor) subsets are the minority groups, while cat(indoor) and dog(outdoor) are majority groups. We keep the total size of training data as 3000 images unchanged and only vary the portion of minority groups. We use a balanced test set with 524 (131*4) images to report both average accuracy and worst group accuracy. ``` # The source COCO images; replace with the path to your COCO IMAGE_DATA_FOLDER = '/home/ubuntu/data/coco/train2017/' # The folder to generate COCO CUSTOM_SPLIT_DATASET_FOLDER = '/data/MetaShift/COCO-Cat-Dog-indoor-outdoor' %matplotlib inline from pycocotools.coco import COCO import numpy as np import skimage.io as io import matplotlib.pyplot as plt import pylab pylab.rcParams['figure.figsize'] = (8.0, 10.0) import random import pickle import numpy as np import json, re, math from collections import Counter, defaultdict import pprint import networkx as nx # graph vis import pandas as pd dataDir='/home/ubuntu/data/coco' # replace with your COCO 2017 data dir dataType='train2017' # dataType='val2017' # Only for debug annFile='{}/annotations/instances_{}.json'.format(dataDir,dataType) # initialize COCO api for instance annotations coco=COCO(annFile) # display COCO categories and supercategories cats = coco.loadCats(coco.getCatIds()) # print('cats[0]', cats[0]) nms=[cat['name'] for cat in cats] print('COCO {} categories: \n{}\n'.format(len(nms), ' '.join(nms)), ) category_nms = nms nms = set([cat['supercategory'] for cat in cats]) print('COCO {} supercategories: \n{}'.format(len(nms), ' '.join(nms))) supercategory_nms = nms # Compare with Visaul Genome based MetaDataset def load_candidate_subsets(): pkl_save_path = "../meta_data/full-candidate-subsets.pkl" with open(pkl_save_path, "rb") as pkl_f: load_data = pickle.load( pkl_f ) print('pickle load', len(load_data), pkl_save_path) return load_data VG_node_name_to_img_id = load_candidate_subsets() ``` ## Fetch Example COCO Image ``` # get all images containing given categories, select one at random catIds = coco.getCatIds(catNms=['cat']) imgIds = coco.getImgIds(catIds=catIds ) imgIds = coco.getImgIds(imgIds = imgIds[:20]) # in val img = coco.loadImgs(imgIds[np.random.randint(0,len(imgIds))])[0] # load and display instance annotations I = io.imread(img['coco_url']) plt.imshow(I); plt.axis('off') plt.title('Example COCO Image') annIds = coco.getAnnIds(imgIds=img['id'], catIds=catIds, iscrowd=None) anns = coco.loadAnns(annIds) coco.showAnns(anns) ``` # Plan Based on super categories, identify two (mostly) disjoint partitions. let's say indoor, outdoor. and then suriously correlating with two classes. ``` # Construct indoor/outdoor categories. cats = coco.loadCats(coco.getCatIds()) outdoor_categories = [ cat['name'] for cat in cats if cat['supercategory'] in ['outdoor', 'vehicle', 'sports'] ] indoor_categories = [ cat['name'] for cat in cats if cat['supercategory'] in ['indoor', 'kitchen', 'electronic', 'appliance', 'furniture' ] ] # display COCO categories and supercategories print('The following categories are considered as outdoor contexts:\n', outdoor_categories) print() print('The following categories are considered as indoor contexts:\n', indoor_categories) size_array = list() node_name_set = set() class_set = set() for subject_idx_i in range(len(category_nms)): for subject_idx_j in range(subject_idx_i+1, len(category_nms)): nms_i = category_nms[subject_idx_i] nms_j = category_nms[subject_idx_j] catIds = coco.getCatIds(catNms=[nms_i, nms_j]) imgIds = coco.getImgIds(catIds=catIds ) if len(imgIds)>=25: # only consider the subsets that are large enough (with >=25 images) size_array.append(len(imgIds)) node_name_set.add(nms_i + '(' + nms_j + ')') class_set.add(nms_i) class_set.add(nms_j) print('size_array mean:', np.mean(size_array), 'median:', np.median(size_array), 'num of subsets:', len(size_array) ) shared_subset_names = node_name_set.intersection(set(VG_node_name_to_img_id.keys())) print('COCO subsets overlap with VG', len(shared_subset_names), 'ratio:', len(shared_subset_names)/len(node_name_set) ) print('Number of metagraph', len(class_set)) # draw meta-graph for cat. node_name_to_img_id = dict() # cat(xxx) subject_str = 'cat' subject_node_name_set = [x for x in node_name_set if subject_str + '(' in x] # equivalent to: subject_most_common_list subject_node_name_set = set(subject_node_name_set) - {'cat(clock)', 'cat(tie)', 'cat(dog)', 'cat(teddy bear)', 'cat(scissors)'} subject_node_name_set = sorted(subject_node_name_set) print('subject_str', subject_str, 'subject_node_name_set', subject_node_name_set) for node_name in subject_node_name_set: # parse object context_obj_tag = node_name.split('(')[-1][:-1] imgIds = coco.getImgIds(catIds=coco.getCatIds(catNms=[context_obj_tag]) ) node_name_to_img_id[node_name] = set(imgIds) ``` ## Indoor/Outdoor Cat/Dog Subpopulation Shifts ``` # Explore cat/dog indoor/outdoor def union_imgIds_cateogry_list(list_categories): union_imgIds = set() for category in list_categories: imgIds = coco.getImgIds(catIds=coco.getCatIds(catNms=[category]) ) union_imgIds.update(imgIds) return union_imgIds def pad_str_imageID_list(imageID_list): ret = [coco.loadImgs([x])[0]["file_name"].replace('.jpg', '') for x in imageID_list] ret_set = set(ret) return ret_set outdoor_imgIds = union_imgIds_cateogry_list(list_categories = outdoor_categories) indoor_imgIds = union_imgIds_cateogry_list(list_categories = indoor_categories) outdoor_imgIds = pad_str_imageID_list(outdoor_imgIds) indoor_imgIds = pad_str_imageID_list(indoor_imgIds) ambiguous_imdIds = outdoor_imgIds.intersection(indoor_imgIds) outdoor_imgIds -= ambiguous_imdIds indoor_imgIds -= ambiguous_imdIds cat_imgIds = set(coco.getImgIds(catIds=coco.getCatIds(catNms=['cat']) )) dog_imgIds = set(coco.getImgIds(catIds=coco.getCatIds(catNms=['dog']) )) cat_imgIds = pad_str_imageID_list(cat_imgIds) dog_imgIds = pad_str_imageID_list(dog_imgIds) cat_outdoor_imgIds = cat_imgIds.intersection(outdoor_imgIds) cat_indoor_imgIds = cat_imgIds.intersection(indoor_imgIds) dog_outdoor_imgIds = dog_imgIds.intersection(outdoor_imgIds) dog_indoor_imgIds = dog_imgIds.intersection(indoor_imgIds) print( '\n Total number of cat(outdoor) images', len(cat_outdoor_imgIds), '\n Total number of cat(indoor) images', len(cat_indoor_imgIds), '\n Total number of dog(outdoor) images', len(dog_outdoor_imgIds), '\n Total number of dog(indoor) images', len(dog_indoor_imgIds), ) import os import shutil # for copy files ################################## # Copy Images specified by IDs: # destination folder: os.path.join(root_folder, split, subset_str) ################################## def copy_images(root_folder, split, subset_str, img_IDs, use_symlink=True): ################################## # Create dataset a new folder ################################## subject_localgroup_folder = os.path.join(root_folder, split, subset_str) if os.path.isdir(subject_localgroup_folder): shutil.rmtree(subject_localgroup_folder) os.makedirs(subject_localgroup_folder, exist_ok = False) for image_idx_in_set, imageID in enumerate(img_IDs): src_image_path = IMAGE_DATA_FOLDER + imageID + '.jpg' dst_image_path = os.path.join(subject_localgroup_folder, imageID + '.jpg') if use_symlink: ################################## # Image Copy Option B: create symbolic link # Usage: for local use, saving disk storge. ################################## # need to assert existance. assert os.path.isfile(src_image_path), src_image_path os.symlink(src_image_path, dst_image_path) # print('symlink:', src_image_path, dst_image_path) else: ################################## # Image Copy Option A: copy the whole jpg file # Usage: for sharing the meta-dataset ################################## shutil.copyfile(src_image_path, dst_image_path) # print('copy:', src_image_path, dst_image_path) return if os.path.isdir(CUSTOM_SPLIT_DATASET_FOLDER): shutil.rmtree(CUSTOM_SPLIT_DATASET_FOLDER) os.makedirs(CUSTOM_SPLIT_DATASET_FOLDER, exist_ok = False) import random def shuffle_and_truncate(img_id_set, truncate=500): img_id_list = sorted(img_id_set) random.Random(42).shuffle(img_id_list) return img_id_list[:truncate] cat_outdoor_images = shuffle_and_truncate(cat_outdoor_imgIds, 331) # 131 for test, 0-200 for training dog_indoor_images = shuffle_and_truncate(dog_indoor_imgIds, 331) cat_indoor_images = shuffle_and_truncate(cat_indoor_imgIds, 1500) dog_outdoor_images = shuffle_and_truncate(dog_outdoor_imgIds, 1500) from sklearn.model_selection import train_test_split cat_outdoor_train, cat_outdoor_test, dog_indoor_train, dog_indoor_test = train_test_split(cat_outdoor_images, dog_indoor_images, test_size=131, random_state=42) cat_indoor_train, cat_indoor_test, dog_outdoor_train, dog_outdoor_test = train_test_split(cat_indoor_images, dog_outdoor_images, test_size=131, random_state=42) # plan: 1500 training, NUM_MINORITY_IMG = 200 # 15-200/1500: 15(1%), 100(7%), 200(13%) copy_images( CUSTOM_SPLIT_DATASET_FOLDER, 'val_out_of_domain', 'cat', use_symlink=True, img_IDs = cat_outdoor_test + cat_indoor_test, ) copy_images( CUSTOM_SPLIT_DATASET_FOLDER, 'val_out_of_domain', 'dog', use_symlink=True, img_IDs = dog_indoor_test + dog_outdoor_test, ) copy_images( CUSTOM_SPLIT_DATASET_FOLDER, 'train', 'cat', use_symlink=True, img_IDs = cat_outdoor_train[:NUM_MINORITY_IMG] + cat_indoor_train[NUM_MINORITY_IMG:], ) copy_images( CUSTOM_SPLIT_DATASET_FOLDER, 'train', 'dog', use_symlink=True, img_IDs = dog_indoor_train[:NUM_MINORITY_IMG] + dog_outdoor_train[NUM_MINORITY_IMG:], ) print('NUM_MINORITY_IMG', NUM_MINORITY_IMG) ################################## # Book-keeping structure ################################## with open(CUSTOM_SPLIT_DATASET_FOLDER + '/' + 'imageID_to_group.pkl', 'wb') as handle: imageID_to_group = dict() group_to_imageID = { 'cat(outdoor)': cat_outdoor_images, 'dog(indoor)': dog_indoor_images, 'cat(indoor)': cat_indoor_images, 'dog(outdoor)': dog_outdoor_images, } for group_str in group_to_imageID: for imageID in group_to_imageID[group_str]: imageID_to_group[imageID] = [group_str] pickle.dump(imageID_to_group, file=handle) ``` ## All done! ``` print('All done!') print('please check your destination folder', CUSTOM_SPLIT_DATASET_FOLDER) ```
github_jupyter
# Einfache Abfrage _Weitere Informationen sind im Code in den mit # markierten Zeilen zu finden_ ### Import import verschiedener Module wie z.B. zum Zeitmessen ``` import pathlib import csv import time ``` ## Spezifikation für das Funktionieren in der Cloud Die folgenden Codefelder werden nur im bereich der Cloud gebraucht und entfallen bei benutzung auf einem lokalen System An den Stellen an, welchen die Punkte '.........' sind werden eigentlich die erforderlichen Infos eingesetzt, welche aber aus sicherheitstechnischen Gründen von mir entfernt wurden. ``` # @hidden_cell # The following code contains the credentials for a connection in your Project. # You might want to remove those credentials before you share your notebook. cgsCreds = { 'IBM_API_KEY_ID': '........', 'IAM_SERVICE_ID': 'crn:v1:bluemix:public:iam-identity::a/a6c0651c3aab4e74a4d1e131c1858b21::serviceid:ServiceId-cf18b8e2-291a-4175-b02f-4fa012271ab7', 'ENDPOINT': 'https://s3.private.eu-de.cloud-object-storage.appdomain.cloud', 'IBM_AUTH_ENDPOINT': '........', 'BUCKET': '........' } from ibm_botocore.client import Config import ibm_boto3 def read_file_cos(credentials,local_file_name, key): cos = ibm_boto3.client(service_name='s3', ibm_api_key_id=credentials['IBM_API_KEY_ID'], ibm_service_instance_id=credentials['IAM_SERVICE_ID'], ibm_auth_endpoint=credentials['IBM_AUTH_ENDPOINT'], config=Config(signature_version='oauth'), endpoint_url=credentials['ENDPOINT']) data_cos = None try: res=cos.download_file(Bucket=credentials['BUCKET'],Key=key,Filename=local_file_name) except Exception as e: print(Exception, e) else: print('File Downloaded') read_file_cos(cgsCreds, "/var/tmp/tmp.csv", "2017-01-02_sds011_sensor_299.csv") ``` ## Die Eingabe die individuelle Eingabe ``` # die folgenden Zahlen bei y,m,d und s sind im Ramen der Verfügbarkeit frei wählbar y = 2019 #year m = 4 #month d = 5 #day s = 299 #sensor filename = "%04d-%02d-%02d_sds011_sensor_%d.csv" %(y,m,d,s) path = "/var/tmp/" + filename read_file_cos(cgsCreds, path, filename) # path ist der Pfad zu der Datei, in welcher die Rohdaten liegen print(path) ``` ## Der eigentliche Code ``` sPM2_5 = [] sPM10 = [] # Start der Zeit für die Zeitmessung start = time.time() with open(path,newline = '') as f: readers = csv.DictReader(f, delimiter= ';') for row in readers: PM10 = float(row["P1"]) PM2_5 = float(row["P2"]) sPM10.append(PM10) sPM2_5.append(PM2_5) pass # Anzahl der PM2_5 und PM10 Werte anzAll = 0 # Summe aller addierten PM10 Werte wertAllPM10 = 0 for i in range(0, len(sPM10)): #PM10 wertAllPM10 += sPM10[i] anzAll += 1 # Summe aller addierten PM2_5 Werte wertAllPM2_5 = 0 for i in range(0, len(sPM2_5)): #PM2_5 wertAllPM2_5 += sPM2_5[i] # Durchschnittswert = Summe aller Werte durch Anzahl aller Werte durchWertPM10 = wertAllPM10 / anzAll durchWertPM2_5 = wertAllPM2_5 / anzAll # Ende der Zeit für die Zeitmessung end = time.time() # endzeit - Anfangszeit = benötigte Zeit diff = end-start ``` ## Die Printouts ``` print("Der Feinstaubwert (PM10) lag am %d.%d.%d bei %.2f μg pro m^3" %(d,m,y,durchWertPM10)) print("Der Feinstaubwert (PM2_5) lag am %d.%d.%d bei %.2f μg pro m^3" %(d,m,y,durchWertPM2_5)) print("Sec: %.4f" %(diff)) ```
github_jupyter
# Classic OpenSSL ## Initialize ECDSA keypair Generate keypair in PEM format ``` # uncomment to regenerate #import subprocess #ossl_proc = subprocess.Popen(['openssl', 'ecparam', '-name', 'secp256k1', '-genkey', '-noout'], stdout=subprocess.PIPE) #secret_key_pem = ossl_proc.communicate()[0] ossl_priv_key_pem = b""" -----BEGIN EC PRIVATE KEY----- MHQCAQEEIC+de1thpHhRvCoEe1rO8j+3lJXZ3j1PHTQBhhtjUUkLoAcGBSuBBAAK oUQDQgAEu4BpBjbdbTrMMxRocztc309nCn2iocwOGJSlOp0KzxfYyDgkZfIobJcA VBfwy/jrAWjHMKkWtazFhJctSqW4Mg== -----END EC PRIVATE KEY----- """ ``` convert private key from PEM (textual) to DER (binary) format ``` ossl_proc = subprocess.Popen(['openssl', 'ec', '-inform', 'PEM', '-outform', 'DER'], stdout=subprocess.PIPE, stdin=subprocess.PIPE) ossl_priv_key_der = ossl_proc.communicate(input=ossl_priv_key_pem)[0] ossl_priv_key_der.hex() ``` Generate public key in PEM (textual) format ``` ossl_proc = subprocess.Popen(['openssl', 'ec', '-inform', 'PEM', '-pubout'], stdout=subprocess.PIPE, stdin=subprocess.PIPE) ossl_pub_key_pem = ossl_proc.communicate(input=ossl_priv_key_pem)[0] print(ossl_pub_key_pem.decode("utf-8")) ``` Generate public key in DER (binary) format ``` ossl_proc = subprocess.Popen(['openssl', 'ec', '-inform', 'PEM', '-outform', 'DER', '-pubout'], stdout=subprocess.PIPE, stdin=subprocess.PIPE) ossl_pub_key_der = ossl_proc.communicate(input=ossl_priv_key_pem)[0] ossl_pub_key_der.hex() ``` # Pure-Python ECDSA ## import keys generated in OpenSSL Import PEM (textual) private key generated in openSSL ``` from ecdsa import SigningKey, VerifyingKey, SECP256k1 ecdsa_priv_key = SigningKey.from_pem(ossl_priv_key_pem) #ecdsa_pub_key = VerifyingKey.from_pem(ossl_pub_key_pem) ecdsa_pub_key = ecdsa_priv_key.get_verifying_key() # check equality with OpenSSL assert ecdsa_pub_key.to_string() == VerifyingKey.from_pem(ossl_pub_key_pem).to_string() assert ecdsa_pub_key.to_string() == VerifyingKey.from_der(ossl_pub_key_der).to_string() assert ecdsa_pub_key.to_string() == SigningKey.from_der(ossl_priv_key_der).get_verifying_key().to_string() ecdsa_pub_key.to_string().hex() signature = ecdsa_priv_key.sign(b"message") assert ecdsa_pub_key.verify(signature, b"message") signature.hex() from hashlib import sha1 from ecdsa import util # openssl dgst -ecdsa-with-SHA1 -verify vk.pem -signature data.sig 1.txt # openssl dgst -ecdsa-with-SHA1 -verify vk.pem -signature data.sig 1.txt sig_from_openssl_str = '3046022100e3f51d5af41c9f2f5007817c6f2bc418f6d7d9418fe81c7606d9c4b93de363f802210093929eb29162f3fb0e12a8a69af631bc07b5f29be9b0f751d14c11674051e235' sig_from_openssl = bytes.fromhex(sig_from_openssl_str) ecdsa_pub_key.verify(sig_from_openssl, "message\n".encode('utf-8'), hashfunc=sha1, sigdecode=util.sigdecode_der) ``` The OpenSSL signature is 72 bytes long. It is the list of two 32-byte numbers: r and s encoded and serialized by DER(ASN.1) ``` r,s = util.sigdecode_der(sig_from_openssl, 0) (hex(r),hex(s)) ```
github_jupyter
``` import sys sys.path.append('../python') import cool_tigress as ct A = ct.EnumAtom ph = ct.Photx() E = np.logspace(np.log10(5.0), 2, 2000) plt.plot(E, ph.get_sigma(A.H, A.H.value, E), label=A.H.name) #plt.plot(E, ph.get_sigma(A.He, A.He.value, E)) plt.plot(E, ph.get_sigma(A.N, A.N.value, E), 'r-', label=A.N.name) plt.plot(E, ph.get_sigma(A.C, A.C.value, E), 'g-', label=A.C.name) #plt.plot(E, ph.get_sigma(A.O, A.O.value, E) + ph.get_sigma(A.O, A.O.value-6, E)) #plt.plot(E, ph.get_sigma(A.C, A.C.value, E) + ph.get_sigma(A.C, A.C.value-4, E)) #plt.plot(E, ph.get_sigma(A.S, A.S.value, E), 'r-') plt.xscale('log') plt.yscale('log') plt.ylim(1e-21, 1e-16) plt.legend() ``` # Sulfur recombination rate ``` r = ct.RecRate() Z = ct.EnumAtom.S.value ax = r.plt_rec_rate(Z=Z, N=Z-2) ax.set_xlim(1e3, 2e6) ax.set_ylim(6e-13, 5e-11) def alphaH(T): B = 0.7472 T0 = 2.965 T1 = 7.001e5 return 8.318e-11/(np.sqrt(T/T0)*(1.0 + np.sqrt(T/T0))**(1.0 - B)*(1.0 + np.sqrt(T/T1))**(1.0 + B)) T = np.logspace(1, 6) plt.loglog(T, alphaH(T), 'k') #plt.loglog(T, 2.59e-13*(T/1e4)**-0.7, 'k--') alphaA = 4.17e-13*(T/1e4)**(-0.721 - 0.018*np.log(T/1e4)) alphaB = 2.59e-13*(T/1e4)**(-0.833 - 0.035*np.log(T/1e4)) plt.loglog(T, alphaA, 'r--') #plt.loglog(T, alphaB, 'b--') #plt.loglog(T, 2.59e-13*(T/1e4)**(-0.833 - 0.035*np.log(T/1e4)), 'g--') #plt.ylim(1e-18,1e-8) v = PhotVerner96() E = np.logspace(1.0, np.log10(50.0), 100) sigma_HI = v.sigma(1, 1, E) sigma_HeI = v.sigma(2, 2, E) sigma_CI = v.sigma(6, 6, E) sigma_NI = v.sigma(7, 7, E) sigma_OI = v.sigma(8, 8, E) sigma_SI = v.sigma(16, 16, E) plt.plot(E, sigma_HI, 'b-', label='H') plt.plot(E, sigma_HeI, 'r-', label='He') plt.plot(E, sigma_CI, 'g-', label='C') plt.plot(E, sigma_NI, 'y-', label='N') plt.plot(E, sigma_OI, 'k-', label='O') plt.plot(E, sigma_SI, 'm-', label='S') plt.yscale('log') plt.xscale('log') plt.legend() ``` ## H Collisional ionization rate comparison ``` T = np.logspace(3.7, 3.9) lnTe = np.log(T/1.160e4) k_Hplus_e = lambda T: 2.753e-14*(315614.0/T)**1.5 * \ (1.0 + (115188.0/T)**0.407)**(-2.242) kcoll = lambda T: 5.84e-11*np.sqrt(T)*np.exp(-157821.5/T) kcoll2 = lambda lnTe: np.exp(-3.271396786e1 + (1.35365560e1 + (- 5.73932875 + (1.56315498 + (- 2.877056e-1 + (3.48255977e-2 + (- 2.63197617e-3 + (1.11954395e-4 + (-2.03914985e-6) *lnTe)*lnTe)*lnTe)*lnTe)*lnTe)*lnTe)*lnTe)*lnTe) plt.loglog(T, kcoll(T), '--',label='K07') plt.loglog(T, kcoll2(lnTe),label='Gong17') #plt.loglog(T, k_Hplus_e(T)) #plt.ylim(bottom=1e-30) plt.legend() ```
github_jupyter
# 8.2 异步计算 ``` from __future__ import absolute_import, division, print_function, unicode_literals # 安装 TensorFlow try: # Colab only %tensorflow_version 2.x except Exception: pass import tensorflow as tf import tensorflow.keras as keras import os import subprocess import time ``` ## 8.2.1 Tensorflow 中的异步计算 ``` a = tf.ones((1, 2)) b = tf.ones((1, 2)) c = a * b + 2 c class Benchmark(object): def __init__(self, prefix=None): self.prefix = prefix + ' ' if prefix else '' def __enter__(self): self.start = time.time() def __exit__(self, *args): print('%stime: %.4f sec' % (self.prefix, time.time() - self.start)) with Benchmark('Workloads are queued.'): x = tf.random.uniform(shape=(2000, 2000)) y = tf.keras.backend.sum(tf.transpose(x) * x) with Benchmark('Workloads are finished.'): print('sum =', y) ``` ## 8.2.2 用同步函数让前端等待计算结果 ``` with Benchmark(): y = tf.keras.backend.sum(tf.transpose(x) * x) with Benchmark(): y = tf.keras.backend.sum(tf.transpose(x) * x) z = tf.keras.backend.sum(tf.transpose(x) * x) with Benchmark(): y = tf.keras.backend.sum(tf.transpose(x) * x) y.numpy() with Benchmark(): y = tf.keras.backend.sum(tf.transpose(x) * x) print(tf.norm(y).numpy()) ``` ## 8.2.3 使用异步计算提升计算性能 ``` with Benchmark('synchronous.'): for _ in range(1000): y = x + 1 @tf.function def loop(): for _ in range(1000): y = x + 1 return y with Benchmark('asynchronous.'): y = loop() ``` ## 8.2.4 异步计算对内存的影响 ``` def data_iter(): start = time.time() num_batches, batch_size = 100, 1024 for i in range(num_batches): X = tf.random.normal(shape=(batch_size, 512)) y = tf.ones((batch_size,)) yield X, y if (i + 1) % 50 == 0: print('batch %d, time %f sec' % (i+1, time.time()-start)) net = keras.Sequential() net.add(keras.layers.Dense(2048, activation='relu')) net.add(keras.layers.Dense(512, activation='relu')) net.add(keras.layers.Dense(1)) optimizer=keras.optimizers.SGD(0.05) loss = keras.losses.MeanSquaredError() def get_mem(): res = subprocess.check_output(['ps', 'u', '-p', str(os.getpid())]) return int(str(res).split()[15]) / 1e3 for X, y in data_iter(): break loss(y, net(X)) l_sum, mem = 0, get_mem() dense_1 = keras.layers.Dense(2048, activation='relu') dense_2 = keras.layers.Dense(512, activation='relu') dense_3 = keras.layers.Dense(1) trainable_variables = (dense_1.trainable_variables + dense_2.trainable_variables + dense_3.trainable_variables) for X, y in data_iter(): with tf.GradientTape() as tape: logits = net(X) loss_value = loss(y, logits) grads = tape.gradient(loss_value, trainable_variables) optimizer.apply_gradients(zip(grads, trainable_variables)) print('increased memory: %f MB' % (get_mem() - mem)) l_sum, mem = 0, get_mem() for X, y in data_iter(): with tf.GradientTape() as tape: logits = net(X) loss_value = loss(y, logits) grads = tape.gradient(loss_value, net.trainable_weights) optimizer.apply_gradients(zip(grads, net.trainable_weights)) print('increased memory: %f MB' % (get_mem() - mem)) ```
github_jupyter
# COVID-19 comparison using Pie charts Created by (c) Shardav Bhatt on 13 May 2020 # 1. Introduction Jupyter Notebook Created by Shardav Bhatt Data (as on 13 May 2020) References: 1. Vadodara: https://vmc.gov.in/coronaRelated/covid19dashboard.aspx 2. Gujarat: https://gujcovid19.gujarat.gov.in/ 3. India: https://www.mohfw.gov.in/ 4. Other countries and World: https://www.worldometers.info/coronavirus/ In this notebook, I have considered data of COVID-19 cases at Local level and at Global level. The aim is to determine whether there is a significance difference between Global scenario and Local scenario of COVID-19 cases or not. The comparison is done using Pie charts for active cases, recovered cases and deaths. # 2. Importing necessary modules ``` import matplotlib.pyplot as plt import pandas as pd import numpy as np import datetime ``` # 3. Extracting data from file ``` date = str(np.array(datetime.datetime.now())) data = pd.read_csv('data.csv') d = data.values row = np.zeros((d.shape[0],d.shape[1]-2)) for i in range(d.shape[0]): row[i] = d[i,1:-1] ``` # 4. Creating a funtion to print % in Pie chart ``` def func(pct, allvals): absolute = int(round(pct/100.*np.sum(allvals))) return "{:.1f}% ({:d})".format(pct, absolute) ``` # 5. Plot pre-processing ``` plt.close('all') date = str(np.array(datetime.datetime.now())) labels = 'Infected', 'Recovered', 'Died' fs = 20 C = ['lightskyblue','lightgreen','orange'] def my_plot(i): fig, axs = plt.subplots() axs.pie(row[i], autopct=lambda pct: func(pct, row[i]), explode=(0, 0.1, 0), textprops=dict(color="k", size=fs-2), colors = C, radius=1.5) axs.legend(labels, fontsize = fs-4, bbox_to_anchor=(1.1,1)) figure_title = str(d[i,0])+': '+str(d[i,-1])+' cases on '+date plt.text(1, 1.2, figure_title, horizontalalignment='center', fontsize=fs, transform = axs.transAxes) plt.show() print('\n') ``` # 6. Local scenario of COVID-19 cases ``` for i in range(4): my_plot(i) ``` # Observations: 1. Proportion of death in India is significanlty lower than the world. But in Gujarat and Vadodara, the proporations of death are similar to World. 2. Recovered cases proportion in Vadodara is significanlty higher than that in Gujarat and India. In Gujarat and India, proportion of recovered cases are similar to that of World. 3. Active cases in Vadodara are compratively lower than the global scenario. # 7. Global scenario of COVID-19 cases ``` for i in range(4,d.shape[0]): my_plot(i) ``` # Observations: 1. Death rate in Germany, China and Russia are comparatively lower. Germany seems to have best performance in this case since COVID-19 in China already came under control in March, while in Russia it has begin to spread very recently. 2. Italy, UK, Spain and France suffered heavily due to COVID-19 since they are having really high death proportions. 3. China, Germany and Spain are well recovered from COVID-19. 4. USA, Russia, UK and France needs good recovery rates.
github_jupyter
# Developer's Guide `funflow` provides a few task types (`SimpleTask`, `StoreTask`, and `DockerTask`) that will suffice for many pipelines, but the package facilitates creation of new task types as needed. This tutorial aims to help prospective `funflow` developers get started with task type creation. ## 1. Creating your own task In this tutorial, we will create a task called `CustomTask` by defining its type. We will define our own flow type, and write the functions needed to to run it. ### Defining the new task To define a task for our users, we first have to define a type that represents the task. > A task is represented by a generalized algebraic data type (GADT) of kind `* -> * -> *`. ``` -- Required language extensions {-# LANGUAGE GADTs, StandaloneDeriving #-} -- Define the representation of a custom task with some String and Int parameters data CustomTask i o where CustomTask :: String -> Int -> CustomTask String String -- Necessary in order to display it deriving instance (Show i, Show o) => Show (CustomTask i o) ``` Here, we create a type `CustomTask` with type constructor `CustomTask i o`, and a value constructor `CustomTask` of type `String -> Int -> CustomTask String String`. `String -> Int -> SomeCustomTask String String` means thatby providing a `String` and an `Int`, the function will give a task that takes a `String` as input and produces a `String` as output. A new task can be created by using the value constructor: ``` -- An example of instantiation CustomTask "someText" 42 ``` However, a value created this way is a _task_, not a _flow_. To use this value in a flow, we need some more work. ### From a task to a flow The `Flow` type in fact comes from restricting the more general `ExtendedFlow` type, specifying a fixed collection of task types to support. These tasks types are those defined here in funflow: `SimpleTask`, `StoreTask`, and `DockerTask`, which are declared as `RequiredStrands` in `Funflow.Flow`. In other words, a pipeline/workflow typed specifically as `Flow` may comprise tasks of these three types (and only these three), capturing the notion that it's these types with which a `Flow` is compatible. In order to manipulate a flow that can run our _custom_ task (i.e., a value of a new task type), we need to create our own new _flow_ type using `ExtendedFlow`, which is also defined in `Funflow.Flow`: ``` {-# LANGUAGE DataKinds, RankNTypes #-} import Funflow.Flow (ExtendedFlow) type MyFlow input output = ExtendedFlow '[ '("custom", CustomTask) ] input output ``` > Prefixing the leading bracket or parenthesis, i.e. `'[ ... ]` and `'( ... )`, denotes a _type-level_ list or tuple, respectively. This syntax is supported by the `OverloadedLabels` extension and is used to distinguish between the ordinary `[]` and `()` are _data_ constructors, building values rather than types. > > So with `'[ '("custom", CustomTask) ]`, we build a type-level list of type-level tuple, "labeling" our custom task type with a name. > > In `kernmantle`, such a tuple is called a _strand_, and the label facilitates disambiguation among different tasks with the same type. Now that we have our own type of flow that uses our custom task, we can define how a value of our custom task should be _stranded_, using [`kernmantle`](https://github.com/tweag/kernmantle): ``` {-# LANGUAGE OverloadedLabels #-} import Control.Kernmantle.Rope (strand) someCustomFlow :: String -> Int -> MyFlow String String someCustomFlow x y = strand #custom (CustomTask x y) ``` This function is called a _smart constructor_. It facilitates the creation of a flow for a user without having to think about strands. The `#custom` value is a Haskell label, and must match the string label associated to our task type in the flow type definition (here `"custom"`). ``` myFlow :: MyFlow String String myFlow = someCustomFlow "woop!" 7 ``` ### Interpret a task A strength of `funflow` is separation of the _representation_ of a computation (task) from _implementation_ of that task. More concretely, once it's created a task value has fixed input and output types, but __what it _does___ is not fixed. To specify that, we write an _interpreter function_. An interpreter function is executed __before _running_ the flow__. It takes a value of the task type that matches a particular _strand_ (identified by the strand's label) and produces an actual implementation of the task, in compliance with the task's fixed input and output types. In our case, we could define that our custom task `CustomTask n s` appends `n` times the string `s` to the input (which is a `String`): ``` import Control.Arrow (Arrow, arr) -- Helper function that repeats a string n times duplicate :: String -> Int -> String duplicate s n = concat (replicate n s) -- Our interpreter interpretCustomTask :: (Arrow a) => CustomTask i o -> a i o interpretCustomTask customTask = case customTask of CustomTask s n -> arr (\input -> input ++ duplicate s n) ``` What happens here is: 1. We get the `customTask` of our type `CustomTask`. 2. We consider the possible values. As we've defined it, `CustomTask` has only one value constructor, but in general a GADT may have multiple value constructors. 3. Since our function is pure, we can simply wrap it inside of an `Arrow` using `arr`. `\input -> input ++ duplicate s n` is the actual function that will be executed when running the pipeline. > In funflow, pure computation should be wrapped in a `Arrow` while IO operations should wrapped in a `Kleisli IO`. > > Wrapping in an `Arrow` is done by using `arr`, while wrapping in a `Kleisli IO` is done by using `liftKleisliIO`. `funflow`'s interpreter functions are defined in the `Funflow.Run` module and can serve as examples as you write your own interpreter functions. ### Run your custom flow Now that we have defined a way to run our task, we might as well run our pipeline! To run a pipeline typed as `Flow`, funflow provides `runFlow`. Since we've built--in order to include our custom task type--a different type of pipeline (`MyFlow`), though, in order to leverage `runFlow` we first need an additional step. We will use the `weave'` function from `kernmantle`. > In `kernmantle`, intepreting a task with a function is called _weaving_ a strand. > > There are multiple function available to weave strands (`weave`, `weave'`, `weave''`, `weaveK`). > Almost always, the one you want is `weave'`. ``` import Control.Kernmantle.Rope ((&), weave') import Funflow.Flow (Flow) weaveMyFlow myFlow = myFlow & weave' #custom interpretCustomTask ``` > `kernmantle`'s `&` operator allows us to "weave in," or "chain," multiple strands, e.g.: > ```haskell > weaveMyFlow myFlow = myFlow & weave' #custom1 interpretCustomTask1 & weave' #custom2 interpretCustomTask2 > ``` Now, we can run the resulting flow: ``` :opt no-lint import Funflow.Run (runFlow) runMyFlow :: MyFlow i o -> i -> IO o runMyFlow myFlow input = runFlow (weaveMyFlow myFlow) input runMyFlow myFlow "Kangaroo goes " :: IO String ``` > We have to specify the type of the result `IO String` because of some issues with type inference when using GADTs. ## Going further See more about `kernmantle` here: https://github.com/tweag/kernmantle
github_jupyter
# Document AI OCR (async) This notebook shows you how to do OCR on documents using the Google Cloud DocumentAI API asynchronously. For the asynchronous request the GCS URI or GCS bucket with prefix will be send for one or more documents and an operation ID is returned. The operation status will be checked until the result is available. The response is then visualized showing the preprocessed (e.g. rotated) image together with bounding boxes for block, paragraph, line and token. ## Set your Processor Variables ``` PROJECT_ID = "YOUR_GCP_PROJECT_ID" LOCATION = "eu" # Format is 'us' or 'eu' PROCESSOR_ID = "YOUR_DOCAI_PROCESSOR_ID" # Create OCR processor in Cloud Console # check supported file types at https://cloud.google.com/document-ai/docs/processors-list#processor_doc-ocr SUPPORTED_FILE_TYPES = ["PDF", "TIF", "TIFF", "GIF", "JPG", "JPEG", "PNG", "BMP", "WEBP"] # Sample invoices are stored in gs://cloud-samples-data/documentai/async_invoices/ GCS_INPUT_BUCKET = 'cloud-samples-data' GCS_INPUT_PREFIX = 'documentai' # The output bucket will be created if it does not exist GCS_OUTPUT_BUCKET = PROJECT_ID + '-dai-temp' GCS_OUTPUT_PREFIX = 'output' TIMEOUT = 300 ``` ## Setup ``` # Install necessary Python libraries and restart your kernel after. !pip install --quiet -r ../requirements.txt from google.cloud import documentai_v1 as documentai from google.cloud import storage from PIL import Image, ImageDraw from typing import List import mimetypes import io import os import re import numpy as np from enum import Enum import pandas as pd class FeatureType(Enum): PAGE = 1 BLOCK = 2 PARA = 3 LINE = 4 TOKEN = 5 def batch_process(gcs_output_uri: str, gcs_input_uris: List[str] = [], gcs_input_uri_prefix: str = "", skip_human_review: bool = False) -> dict: """Asynchronous (batch) process documents using REST API. Processes documents stored on Google Cloud Storage (GCS) either by list of GCS URIs or GCS URI Prefix and returns operation status. Optionally allows to skip human review if enabled for the processor. See details at https://cloud.google.com/document-ai/docs/reference/rest/v1/projects.locations.processors/batchProcess Args: gcs_output_uri: GCS URI to save output JSON to (e.g. 'gs://bucket/output'). gcs_input_uris: List of GCS URIs (e.g. ['gs://bucket1/file1.jpg','gs://bucket2/file2.pdf']) gcs_input_uri_prefix: GCS URI Prefix (e.g. 'gs://bucket/prefix') to be checked for supported files. skip_human_review: Optional; Whether Human Review feature should be skipped for this request. Default to false. Returns: An operation reflecting the status of the batch process operation. See details at https://cloud.google.com/document-ai/docs/reference/rest/v1/projects.locations.operations#Operation """ # Instantiate a Document AI client client_options = {"api_endpoint": f"{LOCATION}-documentai.googleapis.com"} client = documentai.DocumentProcessorServiceClient(client_options = client_options) # Instantiate a Storage Client storage_client = storage.Client() input_config = None if len(gcs_input_uris) > 0: documents = [] for gcs_input_uri in gcs_input_uris: if not gcs_input_uri.startswith("gs://"): raise Exception(f"gcs_input_uri {gcs_input_uri} missing gs:// prefix.") mime_type = mimetypes.guess_type(gcs_input_uri)[0] if not mime_type: raise Exception(f"MIME type of gcs_input_uri {gcs_input_uri_prefix} could not be guessed from file extension.") document = {"gcs_uri": gcs_input_uri, "mime_type": mime_type} documents.append(document) gcs_documents = documentai.GcsDocuments(documents=documents) input_config = documentai.BatchDocumentsInputConfig(gcs_documents=gcs_documents) elif gcs_input_uri_prefix: if not gcs_input_uri_prefix.startswith("gs://"): raise Exception(f"gcs_input_uri_prefix {gcs_input_uri_prefix} missing gs:// prefix.") gcs_prefix = documentai.GcsPrefix(gcs_uri_prefix = gcs_input_uri_prefix) input_config = documentai.BatchDocumentsInputConfig(gcs_prefix = gcs_prefix) else: raise Exception("Neither gcs_input_uris nor gcs_input_uri_prefix specified.") output_bucket = storage.Bucket(client = storage_client, name = GCS_OUTPUT_BUCKET) if not output_bucket.exists(): print(f"Bucket {GCS_OUTPUT_BUCKET} does not exist, creating it in location {LOCATION}.") output_bucket.create(location = LOCATION) # The full resource name of the processor, e.g.: # projects/project-id/locations/location/processor/processor-id name = f"projects/{PROJECT_ID}/locations/{LOCATION}/processors/{PROCESSOR_ID}" # Where to write results destination_uri = f"gs://{GCS_OUTPUT_BUCKET}/{GCS_OUTPUT_PREFIX}/" output_config = documentai.DocumentOutputConfig( gcs_output_config={"gcs_uri": destination_uri} ) # Batch Process document batch_process_request = documentai.types.document_processor_service.BatchProcessRequest( name=name, input_documents=input_config, document_output_config=output_config, ) return client.batch_process_documents(request = batch_process_request) def get_page_bounds(page, feature): # [START vision_document_text_tutorial_detect_bounds] """Returns document bounds given the OCR output page.""" bounds = [] # Collect specified feature bounds by enumerating all document features if (feature == FeatureType.BLOCK): for block in page.blocks: if not block.layout.bounding_poly.vertices: block.layout.bounding_poly.vertices = [] for normalized_vertice in block.layout.bounding_poly.normalized_vertices: block.layout.bounding_poly.vertices.append(documentai.Vertex(x=int(normalized_vertice.x * page.image.width),y=int(normalized_vertice.y * page.image.height))) bounds.append(block.layout.bounding_poly) if (feature == FeatureType.PARA): for paragraph in page.paragraphs: if not paragraph.layout.bounding_poly.vertices: paragraph.layout.bounding_poly.vertices = [] for normalized_vertice in paragraph.layout.bounding_poly.normalized_vertices: paragraph.layout.bounding_poly.vertices.append(documentai.Vertex(x=int(normalized_vertice.x * page.image.width),y=int(normalized_vertice.y * page.image.height))) bounds.append(paragraph.layout.bounding_poly) if (feature == FeatureType.LINE): for line in page.lines: if not line.layout.bounding_poly.vertices: line.layout.bounding_poly.vertices = [] for normalized_vertice in line.layout.bounding_poly.normalized_vertices: line.layout.bounding_poly.vertices.append(documentai.Vertex(x=int(normalized_vertice.x * page.image.width),y=int(normalized_vertice.y * page.image.height))) bounds.append(line.layout.bounding_poly) if (feature == FeatureType.TOKEN): for token in page.tokens: if not token.layout.bounding_poly.vertices: token.layout.bounding_poly.vertices = [] for normalized_vertice in token.layout.bounding_poly.normalized_vertices: token.layout.bounding_poly.vertices.append(documentai.Vertex(x=int(normalized_vertice.x * page.image.width),y=int(normalized_vertice.y * page.image.height))) bounds.append(token.layout.bounding_poly) # The list `bounds` contains the coordinates of the bounding boxes. # [END vision_document_text_tutorial_detect_bounds] return bounds def draw_boxes(image, bounds, color, width): """Draw a border around the image using the hints in the vector list.""" draw = ImageDraw.Draw(image) for bound in bounds: points = ( (bound.vertices[0].x, bound.vertices[0].y), (bound.vertices[1].x, bound.vertices[1].y), (bound.vertices[2].x, bound.vertices[2].y), (bound.vertices[3].x, bound.vertices[3].y), (bound.vertices[0].x, bound.vertices[0].y) ) draw.line(points,fill=color,width=width,joint='curve') return image def render_doc_text(page): image = Image.open(io.BytesIO(page.image.content)) # this will draw the bounding boxes for block, paragraph, line and token bounds = get_page_bounds(page, FeatureType.BLOCK) draw_boxes(image, bounds, color='blue', width=8) bounds = get_page_bounds(page, FeatureType.PARA) draw_boxes(image, bounds, color='red',width=6) bounds = get_page_bounds(page, FeatureType.LINE) draw_boxes(image, bounds, color='yellow',width=4) bounds = get_page_bounds(page, FeatureType.TOKEN) draw_boxes(image, bounds, color='green',width=2) image.show() # uncomment if you want to save the image with bounding boxes locally #image.save(document.name) # transforming the image should not be necessary and requires opencv which has a lot of dependencies def transform_image(page): # only install depedencies when necessary !sudo apt -qq install -y python3-opencv !pip install --quiet opencv-python import cv2 img_stream = io.BytesIO(page.image.content) img = cv2.imdecode(np.frombuffer(img_stream.read(), np.uint8), 1) matrix = None data = page.transforms[0].data rows = page.transforms[0].rows cols = page.transforms[0].cols if page.transforms[0].type_ == 0: matrix = np.reshape(np.frombuffer(data, np.uint8), (rows, cols)) elif page.transforms[0].type_ == 1: matrix = np.reshape(np.frombuffer(data, np.int8), (rows, cols)) elif page.transforms[0].type_ == 2: matrix = np.reshape(np.frombuffer(data, np.uint16), (rows, cols)) elif page.transforms[0].type_ == 3: matrix = np.reshape(np.frombuffer(data, np.int16), (rows, cols)) elif page.transforms[0].type_ == 4: matrix = np.reshape(np.frombuffer(data, np.int32), (rows, cols)) elif page.transforms[0].type_ == 5: matrix = np.reshape(np.frombuffer(data, np.float32), (rows, cols)) elif page.transforms[0].type_ == 6: matrix = np.reshape(np.frombuffer(data, np.float64), (rows, cols)) elif page.transforms[0].type_ == 7: matrix = np.reshape(np.frombuffer(data, np.float16), (rows, cols)) # TODO: check rows and cols and implement warpPerspective for 3x3, throw error if not 2x3 or 3x3 # the scale factor is required as the transformed image will be larger than the source image scale_factor = 3 if rows == 2 and cols == 3: transformed_img = cv2.warpAffine(img, matrix, (page.image.width * scale_factor, page.image.height * scale_factor)) elif rows == 3 and cols == 3: transformed_img = cv2.warpPerspective(img, matrix, (page.image.width * scale_factor, page.image.height * scale_factor)) # trim image and remove black border gray = cv2.cvtColor(transformed_img,cv2.COLOR_BGR2GRAY) _,thresh = cv2.threshold(gray,1,255,cv2.THRESH_BINARY) contours,hierarchy = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) cnt = contours[0] x,y,w,h = cv2.boundingRect(cnt) transformed_img = transformed_img[y:y+h,x:x+w] content = cv2.imencode('.jpg', transformed_img)[1].tobytes() height, width, _ = transformed_img.shape page.image = documentai.Document.Page.Image(content=content, mime_type=page.image.mime_type, width=width, height=height) return page ``` ### Process documents asynchronously ``` def batch_process_gcs_samples(): gcs_input_uri_prefix = f"gs://{GCS_INPUT_BUCKET}/{GCS_INPUT_PREFIX}" gcs_output_uri = f"gs://{GCS_OUTPUT_BUCKET}/{GCS_OUTPUT_PREFIX}" print(f"Processing all documents at {gcs_input_uri_prefix}") operation = batch_process(gcs_input_uri_prefix = gcs_input_uri_prefix, gcs_output_uri = gcs_output_uri) operation_id = operation._operation.name.split('/')[-1] print(f"Operation ID: {operation_id}") # Wait for the operation to finish operation.result(timeout=TIMEOUT) # Instantiate a Storage Client storage_client = storage.Client() bucket = storage.Bucket(client = storage_client, name = GCS_OUTPUT_BUCKET) blob_list = list(bucket.list_blobs(prefix=f"{GCS_OUTPUT_PREFIX}/{operation_id}")) for i, blob in enumerate(blob_list): # If JSON file, download the contents of this blob as a bytes object. if ".json" in blob.name: blob_as_bytes = blob.download_as_string() document = documentai.types.Document.from_json(blob_as_bytes) # For a full list of Document object attributes, please reference this page: # https://cloud.google.com/document-ai/docs/reference/rpc/google.cloud.documentai.v1#document for page in document.pages: # TODO: remove once b/196544985 is fixed if page.transforms: page = transform_image(page) print(f"Rendering file {blob.name} - Page {page.page_number}/{len(document.pages)}") render_doc_text(page=page) #remove blob, uncomment if you want to inspect the output json print(f"Deleting object {blob.name}") blob.delete() batch_process_gcs_samples() ```
github_jupyter
``` from pyknp import KNP knp = KNP() def knp_deps(sent): result = knp.parse(sent) for bnst in result.bnst_list(): parent = bnst.parent if parent is not None: child_rep = " ".join(mrph.repname for mrph in bnst.mrph_list()) parent_rep = " ".join(mrph.repname for mrph in parent.mrph_list()) print(child_rep, "->", parent_rep) knp_deps("望遠鏡で泳いでいる少女を見た。") sent="望遠鏡で泳いでいる少女を見た。" result = knp.parse(sent) for bnst in result.bnst_list(): print(f"{bnst.bnst_id}, {bnst.midasi}, {bnst.parent_id}, {bnst.repname}, {bnst.dpndtype}") result.draw_bnst_tree() result.draw_tag_tree() upos_maps={'形容詞':'ADJ', '副詞':'ADV', '接続詞':'CCONJ', '連体詞':'DET', '感動詞':'INTJ', '名詞':'NOUN', '名詞-数詞':'NUM', '代名詞':'PRON', '名詞-固有名詞':'PROPN', '補助記号':'PUNCT', '動詞':'VERB', '未定義語':'X' } upos_rev_maps={'PUNCT':['特殊-句点', '特殊-読点'], 'SYM':['補助記号', '補助記号-一般', '補助記号-AA-顔文字'], 'ADP':['助詞-格助詞', '助詞-係助詞'], 'AUX':['助動詞', '動詞-非自立可能', '形容詞-非自立可能'], 'SCONJ':['接続詞', '助詞-接続助詞','助詞-準体助詞'], 'CCONJ':['助詞-格助詞','助詞-格助詞', '助詞-副助詞'], 'PART':['助詞-終助詞', '接尾辞-形状詞的']} def get_pos_mapping(pos1, pos2, default_val='X'): for pos in [f"{pos1}-{pos2}", pos1]: if pos in upos_maps: return upos_maps[pos] else: for k, v in upos_rev_maps.items(): if pos in v: return k return default_val print(get_pos_mapping('名詞', '固有名詞'), get_pos_mapping('助詞','接続助詞'), ) POS_MARK = { '特殊': '*', '動詞': 'v', '形容詞': 'j', '判定詞': 'c', '助動詞': 'x', '名詞': 'n', '固有名詞': 'N', '人名': 'J', '地名': 'C', '組織名': 'A', '指示詞': 'd', '副詞': 'a', '助詞': 'p', '接続詞': 'c', '連体詞': 'm', '感動詞': '!', '接頭辞': 'p', '接尾辞': 's', '未定義語': '?' } ner_mappings={'固有名詞':'MISC', '人名':'PERSON', '地名':'LOC', '組織名':'ORG'} def pos_list(leaf): import re string=[] for mrph in leaf.mrph_list(): # string += mrph.midasi # bunrui (str): 品詞細分類 # hinsi (str): 品詞 if re.search("^(?:固有名詞|人名|地名)$", mrph.bunrui): string.append(POS_MARK[mrph.bunrui]) else: string.append(POS_MARK[mrph.hinsi]) return string def pos_map_list(leaf): string=[] for mrph in leaf.mrph_list(): string.append(get_pos_mapping(mrph.hinsi, mrph.bunrui)) return string def entity_list(leaf): import re string=[] for mrph in leaf.mrph_list(): if mrph.bunrui in ner_mappings: string.append(ner_mappings[mrph.bunrui]) return string import sagas def parse_knp(sents, verbose=False): result = knp.parse(sents) print("文節") rs=[] for bnst in result.bnst_list(): # 各文節へのアクセス if verbose: print("\tID:%d, 見出し:%s, 係り受けタイプ:%s, 親文節ID:%d, 素性:%s" \ % (bnst.bnst_id, "".join(mrph.midasi for mrph in bnst.mrph_list()), bnst.dpndtype, bnst.parent_id, bnst.fstring)) rs.append((bnst.bnst_id, "".join(mrph.midasi for mrph in bnst.mrph_list()), bnst.dpndtype, bnst.parent_id, bnst.fstring)) display(sagas.to_df(rs, ['ID', '見出し', '係り受けタイプ(dep_type)', '親文節ID', '素性'])) print("基本句") rs=[] for tag in result.tag_list(): # 各基本句へのアクセス if verbose: print("\tID:%d, 見出し:%s, 係り受けタイプ:%s, 親基本句ID:%d, 素性:%s" \ % (tag.tag_id, "".join(mrph.midasi for mrph in tag.mrph_list()), tag.dpndtype, tag.parent_id, tag.fstring)) rs.append((tag.tag_id, "".join(mrph.midasi for mrph in tag.mrph_list()), ",".join(pos_list(tag)), ','.join(pos_map_list(tag)), ",".join(entity_list(tag)), tag.dpndtype, tag.parent_id, tag.fstring)) display(sagas.to_df(rs, ['ID', '見出し', 'POS', 'UPOS', 'Entities', '係り受けタイプ', '親基本句ID', '素性'])) print("形態素") rs=[] for mrph in result.mrph_list(): # 各形態素へのアクセス if verbose: print("\tID:%d, 見出し:%s, 読み:%s, 原形:%s, 品詞:%s, 品詞細分類:%s, 活用型:%s, 活用形:%s, 意味情報:%s, 代表表記:%s" \ % (mrph.mrph_id, mrph.midasi, mrph.yomi, mrph.genkei, mrph.hinsi, mrph.bunrui, mrph.katuyou1, mrph.katuyou2, mrph.imis, mrph.repname)) rs.append((mrph.mrph_id, mrph.midasi, mrph.yomi, mrph.genkei, mrph.hinsi, mrph.bunrui, mrph.katuyou1, mrph.katuyou2, mrph.imis, mrph.repname)) display(sagas.to_df(rs, 'ID:%d, 見出し:%s, 読み:%s, 原形:%s, 品詞:%s, 品詞細分類:%s, 活用型:%s, 活用形:%s, 意味情報:%s, 代表表記:%s'.split(', '))) parse_knp("下鴨神社の参道は暗かった。") parse_knp('私の趣味は、多くの小旅行をすることです。') parse_knp("私は望遠鏡で泳いでいる少女を見た。") parse_knp('自由を手に入れる') def put_items(some_map, keyset, val): keystr=':'.join([str(k) for k in sorted(keyset)]) some_map[keystr]=val def get_by_keyset(some_map, keyset): keystr=':'.join([str(k) for k in sorted(keyset)]) # print(keystr) if keystr in some_map: return some_map[keystr] return None def remove_by_keyset(some_map, keyset): keystr=':'.join([str(k) for k in sorted(keyset)]) del some_map[keystr] some_map={} put_items(some_map, {2,1}, 'hi') put_items(some_map, {1,2}, 'hi') put_items(some_map, {2,3}, 'xx') put_items(some_map, {8,0}, 'xx') put_items(some_map, {1,8}, 'xx') print(some_map) print(get_by_keyset(some_map, {3,2})) remove_by_keyset(some_map, {2,3}) print(some_map) def merge_chunk(bnst): chunk="".join(mrph.midasi for mrph in bnst.mrph_list()) tag_size=len(bnst.tag_list()) return f"{chunk}({tag_size})" def merge_tag(tag): chunk=", ".join(mrph.midasi for mrph in tag.mrph_list()) return chunk def print_predicates(result): deps={} predicates=[] predicts=[] for tag in result.tag_list(): if tag.pas is not None: # find predicate predict_cnt=''.join(mrph.midasi for mrph in tag.mrph_list()) print(tag.tag_id, '. 述語: %s' % predict_cnt) predicates.append(merge_tag(tag)) p_args=[] for case, args in tag.pas.arguments.items(): # case: str, args: list of Argument class for arg in args: # arg: Argument class print('\t格: %s, 項: %s (項の基本句ID: %d)' % (case, arg.midasi, arg.tid)) put_items(deps, {tag.tag_id, arg.tid}, case) p_args.append({'name':case, 'value':arg.midasi, 'start':arg.tid, 'end':arg.tid}) predicts.append({'index':tag.tag_id, 'predicate':predict_cnt, 'args':p_args}) print(deps, predicates) print(predicts) return deps, predicates class KnpViz(object): def __init__(self, shape='egg', size='8,5', fontsize=0): from graphviz import Digraph self.f = Digraph('deps', filename='deps.gv') self.f.attr(rankdir='LR', size=size) # font 'Calibri' support Arabic text self.f.attr('node', shape=shape, fontname='Calibri') if fontsize != 0: self.f.attr(fontsize=str(fontsize)) self.prop_sets = {'VERB': lambda f: f.attr('node', style='filled', color='lightgrey'), 'PRON': lambda f: f.attr('node', style='dashed', color='red'), 'AUX': lambda f: f.attr('node', style='dashed', color='green'), 'NOUN': lambda f: f.attr('node', style='solid', color='blue'), } def default_node(self): self.f.attr('node', style='solid', color='black') def process_tags(self, sents): result = knp.parse(sents) print(sents) deps, predicates=print_predicates(result) self.prop_sets['VERB'](self.f) for pr in predicates: self.f.node(pr) self.default_node() establish_set={} rs=[] words=result.tag_list() for tag in words: # 各基本句へのアクセス if verbose: print("\tID:%d, 見出し:%s, 係り受けタイプ:%s, 親基本句ID:%d, 素性:%s" \ % (tag.tag_id, "".join(mrph.midasi for mrph in tag.mrph_list()), tag.dpndtype, tag.parent_id, tag.fstring)) node_text=merge_tag(tag) rs.append((tag.tag_id, "".join(mrph.midasi for mrph in tag.mrph_list()), ",".join(pos_list(tag)), ','.join(pos_map_list(tag)), ",".join(entity_list(tag)), tag.dpndtype, tag.parent_id, tag.fstring)) rel=tag.dpndtype if tag.parent_id==-1: head_node='ROOT' else: head_node=merge_tag(words[tag.parent_id]) rel=get_by_keyset(deps, {tag.tag_id, tag.parent_id}) # print(tag.tag_id, tag.parent_id, {tag.tag_id, tag.parent_id}, rel) if rel is None: rel=tag.dpndtype else: remove_by_keyset(deps, {tag.tag_id, tag.parent_id}) self.f.edge(head_node, node_text, label=rel, fontsize='11', fontname='Calibri') display(sagas.to_df(rs, ['ID', '見出し', 'POS', 'UPOS', 'Entities', '係り受けタイプ(dep_type)', '親基本句ID', '素性'])) print('leaves', deps) return self.f def process(self, sents): result = knp.parse(sents) print(sents) print_predicates(result) rs=[] words=result.bnst_list() for bnst in words: # 各文節へのアクセス if verbose: print("\tID:%d, 見出し:%s, 係り受けタイプ:%s, 親文節ID:%d, 素性:%s" \ % (bnst.bnst_id, "".join(mrph.midasi for mrph in bnst.mrph_list()), bnst.dpndtype, bnst.parent_id, bnst.fstring)) node_text=merge_chunk(bnst) rs.append((bnst.bnst_id, node_text, ",".join(pos_list(bnst)), ','.join(pos_map_list(tag)), ",".join(entity_list(bnst)), bnst.dpndtype, bnst.parent_id, bnst.fstring)) if bnst.parent_id==-1: head_node='ROOT' else: head_node=merge_chunk(words[bnst.parent_id]) self.f.edge(head_node, node_text, label=bnst.dpndtype, fontsize='11', fontname='Calibri') display(sagas.to_df(rs, ['ID', '見出し', 'POS', 'UPOS', 'Entities', '係り受けタイプ(dep_type)', '親文節ID', '素性'])) return self.f # KnpViz().process('各文節へのアクセス') # KnpViz().process("私は望遠鏡で泳いでいる少女を見た。") # KnpViz().process_tags("私は望遠鏡で泳いでいる少女を見た。") sent='久保氏は当初、連合を支持基盤とする民改連との連携を想定した。' KnpViz().process_tags(sent) parse_knp(sent) KnpViz().process('私の趣味は、多くの小旅行をすることです。') KnpViz().process_tags('私の趣味は、多くの小旅行をすることです。') KnpViz().process('下鴨神社の参道は暗かった。') KnpViz().process_tags('下鴨神社の参道は暗かった。') sent="私は望遠鏡で泳いでいる少女を見た。" KnpViz().process_tags(sent) sent='久保氏は当初、連合を支持基盤とする民改連との連携を想定した。' KnpViz().process_tags(sent) KnpViz().process_tags('自由を手に入れる') ```
github_jupyter
(10mins)= # Manage a toy ML project In this quick overview, you will use Mandala to manage a small ML project. You will - set up a pipeline to build and evaluate your own random forest classifier; - evolve the project by extending parameter spaces and functionality; - query the results in various ways, and delete the ones you don't need any more. To start, let's import a few things: ``` from typing import List, Tuple import numpy as np from numpy import ndarray from sklearn.datasets import make_classification from sklearn.metrics import accuracy_score from sklearn.tree import DecisionTreeClassifier from mandala.all import * set_logging_level(level='warning') ``` ## Manage experiments with composable memoization Let's create a storage for the results, and functions to generate a synthetic dataset and train a decision tree: ``` storage = Storage(in_memory=True) @op(storage) def get_data() -> Tuple[ndarray, ndarray]: return make_classification(random_state=0) log_calls = True @op(storage) def train_tree(X, y, max_features=2, random_state=0) -> DecisionTreeClassifier: if log_calls: print('Computing train_tree...') return DecisionTreeClassifier(random_state=random_state, max_depth=2, max_features=max_features).fit(X, y) ``` The `@op` decorator turns functions into **operations**. Inputs/outputs for calls to operations can be [memoized](https://en.wikipedia.org/wiki/Memoization), either in-memory or on disk. In addition to saving the inputs/outputs of function calls, Mandala's memoization - smoothly *composes* through Python's control flow, collections, and functional abstraction; - can load results on demand, getting only the data necessary for control flow to proceed. Below, you'll use this composable behavior to evolve and query the project. ### Retrace memoized code to flexibly interact with storage To start, let's train a few decision trees on the data: ``` with run(storage): X, y = get_data() for i in range(5): train_tree(X, y, random_state=i) ``` As expected, the `train_tree` operation was computed 5 times. All calls to operations inside a `run` block are saved in storage, and re-running a memoized call simply loads its results instead of computing the function. This makes it easy to add more computations directly to memoized code. For example, here's how you can add logic to evaluate the tree ensemble via a majority vote, and also increase the number of trees trained: ``` @op(storage) def eval_forest(trees:List[DecisionTreeClassifier], X, y) -> float: if log_calls: print('Computing eval_forest...') majority_vote = np.array([tree.predict(X) for tree in trees]).mean(axis=0) >= 0.5 return round(accuracy_score(y_true=y, y_pred=majority_vote), 2) with run(storage, lazy=True): X, y = get_data() trees = [train_tree(X, y, random_state=i) for i in range(10)] forest_acc = eval_forest(trees, X, y) print(f'Random forest accuracy: {forest_acc}') ``` Note that - `train_tree` was computed only 5 times, since the first 5 calls were *retraced* - operations return **value references** (like `forest_acc` above), which contain metadata needed for storage and computation. - you can use **collections** of individual value references as inputs/outputs of operations -- like how `eval_forest` takes a list of decision trees -- without duplicating the storage of the collection's elements. By using `lazy=True` (as above) in the `run` context manager, you only load what is necessary for code execution not to be disrupted -- for example, to evaluate a branching condition, or to run new computations. #### Why should you care? The retracing pattern simplifies many aspects of experiment management. It - makes code **open to extension** of parameter spaces and functionality. Directly add new logic to existing code, and re-run it without re-doing expensive work; - enables **expressive queries**. Walk over chains of memoized calls to reach the results you need by directly retracing the steps that generated them. By sprinkling extra control flow when needed, you can query very complex computations; - makes it easy to **resume work after a crash**: just run the code again, and [break jobs with many calls into stages](10mins-hierarchical) to speed up recovery. (10mins-hierarchical)= ### Reduce complexity with hierarchical memoization Once a composition of operations proves to be a useful building block in experiments, you can *extract* it as a higher-level operation using the `@superop` decorator. Below, you'll extract the training of decision as a higher-level operation, and expose the dataset and `max_features` as arguments: ``` @superop(storage) def train_trees(X, y, max_features=2, n_trees=10) -> List[DecisionTreeClassifier]: return [train_tree(X, y, max_features=max_features, random_state=i) for i in range(n_trees)] ``` You can now use this superop to **refactor both the code and the results connected to it**: ``` with run(storage, lazy=True): X, y = get_data() trees = train_trees(X=X, y=y) forest_acc = eval_forest(trees=trees, X=X, y=y) ``` Note that this did not execute any heavy operations -- it only added higher-level indexing to the memoized data. The first call to `train_trees` retraces its internal structure, but all subsequent re-executions will jump straight to its final results. #### Why should you care? Hierarchical memoization extends the computer programming concept of extracting a [subroutine](https://en.wikipedia.org/wiki/Subroutine#Advantages) to the management of *both* code and its results, bringing additional benefits like - **simplicity**: make code *and* queries shorter; - **convenience**: index experimental outcomes in a more meaningful way; - **efficiency**: skip over uninteresting calls when retracing, and improve the time complexity of queries by matching to higher-level patterns. - This turns retracing into a practical tool for large projects, since in any human-designed scenario where you must retrace a large number of calls, these calls will have some abstractable structure that you can extract to a `@superop` and skip over. Together, these properties allow projects to *scale up practically indefinitely*, as long as the designers themselves have a scalable and hierarchical mental decomposition of the logic. ## Turn code into a declarative query interface Retracing is very effective at interacting with storage when the space of input parameters (from which retracing must begin) is known to you in advance. This is not always the case. To make sense of all that exists in storage, you can use a complementary interface for *pattern-matching* against the structure of experiments. First, let's create a bit more data to query by running more experiments: ``` log_calls = False with run(storage, lazy=True): X, y = get_data() for n_trees in (10, 20): trees = train_trees(X=X, y=y, n_trees=n_trees) forest_acc = eval_forest(trees=trees, X=X, y=y) ``` Composing a query works a lot like composing the experiment being queried (so much that a good first step is to just copy-paste the computational code). For example, here is how you can query the relationship between the accuracy of the random forest and the number of trees in it: ``` with query(storage) as q: X, y = get_data() n_trees = Query().named('n_trees') trees = train_trees(X, y, n_trees=n_trees) forest_acc = eval_forest(trees, X, y).named('forest_acc') df = q.get_table(n_trees, forest_acc) df ``` ### What just happened? The `query` context *significantly* changes the meaning of Python code: - calls to `@op`/`@superop`-decorated functions build a pattern-matching graph encoding the query; - This graph represents computational dependencies between variables (such as `n_trees` and `forest_acc`) imposed by operations (such as `train_trees`); - to query the graph, you provide a sequence of variables. The result is a table, where each row is a matching of values to these variables that satisfies *all* the dependencies. ### Advanced use: matching more interesting patterns Above, you queried using the higher-level operation `train_trees` to directly get the list of decision trees from the data. However, you can also do a lower-level query through the internals of `train_trees`! #### A bit of refactoring To make this a little more interesting, suppose you also want to look at the accuracy of each individual tree in the forest. The trees are computed inside the `train_trees` operation, so this is also the natural place to compute their accuracies. However, execution skips over past calls to `train_trees`, so you can't really go inside. To overcome this, you can create a **new version** of `train_trees`, which does not remember the calls to the previous version, and will thus execute them again with the updated logic to evaluate the trees. Then, simply re-run the project to re-compute calls to the new version: ``` @op(storage) def eval_tree(tree, X, y) -> float: return round(accuracy_score(y_true=y, y_pred=tree.predict(X)), 2) @superop(storage, version='1') # note the version update! def train_trees(X, y, max_features=2, n_trees=10) -> List[DecisionTreeClassifier]: trees = [train_tree(X, y, max_features=max_features, random_state=i) for i in range(n_trees)] for tree in trees: eval_tree(tree, X, y) # new logic return trees with run(storage, lazy=True): X, y = get_data() for n_trees in (10, 20): trees = train_trees(X=X, y=y, n_trees=n_trees) forest_acc = eval_forest(trees=trees, X=X, y=y) ``` Note that the new version of `train_trees` still returns the same list of trees, so downstream calls using this list are unaffected. The only new work done was running `eval_tree` inside `train_trees`. #### Advanced query patterns Below is code to query the internals of `train_tree`: ``` with query(storage) as q: X, y = get_data() tree = train_tree(X, y).named('tree') tree_acc = eval_tree(tree, X, y).named('tree_acc') df_trees = q.get_table(tree, tree_acc) print(df_trees.head()) with q.branch(): trees = MakeList(containing=tree, at_index=0).named('trees') forest_acc = eval_forest(trees, X, y).named('forest_acc') df_forest = q.get_table(trees, forest_acc) print(df_forest) ``` The above example introduces two new concepts: - the `MakeList` built-in function matches a list given a variable representing an element of the list. The additional constraint `at_index=0` makes it so that you don't match `trees` multiple times for each of its elements. - the `.branch()` context can be used to give scope to dependencies, so that different code blocks don't interact with one another unless one explicitly uses another's variables. This allows you to match to any `tree` outside the `branch()` context, yet match only the first tree in the list `trees` inside it. The upshot is that query structure can be re-used to see both the forest and the trees :) ## A few other things ### Update an operation to preserve past results Above, you created a new version of `train_trees` -- which behaves like an entirely new operation, sharing only its name with the previous version. In particular, all connection to past calls of `train_trees` is lost in the new version, which forces recomputation of all calls to `train_trees`. Often, you don't want to lose the connection to past results. You can do this by **updating** an operation instead. For example, let's expose a parameter of `get_data`: ``` @op(storage) def get_data(n_samples=CompatArg(default=100)) -> Tuple[ndarray, ndarray]: return make_classification(n_samples=n_samples, random_state=0) ``` Calls to `get_data` can now use the new argument; all existing calls will behave as if they were called with `n_samples=100`. #### Why should you care? Updating an operation makes it easy to evolve logic in many practical cases: - expose parameters in the operation's interface that were hard-coded in its body until now; - extend the operation's behavior, for example by adding a new method for processing the input data; - create a closely related variant of the operation that can coexist with the current one, of fix a bug affecting only some calls to the operation. ### Deletion: run code in undo mode If you want to un-memoize the results of some calls, wrap them in a `delete` block: ``` with run(storage, lazy=True, autocommit=True): X, y = get_data() with delete(): trees = train_trees(X=X, y=y, n_trees=20) ``` It's important to understand just what you deleted by doing this. Deletion works by - collecting all calls captured in a `delete` block, recursively including those inside higher-level operations; - deleting these calls and their outputs; - and all results and calls that were computed using these outputs; - and all calls that involve (as inputs or outputs) any of the deleted values described above. This means that all decision trees trained in the call to `train_trees` got deleted. These are *all* decision trees in the project, since the first 10 are shared between the calls with `n_trees=10` and `n_trees=20`. As a consequence, the call to `train_trees` with `n_trees=10` is deleted too, because it involves a list of deleted trees. There’s also a declarative interface to delete results, which is analogous to the declarative query interface. ## Next steps There are some important capabilities of the library not covered in this tutorial. These will be linked to if tutorials on them become available: - you can disable memoization selectively on a per-output basis. This can be used to force quantities to be recomputed on demand when this is more practical than saving and loading (think `lambda x: x + 1` for a large array `x`); - you can use custom object storage logic on a per-type basis (the default is `joblib`, and there's builtin support for `sqlite`+`pickle` too); - you can nest different kinds of contexts, for example a `query` context inside a `run` context, to compose their functionality
github_jupyter
# Modeling and Simulation in Python Chapter 12 Copyright 2017 Allen Downey License: [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0) ``` # Configure Jupyter so figures appear in the notebook %matplotlib inline # Configure Jupyter to display the assigned value after an assignment %config InteractiveShell.ast_node_interactivity='last_expr_or_assign' # import functions from the modsim.py module from modsim import * ``` ### Code Here's the code from the previous notebook that we'll need. ``` def make_system(beta, gamma): """Make a system object for the SIR model. beta: contact rate in days gamma: recovery rate in days returns: System object """ init = State(S=89, I=1, R=0) init /= sum(init) t0 = 0 t_end = 7 * 14 return System(init=init, t0=t0, t_end=t_end, beta=beta, gamma=gamma) def update_func(state, t, system): """Update the SIR model. state: State with variables S, I, R t: time step system: System with beta and gamma returns: State object """ s, i, r = state infected = system.beta * i * s recovered = system.gamma * i s -= infected i += infected - recovered r += recovered return State(S=s, I=i, R=r) def run_simulation(system, update_func): """Runs a simulation of the system. system: System object update_func: function that updates state returns: TimeFrame """ frame = TimeFrame(columns=system.init.index) frame.row[system.t0] = system.init for t in linrange(system.t0, system.t_end): frame.row[t+1] = update_func(frame.row[t], t, system) return frame ``` ### Metrics Given the results, we can compute metrics that quantify whatever we are interested in, like the total number of sick students, for example. ``` def calc_total_infected(results): """Fraction of population infected during the simulation. results: DataFrame with columns S, I, R returns: fraction of population """ return get_first_value(results.S) - get_last_value(results.S) ``` Here's an example.| ``` beta = 0.333 gamma = 0.25 system = make_system(beta, gamma) results = run_simulation(system, update_func) print(beta, gamma, calc_total_infected(results)) ``` **Exercise:** Write functions that take a `TimeFrame` object as a parameter and compute the other metrics mentioned in the book: 1. The fraction of students who are sick at the peak of the outbreak. 2. The day the outbreak peaks. 3. The fraction of students who are sick at the end of the semester. Note: Not all of these functions require the `System` object, but when you write a set of related functons, it is often convenient if they all take the same parameters. Hint: If you have a `TimeSeries` called `I`, you can compute the largest value of the series like this: I.max() And the index of the largest value like this: I.idxmax() You can read about these functions in the `Series` [documentation](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html). ``` # Solution goes here # Solution goes here # Solution goes here ``` ### What if? We can use this model to evaluate "what if" scenarios. For example, this function models the effect of immunization by moving some fraction of the population from S to R before the simulation starts. ``` def add_immunization(system, fraction): """Immunize a fraction of the population. Moves the given fraction from S to R. system: System object fraction: number from 0 to 1 """ system.init.S -= fraction system.init.R += fraction ``` Let's start again with the system we used in the previous sections. ``` tc = 3 # time between contacts in days tr = 4 # recovery time in days beta = 1 / tc # contact rate in per day gamma = 1 / tr # recovery rate in per day system = make_system(beta, gamma) ``` And run the model without immunization. ``` results = run_simulation(system, update_func) calc_total_infected(results) ``` Now with 10% immunization. ``` system2 = make_system(beta, gamma) add_immunization(system2, 0.1) results2 = run_simulation(system2, update_func) calc_total_infected(results2) ``` 10% immunization leads to a drop in infections of 16 percentage points. Here's what the time series looks like for S, with and without immunization. ``` plot(results.S, '-', label='No immunization') plot(results2.S, '--', label='10% immunization') decorate(xlabel='Time (days)', ylabel='Fraction susceptible') savefig('figs/chap12-fig01.pdf') ``` Now we can sweep through a range of values for the fraction of the population who are immunized. ``` immunize_array = linspace(0, 1, 11) for fraction in immunize_array: system = make_system(beta, gamma) add_immunization(system, fraction) results = run_simulation(system, update_func) print(fraction, calc_total_infected(results)) ``` This function does the same thing and stores the results in a `Sweep` object. ``` def sweep_immunity(immunize_array): """Sweeps a range of values for immunity. immunize_array: array of fraction immunized returns: Sweep object """ sweep = SweepSeries() for fraction in immunize_array: system = make_system(beta, gamma) add_immunization(system, fraction) results = run_simulation(system, update_func) sweep[fraction] = calc_total_infected(results) return sweep ``` Here's how we run it. ``` immunize_array = linspace(0, 1, 21) infected_sweep = sweep_immunity(immunize_array) ``` And here's what the results look like. ``` plot(infected_sweep) decorate(xlabel='Fraction immunized', ylabel='Total fraction infected', title='Fraction infected vs. immunization rate', legend=False) savefig('figs/chap12-fig02.pdf') ``` If 40% of the population is immunized, less than 4% of the population gets sick. ### Logistic function To model the effect of a hand-washing campaign, I'll use a [generalized logistic function](https://en.wikipedia.org/wiki/Generalised_logistic_function) (GLF), which is a convenient function for modeling curves that have a generally sigmoid shape. The parameters of the GLF correspond to various features of the curve in a way that makes it easy to find a function that has the shape you want, based on data or background information about the scenario. ``` def logistic(x, A=0, B=1, C=1, M=0, K=1, Q=1, nu=1): """Computes the generalize logistic function. A: controls the lower bound B: controls the steepness of the transition C: not all that useful, AFAIK M: controls the location of the transition K: controls the upper bound Q: shift the transition left or right nu: affects the symmetry of the transition returns: float or array """ exponent = -B * (x - M) denom = C + Q * exp(exponent) return A + (K-A) / denom ** (1/nu) ``` The following array represents the range of possible spending. ``` spending = linspace(0, 1200, 21) ``` `compute_factor` computes the reduction in `beta` for a given level of campaign spending. `M` is chosen so the transition happens around \$500. `K` is the maximum reduction in `beta`, 20%. `B` is chosen by trial and error to yield a curve that seems feasible. ``` def compute_factor(spending): """Reduction factor as a function of spending. spending: dollars from 0 to 1200 returns: fractional reduction in beta """ return logistic(spending, M=500, K=0.2, B=0.01) ``` Here's what it looks like. ``` percent_reduction = compute_factor(spending) * 100 plot(spending, percent_reduction) decorate(xlabel='Hand-washing campaign spending (USD)', ylabel='Percent reduction in infection rate', title='Effect of hand washing on infection rate', legend=False) ``` **Exercise:** Modify the parameters `M`, `K`, and `B`, and see what effect they have on the shape of the curve. Read about the [generalized logistic function on Wikipedia](https://en.wikipedia.org/wiki/Generalised_logistic_function). Modify the other parameters and see what effect they have. ### Hand washing Now we can model the effect of a hand-washing campaign by modifying `beta` ``` def add_hand_washing(system, spending): """Modifies system to model the effect of hand washing. system: System object spending: campaign spending in USD """ factor = compute_factor(spending) system.beta *= (1 - factor) ``` Let's start with the same values of `beta` and `gamma` we've been using. ``` tc = 3 # time between contacts in days tr = 4 # recovery time in days beta = 1 / tc # contact rate in per day gamma = 1 / tr # recovery rate in per day beta, gamma ``` Now we can sweep different levels of campaign spending. ``` spending_array = linspace(0, 1200, 13) for spending in spending_array: system = make_system(beta, gamma) add_hand_washing(system, spending) results = run_simulation(system, update_func) print(spending, system.beta, calc_total_infected(results)) ``` Here's a function that sweeps a range of spending and stores the results in a `SweepSeries`. ``` def sweep_hand_washing(spending_array): """Run simulations with a range of spending. spending_array: array of dollars from 0 to 1200 returns: Sweep object """ sweep = SweepSeries() for spending in spending_array: system = make_system(beta, gamma) add_hand_washing(system, spending) results = run_simulation(system, update_func) sweep[spending] = calc_total_infected(results) return sweep ``` Here's how we run it. ``` spending_array = linspace(0, 1200, 20) infected_sweep = sweep_hand_washing(spending_array) ``` And here's what it looks like. ``` plot(infected_sweep) decorate(xlabel='Hand-washing campaign spending (USD)', ylabel='Total fraction infected', title='Effect of hand washing on total infections', legend=False) savefig('figs/chap12-fig03.pdf') ``` Now let's put it all together to make some public health spending decisions. ### Optimization Suppose we have \$1200 to spend on any combination of vaccines and a hand-washing campaign. ``` num_students = 90 budget = 1200 price_per_dose = 100 max_doses = int(budget / price_per_dose) dose_array = linrange(max_doses, endpoint=True) max_doses ``` We can sweep through a range of doses from, 0 to `max_doses`, model the effects of immunization and the hand-washing campaign, and run simulations. For each scenario, we compute the fraction of students who get sick. ``` for doses in dose_array: fraction = doses / num_students spending = budget - doses * price_per_dose system = make_system(beta, gamma) add_immunization(system, fraction) add_hand_washing(system, spending) results = run_simulation(system, update_func) print(doses, system.init.S, system.beta, calc_total_infected(results)) ``` The following function wraps that loop and stores the results in a `Sweep` object. ``` def sweep_doses(dose_array): """Runs simulations with different doses and campaign spending. dose_array: range of values for number of vaccinations return: Sweep object with total number of infections """ sweep = SweepSeries() for doses in dose_array: fraction = doses / num_students spending = budget - doses * price_per_dose system = make_system(beta, gamma) add_immunization(system, fraction) add_hand_washing(system, spending) results = run_simulation(system, update_func) sweep[doses] = calc_total_infected(results) return sweep ``` Now we can compute the number of infected students for each possible allocation of the budget. ``` infected_sweep = sweep_doses(dose_array) ``` And plot the results. ``` plot(infected_sweep) decorate(xlabel='Doses of vaccine', ylabel='Total fraction infected', title='Total infections vs. doses', legend=False) savefig('figs/chap12-fig04.pdf') ``` ### Exercises **Exercise:** Suppose the price of the vaccine drops to $50 per dose. How does that affect the optimal allocation of the spending? **Exercise:** Suppose we have the option to quarantine infected students. For example, a student who feels ill might be moved to an infirmary, or a private dorm room, until they are no longer infectious. How might you incorporate the effect of quarantine in the SIR model? ``` # Solution goes here ```
github_jupyter
# Visualizing analyses with fresnel In this notebook, we simulate a system of tetrahedra, color particles according to their local density, and path-trace the resulting image with [fresnel](https://github.com/glotzerlab/fresnel). The cell below runs a short [HOOMD-blue](https://github.com/glotzerlab/hoomd-blue/) simulation of tetrahedra using Hard Particle Monte Carlo (HPMC). ``` import hoomd import hoomd.hpmc hoomd.context.initialize("") # Create an 8x8x8 simple cubic lattice system = hoomd.init.create_lattice(unitcell=hoomd.lattice.sc(a=1.5), n=8) # Create our tetrahedra and configure the HPMC integrator mc = hoomd.hpmc.integrate.convex_polyhedron(seed=42) mc.set_params(d=0.2, a=0.1) vertices = [(0.5, 0.5, 0.5), (-0.5, -0.5, 0.5), (-0.5, 0.5, -0.5), (0.5, -0.5, -0.5)] mc.shape_param.set("A", vertices=vertices) # Run for 5,000 steps hoomd.run(5e3) snap = system.take_snapshot() ``` Now we import the modules needed for analysis and visualization. ``` import fresnel import freud import matplotlib.cm import numpy as np from matplotlib.colors import Normalize device = fresnel.Device() ``` Next, we'll set up the arrays needed for the scene and its geometry. This includes the analysis used for coloring particles. ``` poly_info = fresnel.util.convex_polyhedron_from_vertices(vertices) positions = snap.particles.position orientations = snap.particles.orientation box = freud.Box.from_box(snap.box) ld = freud.density.LocalDensity(3.0, 1.0) ld.compute(system=snap) colors = matplotlib.cm.viridis(Normalize()(ld.density)) box_points = np.asarray( [ box.make_absolute( [ [0, 0, 0], [0, 0, 0], [0, 0, 0], [1, 1, 0], [1, 1, 0], [1, 1, 0], [0, 1, 1], [0, 1, 1], [0, 1, 1], [1, 0, 1], [1, 0, 1], [1, 0, 1], ] ), box.make_absolute( [ [1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 0, 0], [0, 1, 0], [1, 1, 1], [1, 1, 1], [0, 1, 0], [0, 0, 1], [0, 0, 1], [1, 1, 1], [1, 0, 0], ] ), ] ) ``` This cell creates the scene and geometry objects to be rendered by `fresnel`. ``` scene = fresnel.Scene(device) geometry = fresnel.geometry.ConvexPolyhedron( scene, poly_info, position=positions, orientation=orientations, color=fresnel.color.linear(colors), ) geometry.material = fresnel.material.Material( color=fresnel.color.linear([0.25, 0.5, 0.9]), roughness=0.8, primitive_color_mix=1.0 ) geometry.outline_width = 0.05 box_geometry = fresnel.geometry.Cylinder(scene, points=box_points.swapaxes(0, 1)) box_geometry.radius[:] = 0.1 box_geometry.color[:] = np.tile([0, 0, 0], (12, 2, 1)) box_geometry.material.primitive_color_mix = 1.0 scene.camera = fresnel.camera.Orthographic.fit(scene, view="isometric", margin=0.1) ``` First, we preview the scene. (This doesn't use path tracing, and is much faster.) ``` fresnel.preview(scene, anti_alias=True, w=600, h=600) ``` Finally, we use path tracing for a high quality image. The number of light samples can be increased to reduce path tracing noise. ``` fresnel.pathtrace(scene, light_samples=16, w=600, h=600) ```
github_jupyter
``` # Visualization of the KO+ChIP Gold Standard from: # Miraldi et al. (2018) "Leveraging chromatin accessibility for transcriptional regulatory network inference in Th17 Cells" # TO START: In the menu above, choose "Cell" --> "Run All", and network + heatmap will load # NOTE: Default limits networks to TF-TF edges in top 1 TF / gene model (.93 quantile), to see the full # network hit "restore" (in the drop-down menu in cell below) and set threshold to 0 and hit "threshold" # You can search for gene names in the search box below the network (hit "Match"), and find regulators ("targeted by") # Change "canvas" to "SVG" (drop-down menu in cell below) to enable drag interactions with nodes & labels # Change "SVG" to "canvas" to speed up layout operations # More info about jp_gene_viz and user interface instructions are available on Github: # https://github.com/simonsfoundation/jp_gene_viz/blob/master/doc/dNetwork%20widget%20overview.ipynb # directory containing gene expression data and network folder directory = "." # folder containing networks netPath = 'Networks' # network file name networkFile = 'KC1p5_sp.tsv' # title for network figure netTitle = 'KO+ChIP G.S.' # name of gene expression file expressionFile = 'Th0_Th17_48hTh.txt' # column of gene expression file to color network nodes rnaSampleOfInt = 'Th17(48h)' # edge cutoff edgeCutoff = 0 import sys if ".." not in sys.path: sys.path.append("..") from jp_gene_viz import dNetwork dNetwork.load_javascript_support() # from jp_gene_viz import multiple_network from jp_gene_viz import LExpression LExpression.load_javascript_support() # Load network linked to gene expression data L = LExpression.LinkedExpressionNetwork() L.show() # Load Network and Heatmap L.load_network(directory + '/' + netPath + '/' + networkFile) L.load_heatmap(directory + '/' + expressionFile) N = L.network N.set_title(netTitle) N.threshhold_slider.value = edgeCutoff N.apply_click(None) N.draw() # Add labels to nodes N.labels_button.value=True # Limit to TFs only, remove unconnected TFs, choose and set network layout N.tf_only_click() N.connected_only_click() N.layout_dropdown.value = 'fruchterman_reingold' N.layout_click() # Interact with Heatmap # Limit genes in heatmap to network genes L.gene_click(None) # Z-score heatmap values L.expression.transform_dropdown.value = 'Z score' L.expression.apply_transform() # Choose a column in the heatmap (e.g., 48h Th17) to color nodes L.expression.col = rnaSampleOfInt L.condition_click(None) # Switch SVG layout to get line colors, then switch back to faster canvas mode N.force_svg(None) ```
github_jupyter
MNIST classification (drawn from sklearn example) ===================================================== MWEM is not particularly well suited for image data (where there are tons of features with relatively large ranges) but it is still able to capture some important information about the underlying distributions if tuned correctly. We use a feature included with MWEM that allows a column to be specified for a custom bin count, if we are capping every other bin count at a small value. In this case, we specify that the numerical column (784) has 10 possible values. We do this with the dict {'784': 10}. Here we borrow from a scikit-learn example, and insert MWEM synthetic data into their training example/visualization, to understand the tradeoffs. https://scikit-learn.org/stable/auto_examples/linear_model/plot_sparse_logistic_regression_mnist.html#sphx-glr-download-auto-examples-linear-model-plot-sparse-logistic-regression-mnist-py ``` import warnings warnings.filterwarnings('ignore') import time import matplotlib.pyplot as plt import numpy as np import pandas as pd from sklearn.datasets import fetch_openml from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.utils import check_random_state # pip install scikit-image from skimage import data, color from skimage.transform import rescale # Author: Arthur Mensch <arthur.mensch@m4x.org> # License: BSD 3 clause # Turn down for faster convergence t0 = time.time() train_samples = 5000 # Load data from https://www.openml.org/d/554 data = fetch_openml('mnist_784', version=1, return_X_y=False) data_np = np.hstack((data.data,np.reshape(data.target.to_numpy().astype(int), (-1, 1)))) from snsynth.mwem import MWEMSynthesizer # Here we set max bin count to be 10, so that we retain the numeric labels synth = MWEMSynthesizer(10.0, 40, 15, 10, split_factor=1, max_bin_count = 128, custom_bin_count={'784':10}) synth.fit(data_np) sample_size = 2000 synthetic = synth.sample(sample_size) from sklearn.linear_model import RidgeClassifier import utils real = pd.DataFrame(data_np[:sample_size]) model_real, model_fake = utils.test_real_vs_synthetic_data(real, synthetic, RidgeClassifier, tsne=True) # Classification coef = model_real.coef_.copy() plt.figure(figsize=(10, 5)) scale = np.abs(coef).max() for i in range(10): l1_plot = plt.subplot(2, 5, i + 1) l1_plot.imshow(coef[i].reshape(28, 28), interpolation='nearest', cmap=plt.cm.RdBu, vmin=-scale, vmax=scale) l1_plot.set_xticks(()) l1_plot.set_yticks(()) l1_plot.set_xlabel('Class %i' % i) plt.suptitle('Classification vector for...') run_time = time.time() - t0 print('Example run in %.3f s' % run_time) plt.show() coef = model_fake.coef_.copy() plt.figure(figsize=(10, 5)) scale = np.abs(coef).max() for i in range(10): l1_plot = plt.subplot(2, 5, i + 1) l1_plot.imshow(coef[i].reshape(28, 28), interpolation='nearest', cmap=plt.cm.RdBu, vmin=-scale, vmax=scale) l1_plot.set_xticks(()) l1_plot.set_yticks(()) l1_plot.set_xlabel('Class %i' % i) plt.suptitle('Classification vector for...') run_time = time.time() - t0 print('Example run in %.3f s' % run_time) plt.show() ```
github_jupyter
``` %pylab inline from __future__ import print_function, division import nibabel as nib import numpy as np import os import stat import os.path as osp import matplotlib.pyplot as plt import nipy import json import scipy.linalg as lin import scipy.stats as sst from warnings import warn import datetime, time import glob as gb from six import string_types import argparse HOME = osp.expanduser('~') atlas_rois = osp.join(HOME,'code', 'regions', 'regions','tmp') DDIR = osp.join(HOME,'data','simpace','data','rename_files','sub01','sess01','preproc') DSRA = osp.join(DDIR, 'smooth') runs_pat = ['*sess01_run{:02d}-0*'.format(i) for i in [1,2,3,4]] runs = [gb.glob(osp.join(DSRA, pat)) for pat in runs_pat] for run in runs: run.sort() print([len(run) for run in runs]) print('\n'.join(runs[0][:4])) _img = nib.load(runs[0][10]) # print(_img.header) ``` ## Step 0: compute fmri mask for this session ``` # import nilearn import nilearn as nil from nilearn import masking as msk from nilearn.image.image import _compute_mean mask = msk.compute_epi_mask(runs[0], opening=1, connected=True) mean0, aff0 = _compute_mean(runs[0]) EXPECTEDSHAPE = (64,64,30,196) assert mean0.shape == EXPECTEDSHAPE[:3] # setup the directories mask_sess = msk.compute_multi_epi_mask(runs, lower_cutoff=0.2, upper_cutoff=0.85, connected=True, opening=2, threshold=0.5) print(mean0.shape) print(mask.shape) print(mask.get_data().shape) print(mask.get_data().dtype) fig, ax = plt.subplots(1,4) sli = 15 r = 142 ax[0].imshow(mask.get_data()[:,:,sli],interpolation='nearest') ax[1].imshow(mask_sess.get_data()[:,:,sli],interpolation='nearest') ax[2].imshow(mean0[:,:,sli],interpolation='nearest') ax[3].imshow(nib.load(runs[0][r]).get_data()[:,:,sli],interpolation='nearest',cmap='gray') ``` ## Step 2: extract roi signals ``` import importlib import utils._utils as ucr ucr = reload(ucr) from nilearn._utils import concat_niimgs run0_4d = concat_niimgs(runs[0], ensure_ndim=4) print(run0_4d.get_data().dtype) assert run0_4d.get_data().shape == EXPECTEDSHAPE print(run0_4d.get_affine()) np.allclose(run0_4d.get_affine(), mask.get_affine()) print(run0_4d.shape) print(run0_4d.get_data().mean()) DROI = osp.join(DDIR, 'registered_files') roi_prefix = 'rraal_*.nii' #rois = gb.glob(osp.join(DROI, roi_prefix)) signals, issues, info = ucr.extract_signals(DROI, roi_prefix, run0_4d, mask=mask, minvox=1) plt.plot(signals['rraal_Thalamus_R__________']) print(info['rraal_Thalamus_L__________']) sig_keys = set(signals.keys()) iss_keys = set(issues.keys()) assert not sig_keys.intersection(iss_keys) signals['rraal_Amygdala_L__________'][:10] arr_sig, labs = ucr._dict_signals_to_arr(signals) print(arr_sig.shape, len(labs)) assert (len(signals) == len(labs)) roi_label = 'rraal_Thalamus_R__________' idx_roi = labs.index(roi_label) print(info.values()[idx_roi]) assert np.allclose(signals[roi_label], arr_sig[:,idx_roi]) labs.index('rraal_Cerebelum_3_R_______') plt.plot(arr_sig[:,42]) DTMP = osp.join(HOME,'data','simpace','data','tmp') fn_mask = osp.join(DTMP, 'mask.nii') mask.to_filename(fn_mask) # why so many nan in the roi? fname = '/home/jb/data/simpace/data/rename_files/sub01/sess01/'+ \ 'preproc/registered_files/rraal_Frontal_Sup_Orb_L___.nii' roi = nib.load(fname) roi_arr = roi.get_data() print((np.logical_not(np.isnan(roi_arr)).sum())) print(np.asarray(roi_arr.shape).prod()) (np.arange(3) > 1).dtype == np.dtype('bool') roi = nib.load(fname) roi_arr = np.asarray(roi.get_data()) print(roi_arr.dtype) roi_arr_not_nan = np.nan_to_num(roi_arr) roi_arr_not_nan.sum() #h = plt.hist(roi_arr.flatten()) h =plt.hist(roi_arr[roi_arr >0],bins=50) DSIG = osp.join(DDIR, 'extracted_signals') import utils.setup_filenames as suf suf = reload(suf) suf.rm_and_create(DSIG) print(DSIG) stat.S_IWGRP | stat.S_IWUSR | stat.S_IWOTH stat.S_IWUSR stat.S_IWGRP print(stat.S_IWRITE, stat.S_IWUSR) type(0o770) %pwd ``` ## Step 3: load confounds ``` print(DDIR) # extract csf time series # dir temporary DCSF = osp.join(DDIR, 'csf_mask') csf_file = osp.join(DCSF, 'csf_map_final.nii.gz') csf_img = nib.load(csf_file) print(csf_img.shape, csf_img.get_data().sum()) print(csf_img.get_data().dtype) h = plt.hist(csf_img.get_data().flatten()) print((csf_img.get_data().astype('bool') > 0.5).sum()) csf_sig, csf_iss, csf_inf = ucr.extract_signals(DCSF, 'csf_map_final.nii.gz', run0_4d) plt.plot(csf_sig['csf_map_final']) print(csf_sig['csf_map_final'].shape) print(DCSF) # load mvt parameters DREALIGN = osp.join(DDIR, 'realign') mvtfile = osp.join(DREALIGN,'rp_asub01_sess01_run01-0006.txt') print(mvtfile) run_len = 196 pat = 'rp_asub??_' + '*-0*.txt' mvfile = gb.glob(osp.join(DREALIGN,pat)) mvtfile mvt0, _ = ucr.extract_mvt(mvtfile, 0, run_len) print(mvt0.shape) ``` ## Step 4: filter ``` osp.dirname(osp.dirname(DDIR)) DDIR dsess = osp.dirname(DDIR) # session directory is one up import json from pprint import pprint fname = gb.glob(osp.join(dsess,"su*params")) print(osp.join(dsess,"su*params")) print(fname) assert osp.isfile(fname[0]) with open(fname[0]) as param: data = json.load(param) import utils._utils as ucr ucr = reload(ucr) nt = 196 dt = 2. frametimes = np.linspace(0, (nt-1)*dt, nt) bf_h = ucr._cosine_high_freq(10.05, frametimes) bf_l = ucr._cosine_low_freq(128, frametimes) bf = np.hstack((bf_l, bf_h)) #_ = plt.imshow(bf, interpolation='nearest',aspect='auto') print(np.any(bf.std(axis=0) < np.finfo(float).eps)) # bf.std(axis=0) plt.plot(bf[:,-1]) import scipy.fftpack as fft bfsc = fft.dct(eye(180)) #plt.imshow(bfsc) #plt.plot(bfsc[:,-1]) #plt.imshow(bf.T.dot(bf), interpolation='nearest') plt.imshow(bfsc.T.dot(bfsc)[:10,:10], interpolation='nearest') bfsc[:5,:2] import utils._utils as ucr ucr = reload(ucr) import utils.setup_filenames as suf suf = reload(suf) from nilearn._utils import concat_niimgs file_names = runs[0] idx_run = 0 mask = mask_sess TR = 2.0 VOLNB = 196 ddir = osp.dirname(osp.dirname(file_names[0])) # preproc dir dsess = osp.dirname(ddir) # session directory is one up droi = osp.join(ddir, 'registered_files') dsig = osp.join(ddir, 'extracted_signals') dreal = osp.join(ddir, 'realign') # - parameter (condition name) paramfile = gb.glob(osp.join(dsess,"sub??_sess??_params")) paramfile = suf._check_glob_res(paramfile, ensure=1, files_only=True) with open(paramfile) as fparam: param = json.load(fparam) mvt_cond = str(param['motion'][idx_run]) # - signal files fn_sig = osp.join(dsig, 'signal_run{:02d}_'.format(idx_run) + mvt_cond) fn_fsig = osp.join(dsig, 'filtered_signal_run{:02d}_'.format(idx_run)+mvt_cond) # - csf file dcsf = osp.join(ddir, 'csf_mask') csf_filename = 'csf_map_final.nii.gz' # - mvt file # example : mvtfile = osp.join(dreal,'rp_asub01_sess01_run01-0006.txt') mvtpat = 'rp_asub??_' + '*-0*.txt' mvtfile = gb.glob(osp.join(dreal, mvtpat)) mvtfile = suf._check_glob_res(mvtfile, ensure=1, files_only=True) # - atlas roi files roi_prefix = 'rraal_*.nii' #- other parameters: low_freq = 0.01 high_freq = 0.15 dt = TR mvtpat = ('rp_asub??_sess??_run{:02d}' + '*-00*.txt').format(idx_run+1) mvtfile = gb.glob(osp.join(dreal, mvtpat)) mvtfile = suf._check_glob_res(mvtfile, ensure=1, files_only=True) print("\n".join([dsess,ddir,paramfile,mvtfile])) run_4d = concat_niimgs(file_names, ensure_ndim=4) signals, _issues, _info = ucr.extract_signals(droi, roi_prefix, run_4d, mask=mask, minvox=1) arr_sig, labels_sig = ucr._dict_signals_to_arr(signals) print(arr_sig.shape) signals, _issues, _info = ucr.extract_signals(droi, roi_prefix, run_4d, mask=None, minvox=1) arr_sig, labels_sig = ucr._dict_signals_to_arr(signals) print(arr_sig.shape) for k in _info.keys()[:5]: print(k, _info[k]) suf.rm_and_create(dsig) np.savez(fn_sig, arr_sig, labels_sig) csf_arr, csf_labs = ucr.extract_roi_run(dcsf, csf_filename, run_4d, check_lengh=VOLNB, standardize=True) plt.plot(csf_arr) print(csf_arr.shape, csf_arr.std(), csf_arr.mean()) bf_arr, bf_labs = ucr.extract_bf(low_freq, high_freq, VOLNB, dt, verbose=False) mvt_arr, mvt_labs = ucr.extract_mvt(mvtfile, idx_run, VOLNB, verbose=1) counfounds = np.hstack((csf_arr, mvt_arr, bf_arr)) counfounds_labs = csf_labs + mvt_labs + bf_labs counfounds.shape counfounds_labs[:10] plt.plot(counfounds.std(axis=0)) arr_sig.shape f_arr_sig = ucr.R_proj(counfounds, arr_sig) t = np.arange(arr_sig.shape[0]) idx = 0 plt.plot(t, arr_sig[:,idx]-arr_sig[:,idx].mean(), t, f_arr_sig[:,idx]) #plt.plot(t, arr_sig[:,44]) dsess = osp.dirname(ddir) dbase = osp.dirname(osp.dirname(dsess)) layout = 'directory_layout.json' dlo = osp.join(dbase, layout) analy_param = 'analysis_parameters.json' apr = osp.join(dbase, analy_param) data_param = 'data_parameters.json' dpr = osp.join(dbase, data_param) import json print(apr) a = json.load(open(dlo)) b = json.load(open(apr)) c = json.load(open(dpr)) print(a) print(b) print(c) a['atlas']['prepat'] b assert isinstance(b['apply_csf'],bool) assert isinstance(b['filter'],dict) print(dbase) DIRLAYOUT = 'directory_layout.json' DATAPARAM = 'data_parameters.json' ANALPARAM = 'analysis_parameters.json' fn_layo = osp.join(dbase, DIRLAYOUT) fn_data = osp.join(dbase, DATAPARAM) fn_anal = osp.join(dbase, ANALPARAM) with open(fn_layo) as flayo: dlayo = json.load(flayo) with open(fn_data) as fdata: ddata = json.load(fdata) with open(fn_anal) as fanal: danal = json.load(fanal) params = {'layout': dlayo, 'data': ddata, 'analysis': danal} params DIRLAYOUT = 'directory_layout.json' DATAPARAM = 'data_parameters.json' ANALPARAM = 'analysis_parameters.json' def get_params(dbase, verbose=False): """ parameters: ----------- dbase: string base directory containing subjects directory and jason files """ # Read json files at the base directory fn_layo = osp.join(dbase, DIRLAYOUT) fn_data = osp.join(dbase, DATAPARAM) fn_anal = osp.join(dbase, ANALPARAM) with open(fn_layo) as flayo: dlayo = json.load(flayo) with open(fn_data) as fdata: ddata = json.load(fdata) with open(fn_anal) as fanal: danal = json.load(fanal) params = {'layout': dlayo, 'data': ddata, 'analysis': danal} return params def process_all(dbase, params=None, verbose=False): """ parameters: ----------- dbase: string base directory containing subjects directory and jason files """ if not params: params = get_params(dbase, verbose=verbose) dlayo = params['layout'] ddata = params['data'] # loop over subjects subj_idx = range(1,ddata['nb_sub']+1) # starts at 1, hence + 1 subj_dirs = [osp.join(dbase, (dlayo['dir']['sub+']).format(idx)) for idx in subj_idx] # check all subj_dirs exists for sub_dir in subj_dirs: assert osp.isdir(sub_dir), "sub_dir" subjs_info = {} sub_curr = {} for sub_idx, sub_dir in enumerate(subj_dirs, 1): # start idx at 1 sub_curr['sub_idx'] = sub_idx sub_curr['sub_dir'] = sub_dir sub_str = (dlayo['dir']['sub+']).format(sub_idx) subjs_info[sub_str] = do_one_subject(sub_curr, params, verbose=verbose) return subjs_info def do_one_subject(sub_curr, params, verbose=False): """ launch sessions processing for sub_curr parameters: ----------- sub_curr: dict contains subject base directory contains subject index params: dict parameters for layout, data and analysis """ sub_idx, sub_dir = sub_curr['sub_idx'], sub_curr['sub_dir'] nb_sess = params['data']['nb_sess'] dlayo = params['layout'] sess_idx = range(1, nb_sess+1) sess_dirs = [osp.join(sub_dir, (dlayo['dir']['sess+']).format(idx)) for idx in sess_idx] sesss_info = {} sess_curr = {} for sess_idx, sess_dir in enumerate(sess_dirs, 1): # start idx at 1 sess_curr['sess_idx'] = sess_idx sess_curr['sess_dir'] = sess_dir sess_str = (dlayo['dir']['sess+']).format(sub_idx) sesss_info[sess_str] = do_one_sess(sess_curr, sub_curr, params, verbose=verbose) return sesss_info def do_one_sess(sess_curr, sub_curr, params, verbose=False): """ launch runs processing for sess_curr parameters: ----------- sess_curr: dict contains sess base directory contains sess index params: dict parameters for layout, data and analysis """ sess_idx = sess_curr['sess_idx'] sess_dir = sess_curr['sess_dir'] sub_idx = sub_curr['sub_idx'] nb_runs = params['data']['nb_run'] assert nb_runs == 4 # 4debug dlayo = params['layout'] runs_dir = osp.join(sess_dir, dlayo['dir']['runs']) # should be preproc sess_curr['dir_runs'] = runs_dir dir_smooth_imgs = osp.join(runs_dir, dlayo['dir']['smooth']) sess_curr['dir_smooth_imgs'] = dir_smooth_imgs sess_curr['droi'] = osp.join(runs_dir, dlayo['atlas']['dir']) # 'registered_files' sess_curr['roi_prefix'] = dlayo['atlas']['prepat'] # 'rraal_*.nii' sess_curr['dsig'] = osp.join(runs_dir, dlayo['out']['signals']['dir']) save_is_true = params['analysis']['write_signals'] if save_is_true: # rm existing and recreate signal directory suf.rm_and_create(sess_curr['dsig']) sess_curr['dreal'] = osp.join(runs_dir, dlayo['dir']['realign']) #- csf dir and file sess_curr['csf_dir'] = osp.join(runs_dir, dlayo['csf']['dir']) csf_file = gb.glob(osp.join(sess_curr['csf_dir'], dlayo['csf']['roi_mask'])) csf_file = suf._check_glob_res(csf_file, ensure=1, files_only=True) sess_curr['csf_filename'] = csf_file #- csf dir and file sess_curr['wm_dir'] = osp.join(runs_dir, dlayo['wm']['dir']) wm_file = gb.glob(osp.join(sess_curr['wm_dir'], dlayo['wm']['roi_mask'])) wm_file = suf._check_glob_res(wm_file, ensure=1, files_only=True) sess_curr['wm_filename'] = wm_file #- Get runs' filenames #------------------------ pat_imgs_files = dlayo['pat']['sub+sess+run+']+"*.nii*" # requires idx for sub, sess and run runs_pat = [pat_imgs_files.format(sub_idx, sess_idx, run_idx) \ for run_idx in range(1, nb_runs+1)] # /!\ start idx at 1 requires nb_runs+1 /!\ runs = [gb.glob(osp.join(dir_smooth_imgs, pat)) for pat in runs_pat] # /!\ATTENTION:/!\ must sort the files with filename, should sort in time for run in runs: run.sort() sess_curr['runs'] = runs # compute session wide mask #----------------------------------------------------- # compute_epi_mask(runs[0], opening=1, connected=True) if params['analysis']['apply_sess_mask']: sess_mask = msk.compute_multi_epi_mask(runs, lower_cutoff=0.2, upper_cutoff=0.85, connected=True, opening=2, threshold=0.5) # store sess mask dir_mask = osp.join(runs_dir, dlayo['out']['sess_mask']['dir']) suf.rm_and_create(dir_mask) sess_mask.to_filename(osp.join(dir_mask, dlayo['out']['sess_mask']['roi_mask'])) else: sess_mask = None sess_curr['mask'] = sess_mask # TODO # check mask is reasonable - how ??? # - mvt file # example : mvtfile = osp.join(dreal,'rp_asub01_sess01_run01-0006.txt') # /!\ will always be run01 for spm /!\ mvtpat = dlayo['spm_mvt']['mvtrun1+'].format(sub_idx, sess_idx) mvtfile = gb.glob(osp.join(sess_curr['dreal'], mvtpat)) mvtfile = suf._check_glob_res(mvtfile, ensure=1, files_only=True) sess_curr['mvtfile'] = mvtfile # - parameter file for condition names param_pattern = (dlayo['pat']['sub+sess+']).format(sub_idx, sess_idx) paramfile = gb.glob(osp.join(sess_dir, param_pattern + "params")) paramfile = suf._check_glob_res(paramfile, ensure=1, files_only=True) with open(paramfile) as fparam: sess_param = json.load(fparam) runs_info = {} run_curr = {} for idx_run, run in enumerate(runs, 1): # /!\ starts at 1 /!\ run_curr['run_idx'] = idx_run run_curr['file_names'] = run # TODO : fix this to have sess_param return motion['run1']='HIGH' etc run_curr['motion'] = sess_param['motion'][idx_run-1] # sess_param['motion'] is 0 based runs_info["run{:02d}".format(idx_run)] = \ do_one_run(run_curr, sess_curr, sub_curr, params, verbose=verbose) return runs_info def do_one_run(run_curr, sess_curr, sub_curr, params, verbose=False): """ """ run_info = {} nvol = params['data']['nb_vol'] dt = params['data']['TR'] nb_run = params['data']['nb_run'] file_names = run_curr['file_names'] run_idx = run_curr['run_idx'] run_idx0 = run_idx - 1 assert run_idx0 >= 0 assert run_idx0 < nb_run #sub_idx = sub_curr['sub_idx'] #sess_idx = sess_curr['sess_idx'] mvt_cond = run_curr['motion'] dsig = sess_curr['dsig'] mask = sess_curr['mask'] low_freq = params['analysis']['filter']['low_freq'] high_freq = params['analysis']['filter']['high_freq'] # signal file names #------------------- _fn_sig = params['layout']['out']['signals']['signals+'] _fn_fsig = params['layout']['out']['signals']['f_signals+'] fn_sig = osp.join(dsig, _fn_sig.format(run_idx) + mvt_cond) fn_fsig = osp.join(dsig, _fn_fsig.format(run_idx)+mvt_cond) # extract signals and save them in preproc/roi_signals #----------------------------------------------------- run_4d = concat_niimgs(file_names, ensure_ndim=4) signals, _issues, _info = ucr.extract_signals(sess_curr['droi'], sess_curr['roi_prefix'], run_4d, mask=mask, minvox=1) # construct matrix of counfounds #----------------------------------------------------- #--- get WM #--- get CSF csf_arr, csf_labs = ucr.extract_roi_run( sess_curr['csf_dir'], sess_curr['csf_filename'], run_4d, check_lengh=nvol, verbose=verbose) #--- get MVT mvt_arr, mvt_labs = ucr.extract_mvt(sess_curr['mvtfile'], run_idx0, nvol, verbose=verbose) #--- get cosine functions; bf_arr, bf_labs = ucr.extract_bf(low_freq, high_freq, nvol, dt, verbose=verbose) #--- put it together arr_counf = np.hstack((csf_arr, mvt_arr, bf_arr)) labs_counf = csf_labs + mvt_labs + bf_labs if verbose: print("csf.shape {}, mvt.shape {}, bf.shape {}".format( csf_arr.shape, mvt_arr.shape, bf_arr.shape)) run_info['shapes'] = (csf_arr.shape, mvt_arr.shape, bf_arr.shape) run_info['mean_csf'] = csf_arr.mean(axis=0) run_info['mean_mvt'] = mvt_arr.mean(axis=0) # filter and compute correlation #----------------------------------------------------- arr_sig, labels_sig = ucr._dict_signals_to_arr(signals) arr_sig_f = ucr.R_proj(arr_counf, arr_sig) # save filtered signals save_is_true = params['analysis']['write_signals'] if save_is_true: np.savez(fn_sig, arr_sig=arr_sig, labels_sig=labels_sig) np.savez(fn_fsig, arr_sig_f=arr_sig_f, labels_sig=labels_sig, arr_counf=arr_counf, labs_counf=labs_counf) else: run_info['signals'] = dict(arr_sig=arr_sig, labels_sig=labels_sig, issues=_issues, info=_info) run_info['f_signals'] = dict(arr_sig_f=arr_sig_f, labels_sig=labels_sig, arr_counf=arr_counf, labs_counf=labs_counf) return run_info dbase = '/home/jb/data/simpace/data/rename_files' get_params(dbase, verbose=False) params['analysis']['write_signals'] = False params['analysis']['apply_sess_mask'] = False print(params.keys()) print(params['layout']) print(params['analysis']) params['analysis']['write_signals'] = False subjs_info = process_all(dbase, params=params, verbose=False) print(subjs_info['sub01']['sess01']['run01']['signals'].keys()) signals_dict = subjs_info['sub01']['sess01']['run01']['signals'] print(type(signals_dict['labels_sig'])) print(type(signals_dict['arr_sig'])) labs_sig = subjs_info['sub01']['sess01']['run01']['f_signals']['labels_sig'] info_sig = subjs_info['sub01']['sess01']['run01']['signals']['info'] arr_sig = subjs_info['sub01']['sess01']['run01']['signals']['arr_sig'] dtest = '/home/jb/code/simpace/simpace/tests' mat_file = osp.join(dtest, "sub01_session_1_raw_ROI_timeseries.mat") import scipy.io as sio from numpy.testing import assert_allclose, assert_array_equal to_check = sio.loadmat(mat_file) to_check.keys() to_check['all_rois'][1][0][0] to_check['time_series'][0][0] to_check['Nvox'][0] nvox = to_check['Nvox'][0] for idx, roi in enumerate(to_check['all_rois'][:10]): k, _ = osp.splitext(osp.basename(roi[0][0])) in_sig = k in labs_sig print(k, in_sig) if in_sig: print(nvox[idx], info_sig[k]) [(k,info_sig[k]) for k in sorted(info_sig.keys())][-5:] arielle_roi = [] [osp.splitext(osp.basename(roi[0][0])) for roi in to_check['all_rois']][-8:] nvox = to_check['Nvox'][0] arrielle_nvox = [nvox[idx] for idx in range(len(nvox)) if nvox[idx] != 0] jb_nvox = np.asarray([info_sig[k] for k in sorted(info_sig.keys())]) assert_array_equal(np.asarray(arrielle_nvox)[:-2], np.asarray(jb_nvox)) ```
github_jupyter
# Working with JavaScript and TypeScript * **Difficulty level**: easy * **Time need to lean**: 10 minutes or less * SoS replies on JSON format to convert between complex data types to and from JavaScript ## JavaScript <a id="JavaScript"></a> SoS exchange data with a JavaScript kernel using JSON format. It passes all JSON serializable datatypes using the [`json` module](https://docs.python.org/3.6/library/json.html), and convert numpy arrays to list before translation (`array.tolist()`), and use [DataFrame.to_jason](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_json.html) to translate Pandas DataFrame to a list of records in JS. | Python | condition | JavaScript | | --- | --- |---| | `None` | | `null` | | `boolean`, `int`, `str`, etc | | corresponding JS type | | `numpy.ndarray` | |array | | `numpy.matrix` | | nested array | | `pandas.DataFrame` | | table with scheme and array of records (dictionary) | Translation from JavaScript to Python is easier because Python supports all JSON serializable JS datatypes. The DataFrame translation is particularly interesting because it allows you to pass complex datatypes in Python and R for visualization. For example, for the following data.frame in R, ``` mtcars ``` It appears in SoS as a pandas DataFrame ``` %get mtcars --from R mtcars ``` we can get the data from the JS script kernel as follows: ``` %get mtcars --from R mtcars['Mazda RX4'] ``` ## TypeScript <a id="TypeScript"></a> SoS exchange data with a JypeScript kernel using JSON format. It passes all JSON serializable datatypes using the [`json` module](https://docs.python.org/3.6/library/json.html), and convert numpy arrays to list before translation (`array.tolist()`), and use [DataFrame.to_jason](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_json.html) to translate Pandas DataFrame to a list of records in JS. | Python | condition | TypeScript | | --- | --- |---| | `None` | | `null` | | `boolean`, `int`, `str`, etc | | corresponding JS type | | `numpy.ndarray` | |array | | `numpy.matrix` | | nested array | | `pandas.DataFrame` | | table with scheme and array of records (dictionary) | Translation from TypeScript to Python is easier because Python supports all JSON serializable TS datatypes. The DataFrame translation is particularly interesting because it allows you to pass complex datatypes in Python and R for visualization. For example, for the following data.frame in R, ``` mtcars ``` we can get the data from the TS script kernel as follows: ``` %get mtcars --from R mtcars['Mazda RX4'] ```
github_jupyter
``` %load_ext autoreload %autoreload 2 """Main training script for Cascaded Nets.""" import argparse import glob import matplotlib.pyplot as plt import numpy as np import os import pandas as pd import seaborn as sns import sys import torch from collections import defaultdict from datasets.dataset_handler import DataHandler from matplotlib.lines import Line2D from modules import utils from scipy import interpolate ``` ## Setup Args ``` def setup_args(): parser = argparse.ArgumentParser() parser.add_argument("--random_seed", type=int, default=42, help="random seed") # Paths parser.add_argument("--experiment_root", type=str, default='experiments', help="Local output dir") # parser.add_argument("--experiment_name", type=str, # required=True, # help="Experiment name") # Dataset # parser.add_argument("--dataset_root", type=str, required=True, # help="Dataset root") # parser.add_argument("--dataset_name", type=str, required=True, # help="Dataset name: CIFAR10, CIFAR100, TinyImageNet") parser.add_argument("--split_idxs_root", type=str, default='split_idxs', help="Split idxs root") parser.add_argument("--val_split", type=float, default=0.1, help="Validation set split: 0.1 default") parser.add_argument("--augmentation_noise_type", type=str, default='occlusion', help="Augmentation noise type: occlusion") parser.add_argument("--batch_size", type=int, default=128, help="batch_size") parser.add_argument("--num_workers", type=int, default=2, help="num_workers") parser.add_argument('--drop_last', action='store_true', default=False, help='Drop last batch remainder') # Model parser.add_argument("--model_key", type=str, default='resnet18', help="Model: resnet18, resnet34, ..., densenet_cifar") parser.add_argument("--train_mode", type=str, default='baseline', help="Train mode: baseline, ic_only, sdn") parser.add_argument('--bn_time_affine', action='store_true', default=False, help='Use temporal affine transforms in BatchNorm') parser.add_argument('--bn_time_stats', action='store_true', default=False, help='Use temporal stats in BatchNorm') parser.add_argument("--tdl_mode", type=str, default='OSD', help="TDL mode: OSD, EWS, noise") parser.add_argument("--tdl_alpha", type=float, default=0.0, help="TDL alpha for EWS temporal kernel") parser.add_argument("--noise_var", type=float, default=0.0, help="Noise variance on noise temporal kernel") parser.add_argument("--lambda_val", type=float, default=1.0, help="TD lambda value") parser.add_argument('--cascaded', action='store_true', default=False, help='Cascaded net') parser.add_argument("--cascaded_scheme", type=str, default='parallel', help="cascaded_scheme: serial, parallel") parser.add_argument("--init_tau", type=float, default=0.01, help="Initial tau valu") parser.add_argument("--target_IC_inference_costs", nargs="+", type=float, default=[0.15, 0.30, 0.45, 0.60, 0.75, 0.90], help="target_IC_inference_costs") parser.add_argument('--tau_weighted_loss', action='store_true', default=False, help='Use tau weights on IC losses') # Optimizer parser.add_argument("--learning_rate", type=float, default=0.1, help="learning rate") parser.add_argument("--momentum", type=float, default=0.9, help="momentum") parser.add_argument("--weight_decay", type=float, default=0.0005, help="weight_decay") parser.add_argument('--nesterov', action='store_true', default=False, help='Nesterov for SGD') parser.add_argument('--normalize_loss', action='store_true', default=False, help='Normalize temporal loss') # LR scheduler parser.add_argument("--lr_milestones", nargs="+", type=float, default=[60, 120, 150], help="lr_milestones") parser.add_argument("--lr_schedule_gamma", type=float, default=0.2, help="lr_schedule_gamma") # Other parser.add_argument('--use_cpu', action='store_true', default=False, help='Use cpu') parser.add_argument("--device", type=int, default=0, help="GPU device num") parser.add_argument("--n_epochs", type=int, default=150, help="Number of epochs to train") parser.add_argument("--eval_freq", type=int, default=10, help="eval_freq") parser.add_argument("--save_freq", type=int, default=5, help="save_freq") parser.add_argument('--keep_logits', action='store_true', default=False, help='Keep logits') parser.add_argument('--debug', action='store_true', default=False, help='Debug mode') args = parser.parse_args("") # Flag check if args.tdl_mode == 'EWS': assert args.tdl_alpha is not None, 'tdl_alpha not set' elif args.tdl_mode == 'noise': assert args.noise_var is not None, 'noise_var not set' return args args = setup_args() ``` ## Override Args ``` args.dataset_root = '/hdd/mliuzzolino/datasets' args.experiment_root = '/home/mliuzzolino/experiment_output' # Set required flags| args.dataset_name = 'ImageNet2012' # CIFAR10, CIFAR100, ImageNet2012 args.model_key = 'resnet18' args.dataset_key = 'test' # val, test if args.dataset_name == "ImageNet2012": args.experiment_name = f"{args.model_key}_{args.dataset_name}" elif "cifar" in args.dataset_name.lower(): args.experiment_name = f"{args.model_key}_{args.dataset_name.lower()}" else: print("TinyImageNet not implemented yet!") args.val_split = 0.1 args.test_split = 0.1 args.split_idxs_root = "/hdd/mliuzzolino/split_idxs" args.tdl_mode = 'OSD' # OSD, EWS args.tau_weighted_loss = True args.random_seed = 42 # Make reproducible utils.make_reproducible(args.random_seed) ``` ## Setup Figs Dir ``` figs_root = 'figs' if not os.path.exists(figs_root): os.makedirs(figs_root) fig_path = os.path.join(figs_root, f'{args.dataset_name}.pdf') fig_path ``` ## Model Label Lookup ``` MODEL_LBL_LOOKUP = { "cascaded__serial": "SerialTD", "cascaded__parallel": "CascadedTD", "cascaded__serial__multiple_fcs": "SerialTD-MultiHead", # (SDN) "cascaded__parallel__multiple_fcs": "CascadedTD-MultiHead", "cascaded_seq__serial": "SerialCE", "cascaded_seq__parallel": "CascadedCE", } ``` ## Colors ``` colors_src = { "CascadedTDColor": np.array([182,54,121]) / 255.0, # CascadedTDColor, "CascadedCEColor": np.array([127,38,110]) / 255.0, # CascadedCEColor, "SerialTDColor": np.array([77,184,255]) / 255.0, # SerialTDColor, "SerialCEColor": np.array([54,129,179]) / 255.0, # SerialCEColor, } model_colors = { "cascaded__serial": colors_src["SerialTDColor"], "cascaded__parallel": colors_src["CascadedTDColor"], "cascaded__serial__multiple_fcs": colors_src["SerialTDColor"], # (SDN) "cascaded__parallel__multiple_fcs": colors_src["CascadedTDColor"], "cascaded_seq__serial": colors_src["SerialCEColor"], "cascaded_seq__parallel": colors_src["CascadedCEColor"], } ``` ## Setup Data Handler ``` # Data Handler data_dict = { "dataset_name": args.dataset_name, "data_root": args.dataset_root, "val_split": args.val_split, "test_split": args.test_split, "split_idxs_root": args.split_idxs_root, "noise_type": args.augmentation_noise_type, "load_previous_splits": True, "imagenet_params": { "target_classes": ["terrier"], "max_classes": 10, } } data_handler = DataHandler(**data_dict) # Set Loaders test_loader = data_handler.build_loader(args.dataset_key, args) ``` ## Load Experiment Data ``` # Set experiment root exp_root = os.path.join(args.experiment_root, args.experiment_name, 'experiments') exp_root = f"/hdd/mliuzzolino/cascaded_nets/{args.experiment_name}/experiments" # Find exp paths exp_paths = np.sort(glob.glob(f'{exp_root}/*/outputs/*__{args.dataset_key}__{args.tdl_mode}.pt')) print(f"Num paths: {len(exp_paths)}") ``` #### Build Dataframe ``` df_dict = defaultdict(list) outrep_id = 0 outreps_dict = {} ic_costs_lookup = {} exp_path_lookup = {} for i, exp_path in enumerate(exp_paths): outrep_id = f'rep_id_{i}' outrep = torch.load(exp_path) basename = [ele for ele in exp_path.split(os.path.sep) if 'seed_' in ele][0] keys = basename.split(',') if keys[0].startswith('std') or keys[0].startswith('cascaded_seq'): model_key, lr, weight_decay, seed = keys td_key = 'std' else: td_key, scheme_key, lr, weight_decay, seed = keys[:5] model_key = f'cascaded__{scheme_key}' other_keys = keys[5:] multiple_fcs = 'multiple_fcs' in other_keys tau_weighted = 'tau_weighted' in other_keys pretrained_weights = 'pretrained_weights' in other_keys if multiple_fcs: model_key = f'{model_key}__multiple_fcs' if tau_weighted: model_key = f'{model_key}__tau_weighted' if pretrained_weights: model_key = f'{model_key}__pretrained_weights' if model_key != 'std': exp_root = os.path.dirname(os.path.dirname(exp_path)) IC_cost_path = os.path.join(exp_root, 'ic_costs.pt') if os.path.exists(IC_cost_path): IC_costs = torch.load(IC_cost_path) else: IC_costs = None else: IC_costs = None lr = float(lr.split("_")[1]) weight_decay = float(weight_decay.split("_")[1]) df_dict['model'].append(model_key) df_dict['td_lambda'].append(td_key) df_dict['lr'].append(lr) df_dict['weight_decay'].append(weight_decay) df_dict['seed'].append(seed) df_dict['outrep_id'].append(outrep_id) outreps_dict[outrep_id] = outrep ic_costs_lookup[outrep_id] = IC_costs exp_path_lookup[outrep_id] = exp_path analysis_df = pd.DataFrame(df_dict) ``` ## Build Aggregate Stats ``` df_dict = defaultdict(list) analysis_df = analysis_df.sort_values('model') for i, df_i in analysis_df.iterrows(): outrep_i = outreps_dict[df_i.outrep_id] accs = outrep_i['correct'].float().mean(dim=1) for i, acc in enumerate(accs): df_dict['acc'].append(acc.item() * 100) if len(accs) == 1: i = -1 df_dict['ic'].append(i) for k in list(df_i.index): df_dict[k].append(df_i[k]) accs_df = pd.DataFrame(df_dict) accs_df = accs_df.sort_values(['outrep_id', 'ic']) df_dict = defaultdict(list) for model_key, model_df in accs_df.groupby('model'): for td_lambda, lambda_df in model_df.groupby('td_lambda'): for ic, ic_df in lambda_df.groupby('ic'): mean_acc = np.mean(ic_df.acc) sem_acc = np.std(ic_df.acc) / np.sqrt(len(ic_df.acc)) outrep_id = ic_df.outrep_id.iloc[0] df_dict['model'].append(model_key) df_dict['td_lambda'].append(td_lambda) df_dict['ic'].append(ic) df_dict['acc'].append(mean_acc) df_dict['sem'].append(sem_acc) df_dict['outrep_id'].append(outrep_id) flops = ic_costs_lookup[outrep_id] if flops is not None: try: flops = flops['flops'][ic] except: flops = 1.0 df_dict['flops'].append(flops) stats_df = pd.DataFrame(df_dict) stats_df.loc[stats_df.ic==-1, 'ic'] = np.max(stats_df.ic) stats_df.ic = [ele+1 for ele in stats_df.ic] ``` ## Accuracy vs. TD($\lambda$) Curves ``` color = np.array([182,54,121]) / 255.0 AXIS_LBL_FONTSIZE = 16 LEGEND_FONTSIZE = 16 TICK_FONTSIZE = 14 FIGSIZE = (8,4) # (12,5) plt.figure(figsize=FIGSIZE) g = sns.lineplot( x="td_lambda", y="acc", data=model_df, lw=6, color=color, ) g = sns.scatterplot( x="td_lambda", y="acc", data=model_df, s=100, color=color, ) g.set_xticks(model_df.td_lambda.unique()) g.set_xlabel(r"$\lambda$", fontsize=AXIS_LBL_FONTSIZE) g.set_ylabel("Accuracy (%)", fontsize=AXIS_LBL_FONTSIZE) g.tick_params(axis='x', labelsize=TICK_FONTSIZE) g.tick_params(axis='y', labelsize=TICK_FONTSIZE) save_path = os.path.join("figs", f"{args.dataset_name}__td_curves.pdf") plt.savefig(save_path, dpi=300) plt.savefig(save_path.replace(".pdf", ".png"), dpi=300) ``` # Compute Speed Accuracy Tradeoff ``` def compute_threshold_conf_correct(pred_conf, correct, q): correct_arr = [] best_clf_idxs = [] n_clfs = pred_conf.shape[0] n_samples = pred_conf.shape[1] for i in range(n_samples): pred_conf_i = pred_conf[:,i] idxs = np.where(pred_conf_i >= q)[0] if not len(idxs): best_clf_idx = n_clfs - 1 cor_i = correct[best_clf_idx,i] else: best_clf_idx = idxs[0] cor_i = correct[best_clf_idx,i] correct_arr.append(cor_i) best_clf_idxs.append(best_clf_idx) avg_acc = np.mean(correct_arr) return avg_acc, best_clf_idxs df_dict = defaultdict(list) for model_key, model_df in analysis_df.groupby('model'): if model_key == 'cascaded_seq__serial': delta = 100 else: delta = 100 Qs = np.linspace(0, 1, delta) if model_key in ['std']: continue print(f"\nModel: {model_key}") for td_lambda, td_df in model_df.groupby('td_lambda'): for jj, df_i in td_df.iterrows(): outrep_id = df_i.outrep_id outrep_i = outreps_dict[outrep_id] try: flop_costs = ic_costs_lookup[outrep_id]['flops'] except: for k, v in ic_costs_lookup.items(): if v is not None: flop_costs = v['flops'] break f_interpolate = interpolate.interp1d(range(len(flop_costs)), flop_costs, bounds_error=False) prediction_confidence = outrep_i['prediction_confidence'] correct_vals = outrep_i['correct'] accs = [] flops = [] for qi, q in enumerate(Qs): sys.stdout.write((f'\rTD_lambda: {td_lambda} -- ' f'df_{jj} [{jj+1}/{len(td_df)}] -- ' f'Threshold, q: {q:0.2f} [{qi+1}/{len(Qs)}]')) sys.stdout.flush() acc_i, best_clf_idxs = compute_threshold_conf_correct(prediction_confidence, correct_vals, q) avg_timesteps = np.mean(best_clf_idxs) avg_flop = f_interpolate(avg_timesteps) flops.append(avg_flop) df_dict['model'].append(model_key) df_dict['td_lambda'].append(td_lambda) df_dict['seed'].append(df_i.seed) df_dict['acc'].append(acc_i * 100) df_dict['flops'].append(avg_flop) df_dict['timesteps'].append(avg_timesteps) df_dict['q'].append(q) print("\n") speed_acc_data_df = pd.DataFrame(df_dict) ``` ### Agg Stats ``` def fix_df(df_src, fix_key='cascaded_seq__serial'): df_src = df_src.copy() df = df_src[df_src.model==fix_key] df = df.sort_values('timestep_mean') prev_j = None for i, j in df.iterrows(): if j.timestep_mean != 0.0: break prev_j = j for t in np.linspace(prev_j.timestep_mean, j.timestep_mean, 10)[:-1]: new_j = prev_j.copy() new_j.timestep_mean = t new_j.timestep_mean = t df = df.append(new_j, ignore_index=True) df = df.sort_values('timestep_mean') df_src.drop(df_src[df_src.model==fix_key].index, inplace=True) df_src = pd.concat([df_src, df]) return df_src single_seed = None df_dict = defaultdict(list) for model_key, model_df in speed_acc_data_df.groupby('model'): for td_lambda, td_df in model_df.groupby('td_lambda'): for q, q_df in td_df.groupby('q'): if single_seed is not None: q_df = q_df[q_df.seed.str.contains(f"_{single_seed}")] acc_mean = np.mean(q_df.acc) n = len(q_df) acc_sem = np.std(q_df.acc) / np.sqrt(n) timestep_mean = np.mean(q_df.timesteps) timestep_sem = np.std(q_df.timesteps) / np.sqrt(n) df_dict['model'].append(model_key) df_dict['q'].append(q) df_dict['acc_mean'].append(acc_mean) df_dict['acc_sem'].append(acc_sem) df_dict['timestep_mean'].append(timestep_mean) df_dict['timestep_sem'].append(timestep_sem) df_dict['td_lambda'].append(td_lambda) df_dict['n'].append(n) q_stat_df = pd.DataFrame(df_dict) try: q_stat_df = fix_df(q_stat_df, 'cascaded_seq__serial') except: print("Exception!") ``` ## Speed Accuracy Tradeoff Curves ``` def compute_best_lambdas(stats_df, sdn_TD1=True): best_lambdas = {} for model_key, model_df in stats_df.groupby('model'): model_df = model_df[model_df.ic==model_df.ic.max()] model_df = model_df[model_df.acc==model_df.acc.max()] best_lambda = model_df.iloc[0].td_lambda if sdn_TD1: if 'cascaded__serial' in model_key: best_lambdas[model_key] = 'td(1.0)' elif 'cascaded__parallel' in model_key: best_lambdas[model_key] = 'td(0.0)' else: best_lambdas[model_key] = best_lambda else: best_lambdas[model_key] = best_lambda return best_lambdas def fix_legend_order(handles, labels): order = [ 'CascadedTD', 'CascadedTD-MultiHead', 'CascadedCE', 'SerialTD', 'SerialTD-MultiHead', 'SerialCE', ] idxs = [] for key in order: if key in labels: idx = labels.index(key) idxs.append(idx) handles = list(np.array(handles)[idxs]) labels = list(np.array(labels)[idxs]) return handles, labels SHOW_EBARS = True LINEWIDTH = 3 AXIS_LBL_FONTSIZE = 16 LEGEND_FONTSIZE = 16 TICK_FONTSIZE = 14 fig = plt.figure(figsize=(8,6)) # Compute best lambdas best_lambdas = compute_best_lambdas(stats_df) y_dfs = [] for model_key, model_df in q_stat_df.groupby('model'): best_lambda = best_lambdas[model_key] model_df = model_df[model_df.td_lambda==best_lambda] y_dfs.append(model_df) q_stat_df_fixed = pd.concat(y_dfs) max_flop = np.max(q_stat_df_fixed.timestep_mean) for i, (model_key, model_df) in enumerate(q_stat_df_fixed.groupby('model')): linestyle = '--' if 'multiple_fcs' in model_key else '-' if 'cascaded_seq' in model_key: linestyle = 'dotted' try: color_i = model_colors[model_key] except: color_i = model_colors["cascaded__parallel__multiple_fcs"] timestep_vals = np.array(list(model_df.timestep_mean)) sorted_idxs = np.argsort(timestep_vals) timestep_vals = timestep_vals[sorted_idxs] acc_vals = np.array(list(model_df.acc_mean))[sorted_idxs] sem_error = np.array(list(model_df.acc_sem))[sorted_idxs] td_lambda_lbl = model_df.iloc[0].td_lambda.replace('td(', 'TD(') try: label = MODEL_LBL_LOOKUP[model_key] except: label = "cascaded__scheme_1__multiple_fcs" plt.plot(timestep_vals, acc_vals, label=label, linewidth=LINEWIDTH, c=color_i, linestyle=linestyle) if SHOW_EBARS: lower_b = np.array(acc_vals) - np.array(sem_error) upper_b = np.array(acc_vals) + np.array(sem_error) plt.fill_between(timestep_vals, lower_b, upper_b, alpha=0.075, color=color_i) plt.xlabel('Timesteps', fontsize=AXIS_LBL_FONTSIZE) plt.ylabel('Accuracy (%)', fontsize=AXIS_LBL_FONTSIZE) ax = plt.gca() ax.tick_params(axis='both', which='major', labelsize=TICK_FONTSIZE) handles, labels = ax.get_legend_handles_labels() handles, labels = fix_legend_order(handles, labels) ax.legend(handles=handles, labels=labels) final_fig_path = fig_path if 'metacog_df' in globals() and _SHOW_METACOG: final_fig_path = final_fig_path.replace('.pdf', '_with_metacog.pdf') metacog_df = metacog_df.sort_values('mean_time') metacog_time = metacog_df.mean_time metacog_acc = metacog_df.mean_correct * 100 metacog_color = np.array((255, 148, 77)) / 255. metacog_ls = (0, (3, 1, 1, 1)) plt.plot(metacog_time, metacog_acc, linewidth=LINEWIDTH, color=metacog_color, linestyle=metacog_ls) metacog_patch = Line2D([0], [0], color=metacog_color, lw=LINEWIDTH, linestyle=metacog_ls, label='MetaCog GRU-RNN') handles += [metacog_patch] legend = ax.legend(handles=handles, frameon=False, loc='center left', bbox_to_anchor=(1., 0.5), prop={'size': LEGEND_FONTSIZE}) fig.subplots_adjust(right=0.9) plt.savefig(final_fig_path, dpi=300, bbox_inches='tight') plt.savefig(final_fig_path.replace('pdf', 'png'), dpi=300, bbox_inches='tight') ``` ### Print Stats ``` for i, (model_key, model_df) in enumerate(q_stat_df_fixed.groupby('model')): label = MODEL_LBL_LOOKUP[model_key] final_df = model_df[model_df.timestep_mean==model_df.timestep_mean.max()].iloc[0] acc = final_df.acc_mean sem = final_df.acc_sem print(f"{label}: {acc:0.2f}% +/- {sem:0.2f} (n={final_df.n})") xp = list(model_df.acc_mean) fp = list(model_df.timestep_mean) t_for_50_perc = np.interp(50, xp, fp) print(f"{label}: 50% accuracy @ timestep {t_for_50_perc:0.2f}") print("\n") ```
github_jupyter
``` # text_clustering based on CURE import glob import os import shutil import matplotlib.pyplot as plt from pyclustering.cluster import cluster_visualizer from pyclustering.cluster.cure import cure from pyclustering.utils import read_sample from pyclustering.utils import timedcall from pyspark.sql import SparkSession from pyspark.sql.functions import split, explode from sklearn.datasets import load_files from sklearn.decomposition import PCA from sklearn.feature_extraction.text import TfidfVectorizer spark = SparkSession.builder.appName("Python Spark CURE Clustering").getOrCreate() def get_cluster_datapoints(file, number_clusters, number_represent_points, compression, ccore_flag): sample = read_sample(file) cure_instance = cure(sample, number_clusters, number_represent_points, compression, ccore_flag) (ticks, _) = timedcall(cure_instance.process) clusters = cure_instance.get_clusters() representors = cure_instance.get_representors() means = cure_instance.get_means() return sample, clusters, representors, means, ticks def template_clustering(number_clusters, path, number_represent_points=10, compression=0.5, draw=True, ccore_flag=True, counter=0): cluster_files = glob.glob(path + "/*.csv") for c_file in cluster_files: sample, clusters, representors, means, ticks = get_cluster_datapoints(c_file, number_clusters, number_represent_points, compression, ccore_flag) final = open('final_cluster.txt', 'a+') final.write(str(representors).replace('], ', '\n').replace('[', '').replace(']', '').replace(',', '') + '\n') final.close() if counter % 1 == 0: number_clusters = 7 number_represent_points = 10 sample, clusters, representors, means, ticks = get_cluster_datapoints('final_cluster.txt', number_clusters, number_represent_points, compression, ccore_flag) final = open('final_cluster.txt', 'w+') final.write(str(representors).replace('], ', '\n').replace('[', '').replace(']', '').replace(',', '') + '\n') print("Cluster Dir: ", path, "\t\tExecution time: ", ticks, "\n") if draw is True: visualizer = cluster_visualizer() visualizer.append_clusters(clusters, sample) for cluster_index in range(len(clusters)): visualizer.append_cluster_attribute(0, cluster_index, representors[cluster_index], '*', 10) visualizer.append_cluster_attribute(0, cluster_index, [means[cluster_index]], 'o') # visualizer.save('fig' + str(counter) + '.png') visualizer.show() plt.close() if __name__ == '__main__': files = glob.glob("csv_data/*.csv") counter = 0 for file in files: filepath = file.split('.')[0] + '/' print('processing: ' + filepath) df = spark.read.format("com.databricks.spark.csv").option("header", "true").option("delimiter", ",").option("inferSchema", "true").load(file) df = df.na.drop(subset=["pub_types", "article_title"]) categories = [i.pub_types for i in df.select('pub_types').distinct().collect()] for cat in categories: path = filepath + cat df_temp = df.filter(df.pub_types == cat) df_temp.select('article_title').write.option('maxRecordsPerFile', 20000).csv(path) random_state = 0 data = load_files(filepath, encoding="utf-8", decode_error="replace", random_state=random_state) data_target = [x.item() for x in data['target']] df = spark.createDataFrame(zip(data['data'], data_target), schema=['text', 'label']) df = df.withColumn('text', explode(split('text', '\n'))) vec = TfidfVectorizer(stop_words="english") txt_values = [i.text for i in df.select('text').collect()] df = None vec.fit(txt_values) features = vec.transform(txt_values) pca = PCA(n_components=2) reduced_features = pca.fit_transform(features.toarray()) dd = spark.createDataFrame(zip([x.item() for x in reduced_features[:, 0]], [x.item() for x in reduced_features[:, 1]]), schema=['x', 'y']) dd.write.option('maxRecordsPerFile', 30000).option("delimiter", " ").csv('cluster') dd = None counter += 1 print('') template_clustering(7, 'cluster', 5, 0.5, counter=counter) isExist = os.path.exists('cluster') if isExist: shutil.rmtree('cluster') ```
github_jupyter
# CNN for leave-one-out training splits, time and circadian estimates included We generated the PSG, time, and spectrogram data pickles using [this ETL/feature extraction script](https://github.com/ericcanton/sleep_classifiers_accel_ML/blob/master/source/etl.py). Our data loading, training, and evaluation scheme is described below. If you want to dive into using the code, skip to "Preamble". To get the data, you can add following folder to your Google Drive from Eric Canton's Google Drive. * https://drive.google.com/drive/folders/1pYoXsFHhK1X3qXIOCiTrnoWKG6MTNucy?usp=sharing This should have two folders: pickles and neural. 1. For now, neural is empty. Trained neural networks appear here with naming format like "123_trained_cnn.h5" for subject number 123. 2. pickles contains one folder per subject. We recommend leaving out 7749105 because only about an hour of data is recorded for them (watch failure) by setting <code>exclude = ['7749105']</code> to <code>data_yielder</code> in the Training section's for loops and the function calls in the Evaluation section; this is the case at time of sharing. ## 0. Processed Data loading, model training, and evaluation scheme ### 0.1 Evaluation and split generation functions Basically, these "data pickles" are saved numpy arrays containing our data points stored along axis 0. To easily generate leave-one-out train/test splits, we have divided the data into separate folders for each subject in the study. in <code>evaluators.py</code> we have defined two generators, * <code>data_yielder</code> whose <code>next()</code> method returns a tuple that depends on the <code>nn</code> parameter of this Yielder. If <code>nn=True</code> (the default) when called, the tuple is <code>(spectrogram[i], time[i], psg labels[i], neural network[i]) </code> enumerated according with the order returned by <code>os.walk</code> on the <code>data_path</code> folder. The first three elements are numpy arrays of shape (\*, 65, 73), (\*, 1), (\*, 1); the last is a keras.model trained on the data for all subjects except subject[i]. If <code>nn=False</code> then returns just the first three elements above, <code>(spectrogram[i], time[i], psg labels[i]).</code> This default mode is intended to provide testing splits and neural networks for evaluation. Specifically, the function <code>pr_roc_from_path</code> was written with a <code>data_yielder</code> instance to be passed as the first argument, though it functions perfectly well for any list-like Python object (generally, anything having a <code>next()</code> method will function as well). See the next subsection for an explanation of this function. * <code>split_yielder</code> calls <code>data_yielder</code>, collects all the elements from <code>data_yielder</code>, then yields tuples <code>(subject number excluded, training_split_data, testing_split_data)</code> where the data from subject number <code>subject number excluded</code> is <code>testing_split_data</code> and everyone else's data is stacked into <code>training_split_data</code>. If <code>t</code> is one of these splits, then it is a tuple with elements: * <code>t[0]</code> is the model input data, the structure depending on the <code>with_time</code> parameter. If <code>with_time=True</code> (the default) this is a tuple of length 2: <code>t[0][0]</code> are the spectrograms as a numpy array with shape (*, 65, 73) and <code>t[0][1]</code> are the timestamps, as a numpy array with shape (*,1) or possibly (*,). If <code>with_time=False</code> then <code>t[0]</code> is just the array of spectrograms. * <code>t[1]</code> is the numpy array of PSG labels, having values in <code>[0, 1, 2, 3, 4, 5]</code> with 0 indicating awake and 5 indicating REM. Thus, you likely need to process <code>t[1]</code> more using <code>np.where</code> or <code>np.piecewise</code> to labels you want. For sleep-wake labeling, try <code>psg_sleep_wake = np.where(t[1] > 0, 1, 0)</code> The data pickles being yielded above are stored in the <code>pickles</code> folder inside the Drive folder pointed to by <code>data_path</code>, defined below. The data for subject <code>123</code> is stored in the folder <code>data_path/pickles/123</code>; there you will find three files: 1. <code>psg.pickle</code> 2. <code>spectros.pickle</code> 3. <code>time.pickle</code> ### 0.2 Explanation of the pickles Assume we have loaded these three pickles for subject <code>123</code> into the variables <code>psg, spectros,</code> and <code>time</code>. These are all numpy arrays whose axis-0 lengths are the same. * <code>psg[i]</code> is the PSG label for the time window <code>[30\*i, 30\*(i+1)]</code>. * <code>time[i]</code> is equal to <code>30\*i + 15</code>, the center of this time window, and * <code>spectros'[i]</code> is the spectrogram of derivative of magnitude of acceleration (quite a mouth full...) for times ranging between <code>30\*i + 15 - 46.08</code> and <code>30\*i + 15 + 46.08</code>. The somewhat strange number <code>46.08 = 92.16/2</code> is a consequence of wanting 90 second windows with data sampling rate of 50Hz, but also wanting the number of records in this window (a priori, 90/0.02 = 4500) to be divisble by 128, the number of points per Fourier transform used in the spectrogram creation. So, the shortest time interval over 90 seconds satisfying the additional divisibility requirement is 92.16 seconds, since 4500 = 20 mod 128, or 4608 = 4500 + (128 - 20). ### 0.3 Olivia: Adding circadian predictions *Olivia: you should save the circadian values for each window in this folder, too. Probably easiest to modify <code>etl.py</code> adding a step to load and then save the circadian value in a separate pickle. Or, you could add a column to each time.pickle, giving that array shape (?, 2) instead of (?, 1). I'll indicate in the cell below defining our CNN how to modify things in either case.* ## 1. Preamble ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt from matplotlib.ticker import MultipleLocator from sklearn.metrics import classification_report from sklearn.metrics import roc_curve, auc from sklearn.metrics import precision_recall_curve as pr_curve import tensorflow as tf from tensorflow.keras.layers import concatenate, Conv2D, Dense, Dropout, Flatten, Input, MaxPool2D from tensorflow.keras.models import Model import pickle import glob import sys # See if a GPU is available. # This speeds up training the NNs, with significant gains on the CNN. gpu = tf.test.gpu_device_name() if "GPU" in gpu: print(gpu) else: print("No GPU found!") ``` ### 1.1 Define paths for finding data and support libraries These paths should be from a mounted Google Drive. You should change <code>data_path</code> to point to the directory where your copies of the pickled spectrograms/PSG labels are stored, and ``` data_path = "/content/drive/My Drive/sleep_classifiers_accel_ML/data/" source_path = "/content/drive/My Drive/sleep_classifiers_accel_ML/source/" sys.path.append(source_path) ``` The following library should be stored as <code>source_path + "evaluator.py"<c/code> and is obtainable from <a href="https://github.com/ericcanton/sleep_classifiers_accel_ML/blob/master/source/evaluator.py">Eric's GitHub</a>. ``` import evaluator as ev ``` ## 2. CNN Definitions We define two CNNs, one for sleep/wake classification, the second for staging. These both incorporate time, and can easily be modified to incorporate further inputs. I have detailed how one would do this in model 2.1 immediately below. ### 2.1 CNN for predictiong sleep/wake using time The last layer has 2 neurons because we want to predict 2 classes: * 0 for "awake" * 1 for "asleep" ``` ## # Model input layers # The shape parameters do not include the number of training samples, # which should be the length of axis-0 of the input numpy tensors. ## # Spectrograms. These must be reshaped using .reshape(-1, 65, 73, 1) # from their original shape (-1, 65, 73) to make them appear to be "black and white images" # to the Conv2D layers below. inputs_spectro = Input(shape=(65, 73, 1)) inputs_time = Input(shape=(1,)) ##### ##### # Add more layers here. For example, if we wanted to add # the original x,y,z accleration data (averaged over the time window, e.g.) # then we would add # inputs_accel = Input(shape(3,)) ##### ##### # Convolutional layers. Operate only on spectrograms c_1 = Conv2D(64, kernel_size=3, activation='relu', data_format='channels_last')(inputs_spectro) m_1 = MaxPool2D()(c_1) c_2 = Conv2D(32, kernel_size=3, activation='relu', data_format='channels_last')(m_1) m_2 = MaxPool2D()(c_2) # The output of m_2 is a stream of two-dimensional features # Densely connected layers want one-dimensional features, so we "unwind" # the two-dimensional features using a Flatten layer: # *** # *** # *** # *** ~~~> ***,***,***,*** flat = Flatten(data_format='channels_last')(m_2) # Now append time to the front of this flattened data concat = concatenate([ \ ##### ##### # If you added layers above, include them in the list inside concatenate. # Order shouldn't really matter, just add them below. ##### ##### inputs_time, \ flat]) # Start of densely connected layers d_1 = Dense(32, activation='relu')(concat) drop = Dropout(0.05)(d_1) d_2 = Dense(32, activation='relu')(drop) d_3 = Dense(32, activation='relu')(d_2) # Two categories predicted, giving 2 neurons. activation='softmax' makes # these two nodes sum to 1 and be bounded between 0 and 1. out = Dense(2, activation='softmax')(d_3) cnn_time = Model(inputs=[inputs_spectro, inputs_time], outputs=out) cnn_time.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(), metrics=['accuracy']) # Save this trained model to the attached Google drive. Since the weights in # each layer of the model are randomly initialized, this is important to ensure # we're starting with exactly the same pre-training state to compare performance # of *this exact model instance* on the training splits. cnn_time.save(source_path + "cnn_model_binary_softmax.h5") ``` ### 2.2 CNN for W/N12/N34/REM staging The model below is identical to the one in 2.1 aside from there being 4 neurons on the last Dense layer corresponding to the four stages of sleep above. These stages MUST be <code>[0,1,2,3]</code> in the PSG labeling for the training. ``` # Model input layers inputs_spectro = Input(shape=(65, 73, 1)) inputs_time = Input(shape=(1,)) # Convolutional layers. Operate only on spectrograms c_1 = Conv2D(64, kernel_size=3, activation='relu', data_format='channels_last')(inputs_spectro) m_1 = MaxPool2D()(c_1) c_2 = Conv2D(32, kernel_size=3, activation='relu', data_format='channels_last')(m_1) m_2 = MaxPool2D()(c_2) # Flatten the layer to prepare for the densely connected layers flat = Flatten(data_format='channels_last')(m_2) # Now append time to the front of this flattened data concat = concatenate([inputs_time, flat]) # Start of densely connected layers d_1 = Dense(32, activation='relu')(concat) drop = Dropout(0.05)(d_1) d_2 = Dense(32, activation='relu')(drop) d_3 = Dense(32, activation='relu')(d_2) # Two categories predicted out = Dense(4, activation='softmax')(d_3) cnn_time = Model(inputs=[inputs_spectro, inputs_time], outputs=out) cnn_time.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(), metrics=['accuracy']) cnn_time.save(source_path + "cnn_model_staging_softmax.h5") ``` ### 1.2 No time Same as the first, but without time and so no concatenate layer between Flatten and Dense. ``` # Model input layers inputs_spectro = Input(shape=(65, 73, 1)) # Convolutional layers. Operate only on spectrograms c_1 = Conv2D(64, kernel_size=3, activation='relu', data_format='channels_last')(inputs_spectro) m_1 = MaxPool2D()(c_1) c_2 = Conv2D(32, kernel_size=3, activation='relu', data_format='channels_last')(m_1) m_2 = MaxPool2D()(c_2) # Flatten the layer to prepare for the densely connected layers flat = Flatten(data_format='channels_last')(m_2) # Start of densely connected layers d_1 = Dense(32, activation='relu')(flat) drop = Dropout(0.05)(d_1) d_2 = Dense(32, activation='relu')(drop) d_3 = Dense(32, activation='relu')(d_2) # Two categories predicted out = Dense(2, activation='softmax')(d_3) cnn_no_time = Model(inputs=inputs_spectro, outputs=out) cnn_no_time.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(), metrics=['accuracy']) cnn_no_time.save(source_path + "cnn_no_time_model_softmax.h5") ``` ## 2. Densely connected network definition To make somewhat comparable capacity between models we replace the Conv2D layers in the above models with Dense layers having the same number of neurons. Basically, the expressive power of the network; too much capacity gives better training results but overfits. There is probably more hyperparameter work to be done here to assess the correct capacity for the DNN; how much is needed to have similar performance as CNNs? Mathematically, this is possible, but the width and depth may be exceedingly large. See <a href="http://www2.math.technion.ac.il/~pinkus/papers/neural.pdf">Leshno, et al. (1993)</a> *Multilayer Feedforward Networks with a Nonpolynomial Activation Function can Approximate Any Function* (Neural Networks, Vol 6, pp 861--867) ``` # Input layers inputs_spectro = Input(shape=(65, 73)) inputs_time = Input(shape=(1,)) # Flatten the spectrogram input flat = Flatten()(inputs_spectro) # Pass spectrograms through several densely connected layers before incorporating time. d_1 = Dense(64, activation='relu')(flat) #drop_1 = Dropout(0.2)(d_1) d_2 = Dense(32, activation='relu')(d_1) #m_2 = MaxPool1D()(d_2) # Now append time to the front of this flattened data concat = concatenate([inputs_time, d_2]) # Start of densely connected layers d_3 = Dense(32, activation='relu')(concat) drop = Dropout(0.05)(d_3) d_4 = Dense(32, activation='relu')(drop) d_5 = Dense(32, activation='relu')(d_4) # Two categories predicted out = Dense(2, activation='softmax')(d_3) dnn_time = Model(inputs=[inputs_spectro, inputs_time], outputs=out) dnn_time.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(), metrics=['accuracy']) dnn_time.save(source_path + "dnn_with_time.h5") ``` ## 3. Train networks on leave-one-out splits The loops below use <code>ev.split_yielder</code> to train the above-defined CNNs and DNNs on the training data, per the description of this function in section 0.1. ``` # These describe the main part of the NN naming scheme for saving the trained neural networks. # For example, the CNN for sleep/wake classification would be trained on the training split excluding # subject 123, then saved to data_path + "pickles/123/123_softmax_time_cnn.h5" cnn_time_base = "_softmax_time_cnn.h5" cnn_no_time_base = "_softmax_time_no_cnn.h5" dnn_time_base = "_softmax_time_dnn.h5" count = 0 for split in ev.split_yielder(data_path=data_path, exclude = ['7749105']): # split == (subject in testing_split_data, training_split_data, testing_split_data) # split[1] == 2-tuple with element [i]... # [0] : [training spectrograms, training time] # [1] : training psg # Same elements for split[2], the testing data train_spectros = split[1][0][0].reshape(-1, 65, 73, 1) train_time = split[1][0][1].reshape(-1,1) train_X = [train_spectros, train_time] train_psg = np.where(split[1][1] > 0, 1, 0) test_spectros = split[2][0][0].reshape(-1, 65, 73, 1) test_time = split[2][0][1].reshape(-1,1) test_X = [test_spectros, test_time] test_psg = np.where(split[2][1] > 0, 1, 0) count += 1 # Keeps track of progress through the training regime print("Working on %s (%d of 28)" % (split[0], count)) split_cnn_time = tf.keras.models.load_model(source_path + "cnn_model_softmax.h5") split_cnn_no_time = tf.keras.models.load_model(source_path + "cnn_no_time_model_softmax.h5") print("Neural networks loaded.") with tf.device(gpu): split_cnn_time.fit(train_X, train_psg, epochs = 15, verbose = 1, validation_data = (test_X, test_psg)) split_cnn_no_time.fit(train_spectros, train_psg, epochs = 15, verbose = 1, validation_data = (test_spectros, test_psg)) split_cnn_time.save(data_path + "neural/" + split[0] + cnn_time_base) split_cnn_no_time.save(data_path + "neural/" + split[0] + cnn_no_time_base) count = 0 for split in ev.split_yielder(data_path=data_path, exclude = ['7749105']): # split == (subject in testing_split_data, training_split_data, testing_split_data) # split[1] == 2-tuple with element [i]... # [0] : [training spectrograms, training time] # [1] : training psg # Same elements for split[2], the testing data train_spectros = split[1][0][0] train_time = split[1][0][1].reshape(-1,1) train_X = [train_spectros, train_time] train_psg = np.where(split[1][1] > 0, 1, 0) test_spectros = split[2][0][0] test_time = split[2][0][1].reshape(-1,1) test_X = [test_spectros, test_time] test_psg = np.where(split[2][1] > 0, 1, 0) count += 1 # Keeps track of progress through the training regime print("Working on %s (%d of 28)" % (split[0], count)) split_dnn_time = tf.keras.models.load_model(source_path + "dnn_with_time.h5") print("Neural networks loaded.") split_dnn_time.fit(train_X, train_psg, epochs = 15, verbose = 1, validation_data = (test_X, test_psg)) split_dnn_time.save(data_path + "neural/" + split[0] + dnn_time_base) ``` ## 4. Evaluate We use the <code>pr_roc_from_path</code> function defined in <code>evaluator.py</code> to loop over the trained neural networks with the left-out subject's data as testing data. Passing <code>saveto=data_path + "abc.png"</code> will write the generated PR or ROC curve as abc.png, saved in the folder pointed to by <code>data_path</code>. If <code>saveto=None</code> (default) no picture is saved, just displayed below the cell. Options for <code>mode</code> are <code>"roc"</code> (the default) and <code>"pr"</code> that determine the obvious evaluation plot type. The output ROC or PR curve has many orangish-yellow curves and one blue curve. The blue curve is the pointwise mean of the other curves. ``` ev.pr_roc_from_path( ev.data_yielder(data_path, exclude = ['7749105'], nn_base_name =cnn_time_base), \ title="Leave-one-out training splits using time: ROC curve for CNN", \ # Change this to whatever the class label is you want considered "positive" (default: 0 = sleep) \ pos_label=0, \ # used for y/x axis labeling. If None, defaults to "True/False positive rate" label_names = {'positive' : "Awake", 'negative' : "Sleep"}, \ # Do not save the picture. Change this a string with full path of image file you want to write saveto=None, \ # make ROC plot instead of PR plot with ="pr" mode="roc", \ # we build our NNs with softmax activation at the final layer from_logits=False) ```
github_jupyter
# KENV <a href=mailto:fuodorov1998@gmail.com>V. Fedorov</a>, <a href=mailto:nikdanila@bk.ru>D. Nikiforov</a>, <a href=http://www.inp.nsk.su/~petrenko/>A. Petrenko</a>, (Novosibirsk, 2019) ## Genetic algorithm for building an envelope Sometimes it’s useful to use a computer to adjust the envelope. Genetic algorithms work similarly to natural selection in nature. The basis of the genetic algorithm is the individual, chromosomes (genes), population (set of individuals), the functions of adaptability, selection, crossing and mutation. In practice, everything happens like this: the creation of the first generation, assessment, selection, crossing, mutation, new generation, evaluation, etc. until we get the desired result. DEAP is a framework for working with genetic algorithms, containing many ready-made tools, the main thing is to know how to use them. ## Create a beam and accelerator. ``` import kenv as kv beam = kv.Beam(energy=2, current=2e3, radius=50e-3, rp=50e-3, normalized_emittance=1000e-6) accelerator = kv.Accelerator(0, 5, 0.01) Solenoids = [ [ 0.5000, 0.02, 'Bz.dat', 'Sol. 1'], [ 1.0000, 0.02, 'Bz.dat', 'Sol. 2'], [ 1.5000, 0.02, 'Bz.dat', 'Sol. 3'], [ 2.0000, 0.02, 'Bz.dat', 'Sol. 4'], [ 2.5000, 0.02, 'Bz.dat', 'Sol. 5'], [ 3.0000, 0.02, 'Bz.dat', 'Sol. 6'], [ 3.5000, 0.02, 'Bz.dat', 'Sol. 7'], [ 4.0000, 0.02, 'Bz.dat', 'Sol. 8'], [ 4.5000, 0.02, 'Bz.dat', 'Sol. 9'], ] for z0, B0, filename, name in Solenoids: accelerator.Bz_beamline[name] = kv.Element(z0, B0, filename, name) accelerator.compile() simulation = kv.Simulation(beam, accelerator) simulation.track() ``` ## Graphic ### matplotlib ``` import holoviews as hv hv.extension('matplotlib') %opts Layout [tight=True] %output size=150 backend='matplotlib' fig='svg' %opts Area Curve [aspect=3 show_grid=True] %opts Area (alpha=0.25) %opts Curve (alpha=0.5) %opts Area.Beam [aspect=3 show_grid=True] (color='red' alpha=0.3) import warnings warnings.filterwarnings('ignore') dim_z = hv.Dimension('z', unit='m', range=(accelerator.start, accelerator.stop)) dim_Bz = hv.Dimension('Bz', unit='T', label='Bz', range=(0, 0.1)) dim_Ez = hv.Dimension('Ez', unit='MV/m', label='Ez') dim_r = hv.Dimension('r', label="Beam r", unit='mm', range=(0, 150)) z_Bz= hv.Area((accelerator.parameter,accelerator.Bz(accelerator.parameter)), kdims=[dim_z], vdims=[dim_Bz]) z_r = hv.Area(((accelerator.parameter,simulation.envelope_x(accelerator.parameter)*1e3)), kdims=[dim_z], vdims=[dim_r], group='Beam') (z_r+z_Bz).cols(1) ``` As you can see, the envelope is far from perfect. Apply the genetic algorithm. ## Genetic algorithm First we construct a model envelope. ``` import numpy as np coefficients = np.polyfit([accelerator.start, (accelerator.start+accelerator.stop)/2, accelerator.stop], [0.15, 0.05, 0.03], 2) envelope_mod = coefficients[0]*accelerator.parameter**2 + coefficients[1]*accelerator.parameter+ coefficients[2] z_env = hv.Curve((accelerator.parameter, envelope_mod*1e3), kdims=[dim_z], vdims=[dim_r], label='Envelope_mod', group='Beam') z_env ``` Connect the necessary libraries. ``` import random from deap import creator, base, tools, algorithms ``` The first step is to create the necessary types. Usually it is fitness and the individual. ``` creator.create("FitnessMin", base.Fitness, weights=(-1.0,)) creator.create("Individual", list, fitness=creator.FitnessMin) ``` Next, you need to create a toolkit. To do this, you need to set the basic parameters for our algorithm. ``` Sol_B = 0.02 # [T] average Bz in the solenoids Sol_B_max = 0.05 # [T] max Bz Sol_B_min = 0.005 # [T] min Bz Sol_Num = 9 # quantity CXPB = 0.4 # cross chance MUTPB = 0.6 # Mutation probability NGEN = 100 # Number of generations POP = 100 # Number of individuals toolbox = base.Toolbox() toolbox.register("attr_float", random.gauss, Sol_B, ((Sol_B_max - Sol_B_min)/2)**2) toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_float, n=Sol_Num) toolbox.register("population", tools.initRepeat, list, toolbox.individual) ``` Create a fitness function. ``` def evalution_envelope(individual): for x in range(Sol_Num): accelerator.Bz_beamline['Sol. %.d'%(x+1)].max_field = individual[x] accelerator.compile() simulation = kv.Simulation(beam, accelerator) simulation.track() tuple(envelope_mod) tuple(simulation.envelope_x(accelerator.parameter)) sqerrors = np.sqrt((envelope_mod-simulation.envelope_x(accelerator.parameter))**2) return sum(sqerrors)/len(accelerator.parameter), toolbox.register("evaluate", evalution_envelope) toolbox.register("mate", tools.cxUniform, indpb=MUTPB ) toolbox.register("mutate", tools.mutGaussian, mu=0, sigma=((Sol_B_max - Sol_B_min)/2)**2, indpb=MUTPB) toolbox.register("select", tools.selTournament, tournsize=NGEN//3) ``` Logbook. ``` stats_fit = tools.Statistics(lambda ind: ind.fitness.values) mstats = tools.MultiStatistics(fitness=stats_fit) mstats.register("avg", np.mean) mstats.register("std", np.std) mstats.register("min", np.min) mstats.register("max", np.max) logbook = tools.Logbook() population = toolbox.population(n=POP) pop, logbook = algorithms.eaSimple(population, toolbox, cxpb=CXPB, mutpb=MUTPB, ngen=NGEN, stats=mstats, verbose=True) top = tools.selBest(pop, k=10) gen = np.array(logbook.select("gen")) fit_min = np.array(logbook.chapters["fitness"].select("min")) fit_max = np.array(logbook.chapters["fitness"].select("max")) fit_avg = np.array(logbook.chapters["fitness"].select("avg")) for x in range(Sol_Num): accelerator.Bz_beamline['Sol. %.d'%(x+1)].max_field = top[0][x] accelerator.compile() simulation = kv.Simulation(beam, accelerator) simulation.track() z_Bz_gen= hv.Area((accelerator.parameter,accelerator.Bz(accelerator.parameter)), kdims=[dim_z], vdims=[dim_Bz]) z_r_gen = hv.Area(((accelerator.parameter,simulation.envelope_x(accelerator.parameter)*1e3)), kdims=[dim_z], vdims=[dim_r], group='Beam') (z_r_gen*z_env+z_Bz_gen).cols(1) ```
github_jupyter
# Chat Intents ## Clustering without dimensionality reduction **Summary** This notebook briefly explores a few methods for representing documents with different embedding methods and clustering the embeddings with different algorithsm. In contrast to notebooks 04 and 05 in this repo, here no dimensionality reduction is used. As shown below, the biggest challene here remains selecting the right hyperparameters when the number of clusters isn't already known. ``` import random import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics import silhouette_score from sklearn.metrics.cluster import normalized_mutual_info_score from sklearn.metrics.cluster import adjusted_rand_score from sklearn.manifold import TSNE from sklearn.cluster import KMeans from sklearn.cluster import AgglomerativeClustering import hdbscan import tensorflow as tf import tensorflow_hub as hub from sentence_transformers import SentenceTransformer pd.set_option("display.max_rows", 500) pd.set_option("display.max_columns", 500) pd.set_option("max_colwidth", 400) data_sample = pd.read_csv('../data/processed/data_sample.csv') data_sample.head() ``` ### Helper functions ``` def plot_kmeans(embeddings, k_range): ''' Plot SSE and silhouette score for kmeans clustering for a range of k values Arguments: embeddings: array, sentence embeddings k_range: range, values of k to evaluate for kmeans clustering ''' sse = [] silhouette_avg_n_clusters = [] for k in k_range: kmeans = KMeans(n_clusters=k, init='k-means++', max_iter=100, n_init=1) kmeans.fit(embeddings) sse.append(kmeans.inertia_) silhouette_avg = silhouette_score(embeddings, kmeans.predict(embeddings)) silhouette_avg_n_clusters.append(silhouette_avg) # plot sse fig, axes = plt.subplots(1, 2, figsize=(14, 6)) axes[0].plot(k_range, sse) axes[0].set(xlabel = 'k clusters', ylabel = 'SSE', title = 'Elbow plot') axes[0].grid() # plot avg silhouette score axes[1].plot(k_range, silhouette_avg_n_clusters) axes[1].set(xlabel = 'k clusters', ylabel = 'Silhouette score', title = 'Silhouette score') axes[1].grid() plt.show() def search_cluster_size(embeddings, size_range): ''' Scan HDBSCAN min_cluster_size values and return results Arguments: embeddings: embeddings to use size_range: range of min_cluster_size hyperparameter values to scan Returns: result_df: dataframe of min_cluster_size, total number of clusters, and percent of data labeled as noise ''' results = [] for i in size_range: min_cluster_size = i clusters_hdbscan = (hdbscan.HDBSCAN(min_cluster_size=min_cluster_size, metric='euclidean', cluster_selection_method='eom') .fit(embeddings)) labels = clusters_hdbscan.labels_ label_count = len(np.unique(labels)) total_num = len(clusters_hdbscan.labels_) cost = (np.count_nonzero(clusters_hdbscan.probabilities_ < 0.05)/total_num) results.append([min_cluster_size, label_count, cost]) result_df = pd.DataFrame(results, columns=['min_cluster_size', 'label_count', 'noise']) return result_df def random_search(embeddings, space, num_evals): ''' Random search of HDBSCAN hyperparameter spcae Arguments: embeddings: embeddings to use space: dict, hyperparameter space to search with keys of 'min_cluster_size' and 'min_samples' and values as ranges num_evals: int, number of trials to run Returns: result_df: dataframe of run_id, min_cluster_size, min_samples, total number of clusters, and percent of data labeled as noise ''' results = [] for i in range(num_evals): min_cluster_size = random.choice(space['min_cluster_size']) min_samples = random.choice(space['min_samples']) clusters_hdbscan = (hdbscan.HDBSCAN(min_cluster_size=min_cluster_size, min_samples = min_samples, metric='euclidean', cluster_selection_method='eom') .fit(embeddings)) labels = clusters_hdbscan.labels_ label_count = len(np.unique(labels)) total_num = len(clusters_hdbscan.labels_) cost = (np.count_nonzero(clusters_hdbscan.probabilities_ < 0.05)/total_num) results.append([i, min_cluster_size, min_samples, label_count, cost]) result_df = pd.DataFrame(results, columns=['run_id', 'min_cluster_size', 'min_samples', 'label_count', 'cost']) return result_df.sort_values(by='cost') ``` ### TF-IDF embeddings with K-means ``` cleaned_text = data_sample['cleaned_text'] cleaned_text.head() tfidf_vectorizer = TfidfVectorizer() tfidf_transformed_vector = tfidf_vectorizer.fit_transform(cleaned_text) tfidf_transformed_vector.shape k = 10 kmeans = KMeans(n_clusters=k, init='k-means++', max_iter=100, n_init=1) kmeans.fit(tfidf_transformed_vector) len(kmeans.labels_) %%time k_range = range(5, 141) plot_kmeans(tfidf_transformed_vector, k_range) ``` There's no clear elbow in the scree plot of the sum of squared errors as a function of the number of clusters (k). Additionally, the silhouette score appears to continue increasing over the range considered. Thus, neither approach makes it clear what value to select for k. ## Sentence Embeddings The sentence embedding models typically expect raw sentences (without preprocessing), so we'll use those here. ``` full_text = data_sample['text'] ``` ### USE Sentence Embeddings + Kmeans Start with Universal Sentence Encoder (USE) as an example sentence embedding model. ``` module_url = "https://tfhub.dev/google/universal-sentence-encoder/4" model_use = hub.load(module_url) print(f"module {module_url} loaded") use_embeddings = model_use(full_text) use_embeddings.shape %%time k_range = range(5, 151) plot_kmeans(use_embeddings, k_range) ``` As with the TF-IDF embeddings above, it's not obvious what number of clusters to select from these plots. The silhouette score continues to slowly increase as the number of clusters increases. Even at 150 clusters though, the silhouette score has only reached 0.08, which is quite low. ### Sentence Transformer Embeddings + Kmeans Use a sentence-transformer pretrained model that was made in a way to preserve the usefulness of Euclidean distances (https://www.sbert.net/docs/pretrained_models.html). ``` model_st = SentenceTransformer('all-mpnet-base-v2') st_embeddings = model_st.encode(full_text) st_embeddings.shape %%time k_range = range(5, 151) plot_kmeans(st_embeddings, k_range) ``` As with the USE model, it still isn't obvious what value of k to select. From the silhouette score plot we see that the values seem to somewhat level off starting at around 100 clusters, but it also continues to slowly rise from there. ### Hierarchical clustering ``` # Normalize the embeddings to unit length st_embeddings_norm = st_embeddings / np.linalg.norm(st_embeddings, axis=1, keepdims=True) # Perform clustering agglom_model = AgglomerativeClustering(n_clusters=None, distance_threshold=1.5) agglom_model.fit(st_embeddings_norm) cluster_assignment = agglom_model.labels_ len(np.unique(cluster_assignment)) ``` While we can obvoiusly create clusters using hierarchical clustering, we still have no way to intuitively select the necessary hyperparameters (e.g. distance_threshold in this case). ### Sentence Embeddings + HDBSCAN ``` clusters_hdbscan = hdbscan.HDBSCAN(min_cluster_size=2, metric='euclidean', cluster_selection_method='eom').fit(st_embeddings) labels = clusters_hdbscan.labels_ len(np.unique(labels)) pd.Series(labels).value_counts().head(10) size_range = range(2,11) search_cluster_size(st_embeddings, size_range=size_range) ``` Scanning through different min_cluster_size values for HDBSCAN reveals some of the challenges of using the raw sentence embeddings. Either all the datapoints are lumped into the same, small number of clusters (e.g. 3 total), or a large percentage of datapoints are not clustered (e.g. 38% of the data is left out as noise with a min_cluster_size of 3). ``` %%time space = { "min_cluster_size": range(2, 30), "min_samples": range(2, 30) } random_search(st_embeddings, space, num_evals=100).head(20) ``` Decoupling min_samples separate from min_cluster_size doesn't improve our results (min_samples is set equal to min_cluster_size by default in HDBSCAN if it is not specified). We still see the same issues here or either too few clusters or too many samples being labeled as noise.
github_jupyter
### This notebook gets the hand data csv file and rewrites the tendon values to align with the theory of mirror neurons. Using ridge regression, a mapping is created between visual features and tendon values. These new tendon values created from the visual features are written in a new file called hand_data_mirror ``` import pandas as pd from sklearn.metrics import * from sklearn import linear_model from sklearn.model_selection import cross_val_score from collections import defaultdict as dd import numpy as np from sklearn.model_selection import train_test_split from sklearn import linear_model from slir import SparseLinearRegression import operator import re from collections import Counter #from textblob import TextBlob #from textblob import Word from IPython.display import HTML, display from IPython.display import Image import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib import cm from mpl_toolkits.mplot3d import Axes3D %matplotlib import pickle ``` ### Read data, remove punctuation, stem, and tokenize the descriptions, and add camera one-hot encoding ``` def read_raw_data(): data = pd.read_csv('../data/hand_data3_separated.csv', index_col=False) # remove punctuation data['desc_list'] = data.description.apply(lambda x: [i for i in re.sub(r'[^\w\s]','',str(x)).lower().split()]) data['desc_str'] = data.desc_list.apply(lambda x: ' '.join(x)) #add one-hot encoding camera_data = pd.get_dummies(data.camera_angle) data = pd.concat([data, camera_data], axis=1) cols = data.columns.tolist() cols = cols[:8] + cols[-4:] + cols[8:-4] data = data[cols] #get words and vocabs words = [y for x in data.desc_list for y in x] vocab = list(set(words)) print('number of unique words in our data:', len(vocab), '\nnumber of word tokens in our data: ', len(words)) return data, words, vocab ``` ### Read in data, stack it, and clean it ``` def read_in_data(): train_data = pd.read_pickle("../data/train_data3_separated.pkl") test_data = pd.read_pickle("../data/test_data3_separated.pkl") return train_data, test_data def stack_training_data(mydata): s = mydata.apply(lambda x: pd.Series(x['desc_list']),axis=1).stack().reset_index(level=1, drop=True) s.name = 'word' mydata = mydata.join(s) return mydata def remove_unwated_words(mydata, vocab, words): wanted_words = list(set(words)) unwanted_words = {'hand', 'and', 'the', 'a', 'with', 'is', 'are', 'to', 'of', 'finger', 'fingers', 'thumb'} unwanted_tags = {} for curr_word in vocab: if curr_word in unwanted_words: wanted_words.remove(curr_word) mydata = mydata.loc[mydata['word'].isin(wanted_words)] return mydata _, words, vocab = read_raw_data() train_data, test_data = read_in_data() train_data[:10] ``` ## Create Ridge Regression Model ``` data, words, vocab = read_raw_data() data.columns[:15] START_COL = 'T1' END_COL = 'T5' V_START_COL = 'above' V_END_COL = 'f1000' y = train_data.ix[:,START_COL:END_COL].as_matrix() X = train_data.ix[:,V_START_COL:V_END_COL].as_matrix() y_test = test_data.ix[:,START_COL:END_COL].as_matrix() X_test = test_data.ix[:,V_START_COL:V_END_COL].as_matrix() y_all = data.ix[:,START_COL:END_COL].as_matrix() X_all = data.ix[:,V_START_COL:V_END_COL].as_matrix() print("train", X.shape, y.shape) print("test", X_test.shape, y_test.shape) print("all", X_all.shape, y_all.shape) from sklearn.linear_model import * import numpy as np model = Ridge(alpha=0.0001, copy_X=True, fit_intercept=True, max_iter=None, normalize=True, random_state=False, solver='auto', tol=0.01) model.fit(X, y) ``` ## Evaluation of Ridge Regression model ``` from sklearn.metrics import mean_squared_error from math import sqrt import math y_actual = y_test y_predicted = model.predict(X_test) rms = sqrt(mean_squared_error(y_actual, y_predicted)) print(rms) print(y_actual[:10]) print(np.around(y_predicted[:10], decimals=1)) ``` ## Produce mirror .pkl ``` new_tendons = model.predict(X_all) new_tendons.shape # this should match above # new_tendons now needs to replace the columns from START_COL to END_COL data_old = pd.read_csv('../data/hand_data3_separated.csv', index_col=False) #modify the data data_new = data_old columns = ["T1", "T2", "T3", "T4", "T5"] for i, col in enumerate(columns): print(i, col) data_new = data_new.drop([col], axis=1) data_new.insert(loc=i+3, column=col, value=new_tendons[:,i],) data_new #write new tedoncs to csv file data_new.to_csv(path_or_buf='../data/hand_data3_mirror.csv', index=False) ```
github_jupyter
## week0_09 practice: PyTorch practice, hints and Dataloaders Credits: * First part is based on YSDA [Practical RL course week04 materials](https://github.com/yandexdataschool/Practical_RL/tree/master/week04_%5Brecap%5D_deep_learning). * Second part is based on PyTorch official tutorials and [this kaggle kernel](https://www.kaggle.com/pinocookie/pytorch-dataset-and-dataloader) * Third part is based on PyTorch tutorial by [Stanford CS 231n course](http://cs231n.stanford.edu) ![img](https://pytorch.org/tutorials/_static/pytorch-logo-dark.svg) __This notebook__ will remind you how to use pytorch low and high-level core. You can install it [here](http://pytorch.org/). __Pytorch feels__ differently than other frameworks (like tensorflow/theano) on almost every level. TensorFlow makes your code live in two "worlds" simultaneously: symbolic graphs and actual tensors. First you declare a symbolic "recipe" of how to get from inputs to outputs, then feed it with actual minibatches of data. In pytorch, __there's only one world__: all tensors have a numeric value. You compute outputs on the fly without pre-declaring anything. The code looks exactly as in pure numpy with one exception: pytorch computes gradients for you. And can run stuff on GPU. And has a number of pre-implemented building blocks for your neural nets. [And a few more things.](https://medium.com/towards-data-science/pytorch-vs-tensorflow-spotting-the-difference-25c75777377b) Let's dive into it! ``` import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) import matplotlib.pyplot as plt import torch from torch.utils.data import DataLoader, Dataset, Subset import torchvision from torchvision import transforms ``` ### Task 1: Tensormancy __1.1 The [_disclaimer_](https://gist.githubusercontent.com/justheuristic/e2c1fa28ca02670cabc42cacf3902796/raw/fd3d935cef63a01b85ed2790b5c11c370245cbd7/stddisclaimer.h)__ Let's write another function, this time in polar coordinates: $$\rho(\theta) = (1 + 0.9 \cdot cos (6 \cdot \theta) ) \cdot (1 + 0.01 \cdot cos(24 \cdot \theta)) \cdot (0.5 + 0.05 \cdot cos(200 \cdot \theta)) \cdot (10 + sin(10 \cdot \theta))$$ Then convert it into cartesian coordinates ([howto](http://www.mathsisfun.com/polar-cartesian-coordinates.html)) and plot the results. Use torch tensors only: no lists, loops, numpy arrays, etc. ``` theta = torch.linspace(-np.pi, np.pi, steps=1000) # compute rho(theta) as per formula above rho = (1 + 0.9*torch.cos(6*theta)) * (1 + 0.01*torch.cos(24*theta)) * (0.5 + 0.05*torch.cos(200*theta)) * (10 + torch.sin(6*theta)) # Now convert polar (rho, theta) pairs into cartesian (x,y) to plot them. x = rho * torch.cos(theta) ### YOUR CODE HERE y = rho * torch.sin(theta) ### YOUR CODE HERE plt.figure(figsize=(6, 6)) plt.fill(x.numpy(), y.numpy(), color='red') plt.grid() ``` ### Task 2: Using the Dataloader ``` from torch import nn from torch.nn import functional as F !wget https://raw.githubusercontent.com/girafe-ai/ml-mipt/basic_s20/week0_09_Optimization_and_Regularization_in_DL/notmnist.py -nc from notmnist import load_notmnist X_train, y_train, X_test, y_test = load_notmnist() class DatasetMNIST(Dataset): def __init__(self, path='./notMNIST_small', letters='ABCDEFGHIJ', transform=None): self.data, self.labels, _ ,_ = load_notmnist(path=path, letters=letters, test_size=0) self.transform = transform def __len__(self): return len(self.data) def __getitem__(self, index): # load image as ndarray type (Height * Width * Channels) # be carefull for converting dtype to np.uint8 [Unsigned integer (0 to 255)] # in this example, i don't use ToTensor() method of torchvision.transforms # so you can convert numpy ndarray shape to tensor in PyTorch (H, W, C) --> (C, H, W) image = self.data[index].transpose(1, 2, 0) label = self.labels[index] if self.transform is not None: image = self.transform(image) return image, label full_dataset = DatasetMNIST('./notMNIST_small', 'AB', transform=None) # we can access and get data with index by __getitem__(index) img, lab = full_dataset.__getitem__(0) print(img.shape) print(type(img)) a = torchvision.transforms.ToTensor() a(img).shape inds = np.random.randint(len(full_dataset), size=2) for i in range(2): plt.subplot(1, 2, i + 1) plt.imshow(full_dataset[inds[i]][0].reshape([28,28])) plt.title(str(full_dataset[inds[i]][1])) ``` #### To the DataLoader ``` train_loader = DataLoader(full_dataset, batch_size=8, shuffle=True) ``` We can use dataloader as iterator by using iter() function. ``` train_iter = iter(train_loader) print(type(train_iter)) ``` We can look at images and labels of batch size by extracting data `.next()` method. ``` images, labels = train_iter.next() print('images shape on batch size = {}'.format(images.size())) print('labels shape on batch size = {}'.format(labels.size())) # make grid takes tensor as arg # tensor : (batchsize, channels, height, width) grid = torchvision.utils.make_grid(images.permute([0, 3, 1, 2])) plt.imshow(grid.numpy().transpose((1, 2, 0))) plt.axis('off') plt.title(labels.numpy()); ``` And now with transformations: ``` train_dataset_with_transform = DatasetMNIST( transform=torchvision.transforms.ToTensor() ) img, lab = train_dataset_with_transform.__getitem__(0) print('image shape at the first row : {}'.format(img.size())) train_loader_tr = DataLoader(train_dataset_with_transform, batch_size=8, shuffle=True) train_iter_tr = iter(train_loader_tr) print(type(train_iter_tr)) images, labels = train_iter_tr.next() print('images shape on batch size = {}'.format(images.size())) print('labels shape on batch size = {}'.format(labels.size())) grid = torchvision.utils.make_grid(images) plt.imshow(grid.numpy().transpose((1, 2, 0))) plt.axis('off') plt.title(labels.numpy()); ``` ### Composing several transformations If you want to take data augmentation, you have to make List using `torchvision.transforms.Compose` ``` class Compose(object): """Composes several transforms together. Args: transforms (list of ``Transform`` objects): list of transforms to compose. Example: >>> transforms.Compose([ >>> transforms.CenterCrop(10), >>> transforms.ToTensor(), >>> ]) """ def __init__(self, transforms): self.transforms = transforms def __call__(self, img): for t in self.transforms: img = t(img) return img def __repr__(self): format_string = self.__class__.__name__ + '(' for t in self.transforms: format_string += '\n' format_string += ' {0}'.format(t) format_string += '\n)' return format_string ``` this function can convert some image by order within `__call__` method. ``` class Flatten(): def __call__(self, pic): return pic.flatten() def __repr__(self): return self.__class__.__name__ + '()' a = Flatten() a(img).shape new_transform = torchvision.transforms.Compose([ torchvision.transforms.ToTensor(), Flatten() ]) ``` # Putting all together ``` import time from IPython.display import clear_output # use GPU if available device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") device def subset_ind(dataset, ratio: float): # return ### YOUR CODE HERE return np.random.choice(len(dataset), size=int(ratio*len(dataset)), replace=False) dataset = DatasetMNIST( './notMNIST_small', # 'AB', transform=new_transform ) shrink_inds = subset_ind(dataset, 0.2) dataset = Subset(dataset, shrink_inds) print(f'\n\n dataset size: {len(dataset)}, labels: {np.unique(dataset.dataset.labels)}') val_size = 0.2 val_inds = subset_ind(dataset, val_size) train_dataset = Subset(dataset, [i for i in range(len(dataset)) if i not in val_inds]) val_dataset = Subset(dataset, val_inds) print(f' training size: {len(train_dataset)}\nvalidation size: {len(val_dataset)}') batch_size = 32 train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True) val_loader = DataLoader(val_dataset, batch_size=batch_size, shuffle=False) train_iter = iter(train_loader) print(type(train_iter)) images, labels = train_iter.next() print('images shape on batch size = {}'.format(images.size())) print('labels shape on batch size = {}'.format(labels.size())) loss_func = nn.CrossEntropyLoss() # create network again just in case model = nn.Sequential( nn.Linear(784, 10), nn.Sigmoid(), ) model.to(device, torch.float32) opt = torch.optim.Adam(model.parameters(), lr=1e-3) def train_model(model, train_loader, val_loader, loss_fn, opt, n_epochs: int, device=device): ''' model: нейросеть для обучения, train_loader, val_loader: загрузчики данных loss_fn: целевая метрика (которую будем оптимизировать) opt: оптимизатор (обновляет веса нейросети) n_epochs: кол-во эпох, полных проходов датасета ''' train_loss = [] val_loss = [] val_accuracy = [] for epoch in range(n_epochs): ep_train_loss = [] ep_val_loss = [] ep_val_accuracy = [] start_time = time.time() model.train(True) # enable dropout / batch_norm training behavior for X_batch, y_batch in train_loader: opt.zero_grad() # move data to target device X_batch, y_batch = X_batch.to(device), y_batch.to(device) # train on batch: compute loss, calc grads, perform optimizer step and zero the grads out = model(X_batch) loss = loss_fn(out, y_batch) loss.backward() opt.step() ep_train_loss.append(loss.item()) model.train(False) # disable dropout / use averages for batch_norm with torch.no_grad(): for X_batch, y_batch in val_loader: # move data to target device ### YOUR CODE HERE X_batch, y_batch = X_batch.to(device), y_batch.to(device) # compute predictions ### YOUR CODE HERE out = model(X_batch) loss = loss_fn(out, y_batch) ep_val_loss.append(loss.item()) y_pred = out.max(dim=1)[1] ### YOUR CODE HERE ep_val_accuracy.append(np.sum((y_pred.cpu() == y_batch.cpu()).numpy().astype(float)) / len(y_pred)) # print the results for this epoch: print(f'Epoch {epoch + 1} of {n_epochs} took {time.time() - start_time:.3f}s') train_loss.append(np.mean(ep_train_loss)) val_loss.append(np.mean(ep_val_loss)) val_accuracy.append(np.mean(ep_val_accuracy)) print(f"\t training loss: {train_loss[-1]:.6f}") print(f"\tvalidation loss: {val_loss[-1]:.6f}") print(f"\tvalidation accuracy: {val_accuracy[-1]:.3f}") return train_loss, val_loss, val_accuracy n_epochs = 30 train_loss, val_loss, val_accuracy = train_model(model, train_loader, val_loader, loss_func, opt, n_epochs) def plot_train_process(train_loss, val_loss, val_accuracy): fig, axes = plt.subplots(1, 2, figsize=(15, 5)) axes[0].set_title('Loss') axes[0].plot(train_loss, label='train') axes[0].plot(val_loss, label='validation') axes[0].legend() axes[1].set_title('Validation accuracy') axes[1].plot(val_accuracy) plot_train_process(train_loss, val_loss, val_accuracy) ``` ## Real network ``` # create network again just in case model = nn.Sequential( nn.Linear(784, 500), nn.ReLU(), nn.Linear(500, 200), nn.ReLU(), nn.Linear(200, 10), nn.Sigmoid(), ) model.to(device, torch.float32) opt = torch.optim.Adam(model.parameters(), lr=1e-3) n_epochs = 30 train_loss, val_loss, val_accuracy = train_model(model, train_loader, val_loader, loss_func, opt, n_epochs) plot_train_process(train_loss, val_loss, val_accuracy) ``` ## Your turn Try to add some additional transformations (e.g. random crop, rotation etc.) and train your model! ### Dropout try ``` # create network again just in case model = nn.Sequential( nn.Linear(784, 500), nn.Dropout(0.5), nn.ReLU(), nn.Linear(500, 200), nn.Dropout(0.5), nn.ReLU(), nn.Linear(200, 10), nn.Sigmoid(), ) model.to(device, torch.float32) opt = torch.optim.Adam(model.parameters(), lr=1e-3) n_epochs = 30 train_loss, val_loss, val_accuracy = train_model(model, train_loader, val_loader, loss_func, opt, n_epochs) plot_train_process(train_loss, val_loss, val_accuracy) ``` ### Batchnorm try ``` ``` ### 3. Save the model (model checkpointing) Now we have trained a model! Obviously we do not want to retrain the model everytime we want to use it. Plus if you are training a super big model, you probably want to save checkpoint periodically so that you can always fall back to the last checkpoint in case something bad happened or you simply want to test models at different training iterations. Model checkpointing is fairly simple in PyTorch. First, we define a helper function that can save a model to the disk ``` def save_checkpoint(checkpoint_path, model, optimizer): # state_dict: a Python dictionary object that: # - for a model, maps each layer to its parameter tensor; # - for an optimizer, contains info about the optimizer’s states and hyperparameters used. state = { 'state_dict': model.state_dict(), 'optimizer' : optimizer.state_dict()} torch.save(state, checkpoint_path) print('model saved to %s' % checkpoint_path) def load_checkpoint(checkpoint_path, model, optimizer): state = torch.load(checkpoint_path) model.load_state_dict(state['state_dict']) optimizer.load_state_dict(state['optimizer']) print('model loaded from %s' % checkpoint_path) # create a brand new model model = Net().to(device) optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9) # Testing -- you should get a pretty poor performance since the model hasn't learned anything yet. test() ``` #### Define a training loop with model checkpointing ``` def train_save(epoch, save_interval, log_interval=100): model.train() # set training mode iteration = 0 for ep in range(epoch): for batch_idx, (data, target) in enumerate(trainset_loader): data, target = data.to(device), target.to(device) optimizer.zero_grad() output = model(data) loss = F.nll_loss(output, target) loss.backward() optimizer.step() if iteration % log_interval == 0: print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format( ep, batch_idx * len(data), len(trainset_loader.dataset), 100. * batch_idx / len(trainset_loader), loss.item())) # different from before: saving model checkpoints if iteration % save_interval == 0 and iteration > 0: save_checkpoint('mnist-%i.pth' % iteration, model, optimizer) iteration += 1 test() # save the final model save_checkpoint('mnist-%i.pth' % iteration, model, optimizer) train_save(5, save_interval=500, log_interval=100) # create a new model model = Net().to(device) optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9) # load from the final checkpoint load_checkpoint('mnist-4690.pth', model, optimizer) # should give you the final model accuracy test() ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ### More about pytorch: * Using torch on GPU and multi-GPU - [link](http://pytorch.org/docs/master/notes/cuda.html) * More tutorials on pytorch - [link](http://pytorch.org/tutorials/beginner/deep_learning_60min_blitz.html) * Pytorch examples - a repo that implements many cool DL models in pytorch - [link](https://github.com/pytorch/examples) * Practical pytorch - a repo that implements some... other cool DL models... yes, in pytorch - [link](https://github.com/spro/practical-pytorch) * And some more - [link](https://www.reddit.com/r/pytorch/comments/6z0yeo/pytorch_and_pytorch_tricks_for_kaggle/)
github_jupyter
``` !wget -p https://www.anatel.gov.br/dadosabertos/paineis_de_dados/acessos/acessos_banda_larga_fixa.zip import pandas as pd import numpy as np import os from zipfile import ZipFile pasta = '/content/www.anatel.gov.br/dadosabertos/paineis_de_dados/acessos' broadband = os.path.join(pasta, 'acessos_banda_larga_fixa.zip') #decodificando os arquivos #Anatel separa os arquivos por biênio #Entre 2007 e 2010 os dados eram fornecidos por trimestre, a partir de 2011 os dados passam a ser mensais with ZipFile(broadband) as z: with z.open(f'Acessos_Banda_Larga_Fixa_2007-2010.csv') as f: b_1 = pd.read_csv(f,sep=';', encoding='utf-8') with ZipFile(broadband) as z: with z.open(f'Acessos_Banda_Larga_Fixa_2011-2012.csv') as f: b_2 = pd.read_csv(f,sep=';', encoding='utf-8') with ZipFile(broadband) as z: with z.open(f'Acessos_Banda_Larga_Fixa_2013-2014.csv') as f: b_3 = pd.read_csv(f,sep=';', encoding='utf-8') with ZipFile(broadband) as z: with z.open(f'Acessos_Banda_Larga_Fixa_2015-2016.csv') as f: b_4 = pd.read_csv(f,sep=';', encoding='utf-8') with ZipFile(broadband) as z: with z.open(f'Acessos_Banda_Larga_Fixa_2017-2018.csv') as f: b_5 = pd.read_csv(f,sep=';', encoding='utf-8') with ZipFile(broadband) as z: with z.open(f'Acessos_Banda_Larga_Fixa_2019-2020.csv') as f: b_6 = pd.read_csv(f,sep=';', encoding='utf-8') with ZipFile(broadband) as z: with z.open(f'Acessos_Banda_Larga_Fixa_2021.csv') as f: b_7 = pd.read_csv(f,sep=';', encoding='utf-8') #junção das bases bl = b_1.append([b_2, b_3, b_4, b_5, b_6, b_7], ignore_index=True) #renomeando variaveis bl.rename(columns={'Ano': 'ano','Mês':'mes', 'Grupo Econômico':'grupo_economico', 'Empresa':'empresa', 'CNPJ':'cnpj', 'Porte da Prestadora':'porte_empresa', 'UF':'sigla_uf', 'Município':'municipio', 'Código IBGE Município':'id_municipio', 'Faixa de Velocidade':'velocidade', 'Tecnologia':'tecnologia', 'Meio de Acesso':'transmissao', 'Acessos':'acessos', 'Tipo de Pessoa': 'pessoa'}, inplace=True) #organização das variáveis bl.drop(['grupo_economico', 'municipio', 'pessoa'], axis=1, inplace=True) bl = bl[['ano', 'mes', 'sigla_uf', 'id_municipio', 'cnpj', 'empresa', 'porte_empresa', 'tecnologia', 'transmissao', 'velocidade', 'acessos']] bl.sort_values(['ano', 'mes', 'id_municipio'], inplace=True) #presença de variáveis duplicado = bl.duplicated(subset=['ano', 'mes', 'sigla_uf', 'id_municipio', 'cnpj', 'empresa', 'porte_empresa', 'tecnologia', 'transmissao', 'velocidade']).any() duplicado #os dados possuem duplicações mostrando diferentes resultados para acesso #o agrupamento é feito pelas variáveis de identificação bl['acessos_total'] = bl.groupby(['ano', 'mes', 'sigla_uf', 'id_municipio', 'cnpj', 'empresa', 'porte_empresa', 'tecnologia', 'transmissao', 'velocidade'])['acessos'].transform(np.sum) #após ordenamento das observações, se mantém somente 1 linha que identifique as observações bl.sort_values(['ano', 'mes', 'sigla_uf', 'id_municipio', 'cnpj', 'empresa', 'porte_empresa', 'tecnologia', 'transmissao', 'velocidade'], inplace=True) bl.drop_duplicates(subset=['ano', 'mes', 'sigla_uf', 'id_municipio', 'cnpj', 'empresa', 'porte_empresa', 'tecnologia', 'transmissao', 'velocidade'], keep='first', inplace=True) #exclui-se a coluna de acessos e renomeia bl.drop('acessos', axis=1, inplace=True) bl.rename(columns={'acessos_total':'acessos'}, inplace=True) #salvar arquivos no Drive from google.colab import drive drive.mount('/content/drive') #exportação para csv bl.to_csv('/content/drive/MyDrive/br_anatel/banda_larga_fixa/output/banda_larga_microdados.csv', index=False) #drop das variáveis ligada a empresas bl_mun = bl.drop(['empresa','cnpj', 'porte_empresa'], axis = 1) #collapse para acessos bl_mun['acessos_total'] = bl_mun.groupby(['ano', 'mes', 'id_municipio', 'tecnologia', 'transmissao', 'velocidade'])['acessos'].transform(np.sum) #ordenamento das variaveis bl_mun.sort_values(['ano', 'mes', 'id_municipio', 'tecnologia', 'transmissao', 'velocidade'], inplace=True) #exclusão das variaveis duplicadas bl_mun.drop_duplicates(subset=['ano', 'mes', 'id_municipio', 'tecnologia', 'transmissao', 'velocidade'], keep ='first', inplace = True) #exclusão da coluna de acessos bl_mun.drop('acessos', axis=1, inplace=True) #renome da coluna de acessos total bl_mun.rename(columns={'acessos_total':'acessos'}, inplace=True) bl_mun.to_csv('/content/drive/MyDrive/br_anatel/banda_larga_fixa/output/banda_larga_municipios', index=False) ```
github_jupyter
``` import numpy as np import pandas as pd df = pd.read_csv('dataset_AirQual.csv') #use fillna() method to replace missing values with mean value df['pm2.5'].fillna(df['pm2.5'].mean(), inplace = True) #one hot encoding cols = df.columns.tolist() df_new = pd.get_dummies(df[cols]) #put column pm2.5 at the end of the df #avoid one of the column rearrangement steps cols = df_new.columns.tolist() cols_new = cols[:5] + cols[6:] + cols[5:6] df_new = df_new[cols_new] df_new.head() ``` Before I start to build, train and validate the model, I want to check the correlation between the indepependent variables and the dependent variable pm2.5. The higher the cumulated wind speed (lws) and the more the wind is blowin from north west (cbwd_NW), the lower the concentration of pm2.5. <br> The more the wind is blowing from south west (cbwd_cv) and the higher the dew point (DEWP), the higher the concentration of pm2.5 in the air. The dew point indicates the absolute humidity. During times with high humidity, more pm2.5 particles can connect themselves with water droplets, that hover in the air. ``` indep_var = cols_new[:-1] df_new[indep_var].corrwith(df_new['pm2.5']).sort_values() #get matrix arrays of dependent and independent variables X = df_new.iloc[:, :-1].values y = df_new.iloc[:, -1].values #train decision tree regression model from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LinearRegression from sklearn.tree import DecisionTreeRegressor #training the model def train(X_train, y): #scale the training set data sc = StandardScaler() X_train_trans = sc.fit_transform(X_train) regressor = DecisionTreeRegressor(random_state=1) regressor.fit(X_train_trans, y) return regressor from sklearn.preprocessing import StandardScaler #make predictions (apply model to new data) def predict(X_val, regressor): #scale the new data sc = StandardScaler() X_val_trans = sc.fit_transform(X_val) y_pred = regressor.predict(X_val_trans) return y_pred from sklearn.metrics import mean_squared_error #do k-fold cross-validation from sklearn.model_selection import KFold kfold = KFold(n_splits=10, shuffle=True, random_state=1) mse_list = [] for train_idx, val_idx in kfold.split(X): #split data in train & val sets X_train = X[train_idx] X_val = X[val_idx] y_train = y[train_idx] y_val = y[val_idx] #train model and make predictions model = train(X_train, y_train) y_pred = predict(X_val, model) #evaluate mse = mean_squared_error(y_val, y_pred) mse_list.append(mse) print('mse = %0.3f ± %0.3f' % (np.mean(mse_list), np.std(mse_list))) #compare predicted values with real ones np.set_printoptions(precision=2) conc_vec = np.concatenate((y_pred.reshape(len(y_pred),1), y_val.reshape(len(y_val),1)), 1) conc_vec[50:100] ```
github_jupyter
<div style="text-align: right" align="right"><i>Peter Norvig<br>December 2020</i></div> # Advent of Code 2020 This year I return to [Advent of Code](https://adventofcode.com), as I did in [2016](Advent+of+Code), [17](Advent+2017), and [18](Advent-2018.ipynb). Thank you, [**Eric Wastl**](http://was.tl/)! You'll have to look at the [Advent of Code website](https://adventofcode.com/2020) if you want the full description of each puzzle; this notebook gives only a brief summary. For each day from 1 to 25, I'll write **four pieces of code**, each in a separate notebook cell. For example, on day 3: - `in3: List[str] = data(3)`: the day's input data, parsed into an appropriate form (here, a list of string lines). Most days the data comes from a file, read via the function `data` (which has optional arguments to say how to split the data into sections/records and how to parse each one), but some days the data is so small I just copy and paste it. - `def day3_1(nums): ... `: a function that takes the day's data as input and returns the answer for Part 1. - `def day3_2(nums): ... `: a function that takes the day's data as input and returns the answer for Part 2. - `do(3)`: executes the call `day3_1(in3)`. I'll then use the result to hopefully unlock part 2 and define `day3_2`, which also gets run when I call `do(3)` again. Once I verify both answers, I'll change `do(3)` to `do(3, 167, 736527114)` to serve as a unit test. # Day 0: Imports and Utility Functions Preparations prior to Day 1: - Some imports. - A way to read the day's data file and to print/check the output. - Some utilities that are likely to be useful. ``` from __future__ import annotations from collections import Counter, defaultdict, namedtuple, deque from itertools import permutations, combinations, product, chain from functools import lru_cache, reduce from typing import Dict, Tuple, Set, List, Iterator, Optional, Union, Sequence from contextlib import contextmanager import operator import math import ast import sys import re def data(day: int, parser=str, sep='\n') -> list: "Split the day's input file into sections separated by `sep`, and apply `parser` to each." with open(f'data/advent2020/input{day}.txt') as f: sections = f.read().rstrip().split(sep) return list(map(parser, sections)) def do(day, *answers) -> List[int]: "E.g., do(3) returns [day3_1(in3), day3_2(in3)]. Verifies `answers` if given." g = globals() got = [] for part in (1, 2): fname = f'day{day}_{part}' if fname in g: got.append(g[fname](g[f'in{day}'])) if len(answers) >= part: assert got[-1] == answers[part - 1], ( f'{fname}(in{day}) got {got[-1]}; expected {answers[part - 1]}') else: got.append(None) return got Number = Union[float, int] Atom = Union[Number, str] Char = str # Type used to indicate a single character cat = ''.join flatten = chain.from_iterable def quantify(iterable, pred=bool) -> int: "Count the number of items in iterable for which pred is true." return sum(1 for item in iterable if pred(item)) def first(iterable, default=None) -> object: "Return first item in iterable, or default." return next(iter(iterable), default) def prod(numbers) -> Number: "The product of an iterable of numbers." return reduce(operator.mul, numbers, 1) def dot(A, B) -> Number: "The dot product of two vectors of numbers." return sum(a * b for a, b in zip(A, B)) def ints(text: str) -> Tuple[int]: "Return a tuple of all the integers in text." return mapt(int, re.findall('-?[0-9]+', text)) def lines(text: str) -> List[str]: "Split the text into a list of lines." return text.strip().splitlines() def mapt(fn, *args): "Do map(fn, *args) and make the result a tuple." return tuple(map(fn, *args)) def atoms(text: str, ignore=r'', sep=None) -> Tuple[Union[int, str]]: "Parse text into atoms separated by sep, with regex ignored." text = re.sub(ignore, '', text) return mapt(atom, text.split(sep)) def atom(text: str, types=(int, str)): "Parse text into one of the given types." for typ in types: try: return typ(text) except ValueError: pass @contextmanager def binding(**kwds): "Bind global variables within a context; revert to old values on exit." old_values = {k: globals()[k] for k in kwds} try: globals().update(kwds) yield # Stuff within the context gets run here. finally: globals().update(old_values) ``` Notes: - Since I'm not even attempting to compete to be among the first 100 people to find a solution, I'll take the time to write docstrings; to use reasonable variable names (not single-letter names); and to give type annotations for most functions (but not the `day` functions, which all return `int`, except `day21_2`). - Traditionally, a lot of AoC problems are solved by one of the following two forms: - `quantify(inputs, P)`: How many of your input items have property P? - `sum(map(F, inputs))`: What is the sum of the result of applying F to each input item? - Some days I will re-use code that was defined on a previous day. - I will give a few tests using `assert`, but far fewer test cases than if I was programming seriously. # Day 1: Report Repair 1. Find the two entries in your expense report (a file of integers) that sum to 2020; what do you get if you multiply them together? 2. In your expense report, what is the product of the three entries that sum to 2020? ``` in1: Set[int] = set(data(1, int)) def day1_1(nums): "Find 2 distinct numbers that sum to 2020, and return their product." return first(x * y for x in nums for y in nums & {2020 - x} if x != y) def day1_2(nums): "Find 3 distinct numbers that sum to 2020, and return their product." return first(x * y * z for x, y in combinations(nums, 2) for z in nums & {2020 - x - y} if x != z != y) do(1, 787776, 262738554) ``` # Day 2: Password Philosophy 1. A password policy is of the form "`1-3 b: cdefg`" meaning that the password must contain 1 to 3 instances of `b`; `cdefg` is invalid under this policy. How many passwords in your input file are valid according to their policies? - JK! The policy actually means that exactly one of positions 1 and 3 (1-based) must contain the letter `b`. How many passwords are valid according to the new interpretation of the policies? ``` Policy = Tuple[int, int, Char, str] def parse_password_policy(line: str) -> Policy: "Given '1-3 b: cdefg', return (1, 3, 'b', 'cdefg')." a, b, L, pw = re.findall(r'[^-:\s]+', line) return (int(a), int(b), L, pw) in2: List[tuple] = data(2, parse_password_policy) def valid_password(policy) -> bool: "Does policy's pw have between a and b instances of letter L?" a, b, L, pw = policy return a <= pw.count(L) <= b def day2_1(policies): return quantify(policies, valid_password) def day2_2(policies): return quantify(policies, valid_password_2) def valid_password_2(policy) -> bool: "Does line's pw have letter L at position a or b (1-based), but not both?" a, b, L, pw = policy return (L == pw[a - 1]) ^ (L == pw[b - 1]) do(2, 383, 272) ``` # Day 3: Toboggan Trajectory The input file is a map of a field that looks like this: ..##....... #...#...#.. .#....#..#. ..#.#...#.# .#...##..#. where each `#` is a tree and the pattern in each row implicitly repeats to the right. We'll call a list of row-strings a *picture*. 1. Starting at the top-left corner of your map and following a slope of down 1 and right 3, how many trees would you encounter? 2. What do you get if you multiply together the number of trees encountered on each of the slopes 1/1, 1/3, 1/5, 1/7, 2/1? ``` Picture = List[str] in3: Picture = data(3) def day3_1(picture, dx=3, dy=1, tree='#'): "How many trees are on the coordinates on the slope dy/dx?" return quantify(row[(dx * y) % len(row)] == tree for y, row in enumerate(picture[::dy])) def day3_2(picture): "What is the product of the number of trees on these five slopes?" def t(dx, dy): return day3_1(picture, dx, dy) return t(1, 1) * t(3, 1) * t(5, 1) * t(7, 1) * t(1, 2) do(3, 167, 736527114) ``` # Day 4: Passport Processing The input is a file of passport data that looks like this (each passport is a series of field:value pairs separated from the next passport by a blank line): ecl:gry pid:860033327 eyr:2020 hcl:#fffffd byr:1937 iyr:2017 cid:147 hgt:183cm hcl:#ae17e1 iyr:2013 eyr:2024 ecl:brn pid:760753108 byr:1931 hgt:179cm 1. Count the number of valid passports &mdash; those that have all seven required fields (`byr, ecl, eyr, hcl, hgt, iyr, pid`). 2. Count the number of valid passports &mdash; those that have valid values for all required fields (see the rules in `valid_fields`). ``` Passport = dict # e.g. {'iyr': '2013', ...} def parse_passport(text: str) -> Passport: "Make a dict of the 'key:val' entries in text." return Passport(re.findall(r'([a-z]+):([^\s]+)', text)) assert parse_passport('''a:1 b:two\nsee:3''') == {'a': '1', 'b': 'two', 'see': '3'} in4: List[Passport] = data(4, parse_passport, '\n\n') # Passports are separated by blank lines required_fields = {'byr', 'ecl', 'eyr', 'hcl', 'hgt', 'iyr', 'pid'} def day4_1(passports): return quantify(passports, required_fields.issubset) def day4_2(passports): return quantify(passports, valid_passport_fields) def valid_passport_fields(passport) -> bool: '''Validate fields according to the following rules: byr (Birth Year) - four digits; at least 1920 and at most 2002. iyr (Issue Year) - four digits; at least 2010 and at most 2020. eyr (Expr. Year) - four digits; at least 2020 and at most 2030. hgt (Height) - a number followed by either cm or in: If cm, the number must be at least 150 and at most 193. If in, the number must be at least 59 and at most 76. hcl (Hair Color) - a '#' followed by exactly six characters 0-9 or a-f. ecl (Eye Color) - exactly one of: amb blu brn gry grn hzl oth. pid (Passport ID) - a nine-digit number, including leading zeroes. cid (Country ID) - ignored, missing or not.''' return all(field in passport and field_validator[field](passport[field]) for field in required_fields) field_validator = dict( byr=lambda v: 1920 <= int(v) <= 2002, iyr=lambda v: 2010 <= int(v) <= 2020, eyr=lambda v: 2020 <= int(v) <= 2030, hcl=lambda v: re.match('#[0-9a-f]{6}$', v), ecl=lambda v: re.match('(amb|blu|brn|gry|grn|hzl|oth)$', v), pid=lambda v: re.match('[0-9]{9}$', v), hgt=lambda v: ((v.endswith('cm') and 150 <= int(v[:-2]) <= 193) or (v.endswith('in') and 59 <= int(v[:-2]) <= 76))) do(4, 237, 172) ``` # Day 5: Binary Boarding The input is a list of boarding passes, such as `'FBFBBFFRLR'`. Each boarding pass corrsponds to a *seat ID* using an encoding where B and F stand for the back and front half of the remaining part of the plane; R and L stand for right and left half of a row. (The encoding is the same as substituting 0 for F or L, and 1 for B or R, and treating the result as a binary number.) 1. What is the highest seat ID on a boarding pass? - What is the one missing seat ID, between the minimum and maximum IDs, that is not on the list of boarding passes? ``` ID = int # A type def seat_id(seat: str, table=str.maketrans('FLBR', '0011')) -> ID: "Treat a seat description as a binary number; convert to int." return ID(seat.translate(table), base=2) assert seat_id('FBFBBFFRLR') == 357 in5: List[ID] = data(5, seat_id) day5_1 = max # Find the maximum seat id. def day5_2(ids): "The one missing seat id." [missing] = set(range(min(ids), max(ids))) - set(ids) return missing do(5, 906, 519) ``` # Day 6: Custom Customs Each passenger fills out a customs form; passengers are arranged in groups. The "yes" answer are recorded; each person on one line, each group separated by a blank line. E.g.: abc ab ac 1. For each group, count the number of questions to which *anyone* answered "yes". What is the sum of those counts? 2. For each group, count the number of questions to which *everyone* answered "yes". What is the sum of those counts? ``` Group = List[str] in6: List[Group] = data(6, lines, sep='\n\n') def day6_1(groups): "For each group, compute the number of letters that ANYONE got. Sum them." return sum(len(set(cat(group))) for group in groups) def day6_2(groups): "For each group, compute the number of letters that EVERYONE got. Sum them." return sum(len(set.intersection(*map(set, group))) for group in groups) do(6, 6530, 3323) ``` # Day 7: Handy Haversacks There are strict luggage processing rules for what color bags must contain what other bags. For example: light red bags contain 1 bright white bag, 2 muted yellow bags. dark orange bags contain 3 bright white bags, 4 muted yellow bags. 1. How many bag colors must eventually contain at least one shiny gold bag? 2. How many individual bags must be inside your single shiny gold bag? I wasn't quite sure, but it turns out that "light red" and "dark red" are different colors. ``` Bag = str BagRules = Dict[Bag, Dict[Bag, int]] # {outer: {inner: count, ...}, ...} def parse_bag_rule(line: str) -> Tuple[Bag, Dict[Bag, int]]: "Return (outer_bag, {inner_bag: num, ...})" line = re.sub(' bags?|[.]', '', line) # Remove redundant info outer, inner = line.split(' contain ') return outer, dict(map(parse_inner, inner.split(', '))) def parse_inner(text) -> Tuple[Bag, int]: "Return the color and number of inner bags." n, bag = text.split(maxsplit=1) return bag, (0 if n == 'no' else int(n)) assert parse_inner('3 muted gray') == ('muted gray', 3) assert (dict([parse_bag_rule("shiny gold bags contain 4 bright blue bags")]) == {'shiny gold': {'bright blue': 4}}) in7: BagRules = dict(data(7, parse_bag_rule)) def day7_1(rules, target='shiny gold'): "How many colors of bags can contain the target color bag?" @lru_cache(None) def contains(bag, target) -> bool: "Does this bag contain the target (perhaps recursively)?" contents = rules.get(bag, {}) return (target in contents or any(contains(inner, target) for inner in contents)) return quantify(contains(bag, target) for bag in rules) def num_contained_in(rules, target='shiny gold') -> int: "How many bags are contained (recursively) in the target bag?" return sum(n + n * num_contained_in(rules, inner) for (inner, n) in rules[target].items() if n > 0) day7_2 = num_contained_in do(7, 103, 1469) ``` # Day 8: Handheld Halting The puzzle input is a program in an assembly language with three instructions: `jmp, acc, nop`. Since there is no conditional branch instruction, a program that executes any instruction twice will infinite loop; terminating programs will execute each instruction at most once. 1. Immediately before any instruction is executed a second time, what value is in the accumulator register? 2. Fix the program so that it terminates normally by changing exactly one jmp to nop or nop to jmp. What is the value of the accumulator register after the program terminates? ``` Instruction = Tuple[str, int] # e.g. ('jmp', +4) Program = List[Instruction] in8: Program = data(8, atoms) def day8_1(program): "Execute the program until it loops; then return accum." pc = accum = 0 executed = set() # Set of instruction addresses executed so far while True: if pc in executed: return accum executed.add(pc) opcode, arg = program[pc] pc += 1 if opcode == 'acc': accum += arg if opcode == 'jmp': pc = pc - 1 + arg ``` I had to think about what to do for Part 2. Do I need to make a flow graph of where the loops are? That sounds hard. But I soon realized that I can just use brute force&mdash;try every alteration of an instruction (there are only 638 instructions and at most one way to alter each instruction), and run each altered program to see if it terminates (that too takes no more than 638 steps each). ``` def day8_2(program): "Return the accumulator from the first altered program that terminates." programs = altered_programs(program) return first(accum for (terminates, accum) in map(run_program, programs) if terminates) def altered_programs(program, other=dict(jmp='nop', nop='jmp')) -> Iterator[Program]: "All ways to swap a nop for a jmp or vice-versa." for i, (opcode, arg) in enumerate(program): if opcode in other: yield [*program[:i], (other[opcode], arg), *program[i + 1:]] def run_program(program) -> Tuple[bool, int]: "Run the program until it loops or terminates; return (terminates, accum)" pc = accum = 0 executed = set() # Set of instruction addresses executed so far while 0 <= pc < len(program): if pc in executed: return False, accum # program loops executed.add(pc) opcode, arg = program[pc] pc += 1 if opcode == 'acc': accum += arg if opcode == 'jmp': pc = pc - 1 + arg return True, accum # program terminates do(8, 1521, 1016) ``` # Day 9: Encoding Error Given a list of numbers: 1. Find the first number in the list (after the preamble of 25 numbers) which is not the sum of two of the 25 numbers before it. 2. Find a contiguous subsequence of numbers in your list which sum to the number from step 1; add the smallest and largest numbers in this subsequence. I could do this efficiently in $O(n)$ as in Day 1, but $n$ is so small I'll just use brute force. ``` in9: List[int] = data(9, int) def day9_1(nums, p=25): """Find the first number in the list of numbers (after a preamble of p=25 numbers) which is not the sum of two of the p numbers before it.""" return first(x for i, x in enumerate(nums) if i > p and x not in twosums(nums[i-p:i])) def twosums(nums): return map(sum, combinations(nums, 2)) def day9_2(nums, target=day9_1(in9)): "Find a contiguous subsequence of nums that sums to target; add their max and min." subseq = find_subseq(nums, target) return max(subseq) + min(subseq) def find_subseq(nums, target) -> Optional[deque]: "Find a contiguous subsequence of nums that sums to target." subseq = deque() total = 0 for x in nums: if total < target: subseq.append(x) total += x if total == target and len(subseq) >= 2: return subseq while total > target: total -= subseq.popleft() return None do(9, 776203571, 104800569) ``` # Day 10: Adapter Array You are given a bunch of *joltage adapters*, each with a listed joltage output; each can take an input source that is 1, 2, or 3 jolts lower than the output. There is a charging outlet rated 0 jolts, and you want to chargwe a device that is 3 jolts higher than the maximum adapter. 1. Find a chain that uses all of your adapters to connect the charging outlet to your device's built-in adapter and count the joltage differences between the charging outlet, the adapters, and your device. What is the number of 1-jolt differences multiplied by the number of 3-jolt differences? 2. What is the total number of distinct ways you can arrange the adapters to connect the charging outlet to your device? Note: at first I thought this was a search problem. But then I realized that the only possibility is to increase joltage from source to adapter, so that means the adapters must appear in sorted order. For part 2, some adapters can be left out. ``` in10: List[int] = data(10, int) # Input is the joltage of each adapter def day10_1(jolts): """Arrange the joltages in order; count the number of each size difference; return the product of 1- and 3-jolt differences.""" jolts = [0] + sorted(jolts) + [max(jolts) + 3] diffs = Counter(jolts[i + 1] - jolts[i] for i in range(len(jolts) - 1)) assert {1, 2, 3}.issuperset(diffs) return diffs[1] * diffs[3] def day10_2(jolts): return arrangements(tuple(sorted(jolts)), 0) @lru_cache(None) def arrangements(jolts, prev) -> int: "The number of arrangements that go from prev to the end of `jolts`." first, rest = jolts[0], jolts[1:] if first - prev > 3: return 0 elif not rest: return 1 else: return (arrangements(rest, first) + # Use first arrangements(rest, prev)) # Skip first assert arrangements((3, 6, 9, 12), 0) == 1 assert arrangements((3, 6, 9, 13), 0) == 0 assert arrangements((1, 2, 3, 4), 0) == 7 do(10, 2346, 6044831973376) ``` # Day 11: Seating System This is a version of Conway's *Life*, except that: - The world is bounded, not infinite. - Cells (seats) have three states, not two: *floor* as well as the traditional *occupied* and *empty*. - The rules for what changes between occupied and empty in the next generation are different: - If a seat is empty (`L`) and there are no occupied seats adjacent to it, the seat becomes occupied. - If a seat is occupied (`#`) and four or more seats adjacent to it are also occupied, the seat becomes empty. - Otherwise, the seat's state does not change. 1. Simulate your seating area by applying the seating rules repeatedly until no seats change state. How many seats end up occupied? 2. Same problem, but with two rule changes: - When considering adjacency, if there is a *floor* cell in some direction, skip over that to the next visible seat in that direction. - A seat becomes empty only when there are 5 occupied neighbors, not 4. ``` in11: List[str] = data(11) floor, empty, occupied, off = ".L#?" Contents = Char # The contents of each location is one of the above 4 characters class Layout(list): "A layout of seats (occupied or not) and floor space." crowded = 4 deltas = ((-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, +1), (0, +1), (1, +1)) def next_generation(self) -> Layout: "The next generation, according to the rules." seats = (cat(self.next_generation_at(x, y) for x in range(len(self[y]))) for y in range(len(self))) return type(self)(seats) def next_generation_at(self, x, y) -> Contents: "The contents of location (x, y) in the next generation." old = self[y][x] N = self.neighbors(x, y).count(occupied) return (occupied if old is empty and N == 0 else empty if old is occupied and N >= self.crowded else old) def neighbors(self, x, y) -> List[Contents]: "The contents of the 8 neighboring locations." return [self.at(x + dx, y + dy) for dx, dy in self.deltas] def count(self, kind: Contents) -> int: return cat(self).count(kind) def at(self, x, y) -> Contents: "The contents of location (x, y): empty, occupied, floor, or off?" if 0 <= y < len(self) and 0 <= x < len(self[y]): return self[y][x] else: return off def run(self) -> Layout: "Run until equilibrium." new = self while True: new, old = new.next_generation(), new if new == old: return new def day11_1(seats): return Layout(seats).run().count(occupied) def day11_2(seats): return Layout2(seats).run().count(occupied) class Layout2(Layout): "A layout of seats (occupied or not) and floor space, with new rules." crowded = 5 def neighbors(self, x, y) -> List[Contents]: "The contents of the nearest visible seat in each of the 8 directions." return [self.visible(x, dx, y, dy) for dx, dy in self.deltas] def visible(self, x, dx, y, dy) -> Contents: "The contents of the first visible seat in direction (dx, dy)." for i in range(1, sys.maxsize): x += dx; y += dy if not (0 <= y < len(self) and 0 <= x < len(self[y])): return off if self[y][x] is not floor: return self[y][x] do(11, 2299, 2047) ``` I have to confess that I "cheated" here: after seeing the problem description for Part 2, I went back and refactored the code for Part 1 in two places: - `Layout`: Introduced the `crowded` attribute; it had been an inline literal `4`. Also made `deltas` an attribute, not a global constant. - `next_generation`: Changed `Layout(seats)` to `type(self)(seats)`. There was more refactoring and less reuse in Part 2 than I would have liked, but I don't feel like I made bad choices in Part 1. # Day 12: Rain Risk Another problem involving interpreting a kind of assembly language, with navigation instructions for a ship. 1. Figure out where the navigation instructions lead. What is the Manhattan distance between that location and the ship's starting position? 2. Figure out where the navigation instructions *actually* lead, with the updated interpretation. What is the Manhattan distance between that location and the ship's starting position? The difference between Part 1 and Part 2 comes down to the initial value of the heading/waypoint, and whether the N/E/W/S commands alter the location or the waypoint. Everything else is the same between the two parts. ``` in12: List[Instruction] = data(12, lambda line: (line[0], int(line[1:]))) Point = Heading = Tuple[int, int] directions = dict(N=(0, 1), E=(1, 0), S=(0, -1), W=(-1, 0)) def navigate(instructions, loc=(0, 0), heading=directions['E']) -> Point: "Follow instructions to change ship's loc and heading; return final loc." for op, n in instructions: if op == 'R': heading = turn(n, *heading) elif op == 'L': heading = turn(-n, *heading) elif op == 'F': loc = go(n, *loc, *heading) else: loc = go(n, *loc, *directions[op]) return loc def turn(degrees, x, y) -> Heading: "Turn `degrees` from the current (x, y) heading." return (x, y) if degrees % 360 == 0 else turn(degrees - 90, y, -x) def go(n, x, y, dx, dy) -> Point: "Go n steps in the (dx, dy) direction from (x, y)." return (x + n * dx, y + n * dy) def manhatten_distance(point) -> int: return sum(map(abs, point)) def day12_1(instructions): return manhatten_distance(navigate(instructions)) def navigate2(instructions, loc=(0, 0), way=(10, 1)) -> Point: "Follow updated instructions to change ship's loc and waypoint; return final loc." for op, n in instructions: if op == 'R': way = turn(n, *way) elif op == 'L': way = turn(-n, *way) elif op == 'F': loc = go(n, *loc, *way) else: way = go(n, *way, *directions[op]) return loc def day12_2(instructions): return manhatten_distance(navigate2(instructions)) do(12, 439, 12385) ``` # Day 13: Shuttle Search A bus with ID *d* leaves the terminal at times 0, *d*, 2*d*, 3*d*, ... You are given bus IDs and an earliest time you can leave. 1. What is the ID of the earliest bus you can take, multiplied by the number of minutes you'll need to wait for that bus? 2. What is the earliest timestamp such that all of the listed bus IDs depart at offsets matching their positions in the list? ``` x = 0 in13: Tuple[ID] = (29,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,41,x,x,x,x,x,x,x,x,x,577, x,x,x,x,x,x,x,x,x,x,x,x,13,17,x,x,x,x,19,x,x,x,23,x,x,x,x,x,x,x,601,x,x,x,x,x, x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,37) def day13_1(ids, start=1000001): "Find the id of the earliest bus after start; return id * wait." ids = set(ids) - {x} id = min(ids, key=lambda id: wait(id, start)) return id * wait(id, start) def wait(id, t): "How long you have to wait from t for bus id." return 0 if t % id == 0 else id - t % id ``` Here's a brute-force solution for Part 2 that works for the simple test cases: ``` def day13_2(ids): "Find the time where all the buses arrive at the right offsets." schedule = {t: id for t, id in enumerate(ids) if id != x} step = schedule[0] return first(t for t in range(0, sys.maxsize, step) if all(wait(schedule[i], t) == i for i in schedule)) assert day13_2((7,13,x,x,59,x,31,19)) == 1068781 assert day13_2((1789,37,47,1889)) == 1202161486 ``` However, it is clear this will be too slow for the real input data. Instead of looking at every multiple of the first number, I'll incrementally update the `step` as we go through the numbers. Out of all the puzzles so far, this is the one I had to think most carefully about. For each bus id, we want to find a time where we get that id right, then step the time by a multiple of all the ids encountered so far: ``` def day13_2(ids): "Find the time where all the buses arrive at the right offsets." time = 0 step = 1 schedule = {t: id for t, id in enumerate(ids) if id != x} for t in schedule: while wait(schedule[t], time + t): time += step step *= schedule[t] return time do(13, 174, 780601154795940) ``` # Day 14: Docking Data Another "interpret assembly code" puzzle, with two different versions of the instructions (which I won't describe here). 1. Execute the initialization program. What is the sum of all values left in memory after it completes? 2. Execute the initialization program using an emulator for a version 2 decoder chip. What is the sum of all values left in memory after it completes? A *mask* is a bit string but with three possible values at each position, `01X`. I could make it into two bitstrings, but I choose to leave it as a `str`. ``` def parse_docking(line: str) -> tuple: "Parse 'mask = XX10' to ('mask', 'XX10') and 'mem[8] = 11' to (8, 11)" if line.startswith('mask'): return ('mask', line.split()[-1]) else: return ints(line) in14 = data(14, parse_docking) Memory = Dict[int, int] def run_docking(program) -> Memory: "Execute the program and return memory." mask = bin36(0) mem = defaultdict(int) for addr, val in program: if addr == 'mask': mask = val else: mem[addr] = int(cat(m if m in '01' else v for m, v in zip(mask, bin36(val))), base=2) return mem def bin36(i) -> str: return f'{i:036b}' assert bin36(255 + 2 ** 20) == '000000000000000100000000000011111111' def day14_1(program): return sum(run_docking(program).values()) def day14_2(program): return sum(run_docking2(program).values()) def run_docking2(program) -> Memory: "Execute the program using version 2 instructions and return memory." mask = bin36(0) mem = defaultdict(int) for addr, val in program: if addr == 'mask': mask = val else: addr = cat(a if m == '0' else '1' if m == '1' else '{}' for m, a in zip(mask, bin36(addr))) for bits in product('01', repeat=addr.count('{')): mem[int(addr.format(*bits), base=2)] = val return mem do(14, 11884151942312, 2625449018811) ``` # Day 15: Rambunctious Recitation This puzzle involves a game where players speak a new number each turn, based on previous numbers. 1. Given your starting numbers, what will be the 2020th number spoken? 2. Given your starting numbers, what will be the 30,000,000th number spoken? ``` in15 = 10,16,6,0,1,17 def day15_1(starting: Tuple[int], nth=2020) -> int: "Return the nth (1-based) number spoken." last = starting[-1] # `spoken` is a mapping of {number: turn_when_last_spoken} spoken = defaultdict(int, {n: t for t, n in enumerate(starting[:-1])}) for t in range(len(starting), nth): new = 0 if last not in spoken else t - 1 - spoken[last] spoken[last] = t - 1 last = new return last assert day15_1((0, 3, 6), 2020) == 436 ``` Part 2 involves no changes, but asks for the 30 millionth number. If it had been 3 million, I'd think "no problem!" If it had been 30 billion, I'd think "I need a more efficient solution!" As it is, I'll run it and see how long it takes: ``` def day15_2(starting): return day15_1(starting, nth=30_000_000) %time do(15, 412, 243) ``` That's reasonable; I won't bother trying to find a more efficient approach. # Day 16: Ticket Translation The input to this puzzle has three parts: some rules for valid fields; your ticket; and a set of nearby tickets. The puzzle is to figure out what field number corresponds to what field name (class, row, seat, etc.). The input looks like: class: 1-3 or 5-7 row: 6-11 or 33-44 your ticket: 7,1,14 nearby tickets: 7,3,47 40,4,50 1. Consider the validity of the nearby tickets you scanned. What is the sum of the values that are are not valid for any field? 2. Discard invalid tickets. Use the remaining valid tickets to determine which field is which. Look for the six fields on your ticket that start with the word departure. What do you get if you multiply those six values together? First parse the input file, introducing the class `TicketData` to hold the three parts of the input file (the fields, your ticket, and nearby tickets), and the class `Sets` for a tuple of ranges or other set-like objects, so that we can easily test a number is an element of any one of a number of possibilities. For Part 1, just go through the ticket values and see which values are not in any range. ``` TicketData = namedtuple('TicketData', 'fields, your, nearby') Ticket = ints # A ticket is a tuple of ints class Sets(tuple): "A tuple of set-like objects (such as ranges); supports `in`." def __contains__(self, item): return any(item in s for s in self) def parse_ticket_sections(fieldstr: str, your: str, nearby: str) -> TicketData: return TicketData(fields=dict(map(parse_ticket_line, fieldstr)), your=Ticket(your[1]), nearby=[Ticket(line) for line in nearby[1:]]) def parse_ticket_line(line: str) -> Tuple[str, Sets]: "Parse 'row: 10-20 or 30-40' to ('row', Sets((range(10, 21), range(30, 41))))." field = line.split(':')[0] a, b, c, d = ints(line.replace('-', ' ')) return field, Sets((range(a, b + 1), range(c, d + 1))) in16 = parse_ticket_sections(*data(16, lines, sep='\n\n')) def day16_1(ticket_data): "The sum of the invalid entries in the nearby tickets." ranges = Sets(ticket_data.fields.values()) return sum(v for ticket in ticket_data.nearby for v in ticket if v not in ranges) ``` For part 2, we're playing a simplified variant of Sudoku: - First find the valid tickets. - Then start with the assumption that any field name is `possible` for any index number in the tickets. - Determine what field names are invalid for what ticket index numbers. - Remove the field name from the possibilities for that index, and - If there is only one possible field name left, then remove it from all other index positions. ``` def valid_ticket(ticket, ranges) -> bool: return all(v in ranges for v in ticket) def decode_tickets(ticket_data) -> Dict[str, int]: "Return a mapping of {field_name: field_number} (index into ticket)." fields, your, nearby = ticket_data ranges = Sets(ticket_data.fields.values()) valid = [t for t in nearby + [your] if valid_ticket(t, ranges)] possible = {i: set(fields) for i in range(len(your))} while any(len(possible[i]) > 1 for i in possible): for field_name, i in invalid_fields(valid, fields): possible[i] -= {field_name} if len(possible[i]) == 1: eliminate_others(possible, i) return {field: i for i, [field] in possible.items()} def invalid_fields(valid, fields) -> Iterable[Tuple[str, int]]: "Yield (field_name, field_number) for all invalid fields." return ((field_name, i) for ticket in valid for i in range(len(ticket)) for field_name in fields if ticket[i] not in fields[field_name]) def eliminate_others(possible, i): "Eliminate possible[i] from all other possible[j]." for j in possible: if j != i: possible[j] -= possible[i] def day16_2(ticket_data): "The product of the 6 fields that start with 'departure'." code = decode_tickets(ticket_data) return prod(ticket_data.your[code[field]] for field in code if field.startswith('departure')) do(16, 21071, 3429967441937) ``` # Day 17: Conway Cubes Now we are explicitly playing *Life*, but in three dimensions, not two. I've coded this before; I'll adapt my [old version](Life.ipynb) to three dimensions (actually, make it `d` dimensions in general). My implementation represents a generation as the set of active cell coordinates. 1. Starting with your given initial configuration, simulate six cycles. How many cubes are left in the active state after the sixth cycle? 2. Simulate six cycles in a 4-dimensional space. How many cubes are left in the active state after the sixth cycle? ``` in17: Picture = lines(''' ##.#.... ...#...# .#.#.##. ..#.#... .###.... .##.#... #.##..## #.####.. ''') Cell = Tuple[int,...] def day17_1(picture, d=3, n=6): "How many cells are active in the nth generation?" return len(life(parse_cells(picture, d), n)) def parse_cells(picture, d=3, active='#') -> Set[Cell]: "Convert a 2-d picture into a set of d-dimensional active cells." return {(x, y, *(0,) * (d - 2)) for (y, row) in enumerate(picture) for x, cell in enumerate(row) if cell is active} def life(cells, n) -> Set[Cell]: "Play n generations of Life." for g in range(n): cells = next_generation(cells) return cells def next_generation(cells) -> Set[Cell]: """The set of live cells in the next generation.""" return {cell for cell, count in neighbor_counts(cells).items() if count == 3 or (count == 2 and cell in cells)} @lru_cache() def cell_deltas(d: int): return set(filter(any, product((-1, 0, +1), repeat=d))) def neighbor_counts(cells) -> Dict[Cell, int]: """A Counter of the number of live neighbors for each cell.""" return Counter(flatten(map(neighbors, cells))) def neighbors(cell) -> List[cell]: "All adjacent neighbors of cell in three dimensions." return [tuple(map(operator.add, cell, delta)) for delta in cell_deltas(len(cell))] def day17_2(picture): return day17_1(picture, d=4) do(17, 291, 1524) ``` # Day 18: Operation Order At first I thought I could just apply `eval` to each line, but alas, the operation order is non-standard. 1. All operations are done left-to-right. Evaluate the expression on each line of the homework; what is the sum of the resulting values? 2. Addition is done before multiplication. What do you get if you add up the results of evaluating the homework problems using these new rules? ``` def parse_expr(line) -> tuple: "Parse an expression: '2 + 3 * 4' => (2, '+', 3, '*', 4)." return ast.literal_eval(re.sub('([+*])', r",'\1',", line)) in18 = data(18, parse_expr) operators = {'+': operator.add, '*': operator.mul} def evaluate(expr) -> int: "Evaluate an expression under left-to-right rules." if isinstance(expr, int): return expr else: a, op, b, *rest = expr x = operators[op](evaluate(a), evaluate(b)) return x if not rest else evaluate((x, *rest)) def day18_1(exprs): return sum(map(evaluate, exprs)) def evaluate2(expr) -> int: "Evaluate an expression under addition-first rules." if isinstance(expr, int): return expr elif '*' in expr: i = expr.index('*') return evaluate2(expr[:i]) * evaluate2(expr[i + 1:]) else: return sum(evaluate2(x) for x in expr if x is not '+') def day18_2(exprs): return sum(map(evaluate2, exprs)) do(18, 3885386961962, 112899558798666) ``` # Day 19 A grep-like pattern matcher, where a *message* is a sequence of characters (all `'a'` or `'b'`) and a *pattern* I will represent as a list of items, where each item can be a character, a rule number (which is associated with a pattern), or a *choice* of two or more patterns. The input has two sections: first "rule number: pattern" lines, then messages, one per line. I will define `match` to return the remaining string in the message if part or all of the message is matched, or `None` if it fails. 1. How many messages completely match rule 0? 2. Two of the rules are wrong. After updating rules 8 and 11, how many messages completely match rule 0? ``` Message = str # A string we are trying to match, e.g. "ababba" Choice = tuple # A choice of any of the elements, e.g. Choice(([5, 6], [7])) Pattern = List[Union[Char, int, Choice]] def parse_messages(rules, messages) -> Tuple[Dict[int, Pattern], List[Message]]: "Return a dict of {rule_number: pattern} and a list of messages." return dict(map(parse_rule, rules)), messages def parse_rule(line): "Parse '1: 2 3' => (1, [2, 3]); '4: 5, 6 | 7' => (4, Choice(([5, 6], [7])))." n, *rhs = atoms(line.replace(':', ' ').replace('"', ' ')) if '|' in rhs: i = rhs.index('|') rhs = [Choice((rhs[:i], rhs[i + 1:]))] return n, rhs in19 = parse_messages(*data(19, lines, sep='\n\n')) def day19_1(inputs): "How many messages completely match rule 0?" rules, messages = inputs return quantify(match(rules[0], msg, rules) == '' for msg in messages) def match(pat, msg, rules) -> Optional[Message]: "If a prefix of msg matches pat, return remaining str; else None" if pat and not msg: # Failed to match whole pat return None elif not pat: # Matched whole pat return msg elif pat[0] == msg[0]: # Matched first char; continue return match(pat[1:], msg[1:], rules) elif isinstance(pat[0], int): # Look up the rule number return match(rules[pat[0]] + pat[1:], msg, rules) elif isinstance(pat[0], Choice): # Match any of the choices for choice in pat[0]: m = match(choice + pat[1:], msg, rules) if m is not None: return m return None ``` For part 2, I coded the two changed rules by hand, taking care to avoid infinite left-recursion: ``` def day19_2(inputs): "How many messages completely match rule 0, with new rules 8 and 11?" rules, messages = inputs rules2 = {**rules, 8: [42, maybe(8)], 11: [42, maybe(11), 31]} return day19_1((rules2, messages)) def maybe(n): return Choice(([], [n])) do(19, 190, 311) ``` # Day 20: Jurassic Jigsaw You are given a bunch of picture tiles, which can be put together to form a larger picture, where the edges of tiles match their neighbors. 1. Assemble the tiles into an image. What do you get if you multiply together the IDs of the four corner tiles? 2. In the assembled image, how many `#` pixels are not part of a sea monster (which is a specific shape)? ``` def jigsaw_tiles(sections: List[List[str]]) -> Dict[ID, Picture]: "Return a dict of {tile_id: tile_picture}." return {first(ints(header)): tile for (header, *tile) in sections} in20 = jigsaw_tiles(data(20, lines, sep='\n\n')) ``` For Part 1, I can find the corners without knowing where all the other tiles go. It is guaranteed that "the outermost edges won't line up with any other tiles," but all the inside edges will. We'll define `edge_count` to count how many times an edge appears on any tile (using a `canonical` orientation, because tiles might be flipped). Then the corner tiles are ones that have two edges that have an edge count of 1. ``` Edge = str def day20_1(tiles: Dict[ID, Picture]): "The product of the ID's of the 4 corner tiles." edge_count = Counter(canonical(e) for id in tiles for e in edges(tiles[id])) is_outermost = lambda edge: edge_count[canonical(edge)] == 1 is_corner = lambda tile: quantify(edges(tile), is_outermost) == 2 corners = [id for id in tiles if is_corner(tiles[id])] return prod(corners) def edges(tile) -> Iterable[Edge]: "The 4 edges of a tile." for i in (0, -1): yield tile[i] # top/bottom yield cat(row[i] for row in tile) # left/right def canonical(edge) -> Edge: return min(edge, edge[::-1]) do(20, 15670959891893) ``` Family holiday preparations kept me from doing **Part 2** on the night it was released, and unfortunately I didn't feel like coming back to it later: it seemed too tedious for too little reward. I thought it was inelegant that a solid block of `#` pixels would be considered a sea monster with waves. # Day 21: Allergen Assessment This is another Sudoku-like problem, similar to Day 16, involving ingredients and allergens. Crucially, each allergen is found in exactly one ingredient, but a food may not list every allergen. I can reuse the function `eliminate_others`, but the rest I need to define here. `day21_2` is the only `day` function that does not return an `int`. 1. Determine which ingredients cannot possibly contain any of the allergens in your list. How many times do any of those ingredients appear? 2. What is your canonical dangerous ingredient list? ``` Ingredient = str Allergen = str Food = namedtuple('Food', 'I, A') # I for set of ingredients; A for set of allergens def parse_food(line) -> Food: "Parse 'xtc wkrp (contains fish, nuts)' => Food({'xtc', 'wkrp'}, {'fish', 'nuts'})" ingredients, allergens = line.split('(contains') return Food(set(atoms(ingredients)), set(atoms(allergens, ignore='[,)]'))) in21 = data(21, parse_food) def day21_1(foods): "How many times does an ingredient with an allergen appear?" bad = bad_ingredients(foods) allergens = set(flatten(bad.values())) return sum(len(food.I - allergens) for food in foods) def bad_ingredients(foods) -> Dict[Allergen, Set[Ingredient]]: "A dict of {allergen: {set_of_ingredients_it_could_be}}; each set should have len 1." all_I = set(flatten(food.I for food in foods)) all_A = set(flatten(food.A for food in foods)) possible = {a: set(all_I) for a in all_A} while any(len(possible[a]) > 1 for a in possible): for food in foods: for a in food.A: possible[a] &= food.I if len(possible[a]) == 1: eliminate_others(possible, a) return possible def day21_2(foods) -> str: "What are the bad ingredients, sorted by the allergen name that contains them?" bad = bad_ingredients(in21) return ','.join(first(bad[a]) for a in sorted(bad)) do(21, 2282, 'vrzkz,zjsh,hphcb,mbdksj,vzzxl,ctmzsr,rkzqs,zmhnj') ``` # Day 22: Crab Combat Part 1 is the card game *War* (here called *Combat*) with no ties. Part 2 is a more complex recursive version of the game. 1. Play a game of Combat using the two decks you just dealt. What is the winning player's score? 2. Play a game of Recursive Combat. What is the winning player's score? Each player holds a *deal* of cards, which I will represent as a `deque` so I can deal from the top and add cards to the bottom. ``` Deal = Union[tuple, deque] # Cards are a tuple on input; a deque internally Deals = Tuple[Deal, Deal] # Cards are split into two piles for the two players. in22: Deals = ( (12,40,50,4,24,15,22,43,18,21,2,42,27,36,6,31,35,20,32,1,41,14,9,44,8), (30,10,47,29,13,11,49,7,25,37,33,48,16,5,45,19,17,26,46,23,34,39,28,3,38)) def day22_1(deals): return combat_score(combat(deals)) def combat(deals: Deals) -> Deals: "Given two deals, play Combat and return the final deals (one of which will be empty)." deals = mapt(deque, deals) while all(deals): topcards = mapt(deque.popleft, deals) winner = 0 if topcards[0] > topcards[1] else 1 deals[winner].extend(sorted(topcards, reverse=True)) return deals def combat_score(deals: Deals) -> int: "The winner's cards, each multiplied by their reverse index number, and summed." winning = deals[0] or deals[1] return dot(winning, range(len(winning), 0, -1)) def day22_2(deals): return combat_score(recursive_combat(deals)) def recursive_combat(deals: Deals) -> Deals: "A game of Recursive Combat." deals = mapt(deque, deals) previously = set() while all(deals): if seen(deals, previously): return (deals[0], ()) topcards = mapt(deque.popleft, deals) if all(len(deals[p]) >= topcards[p] for p in (0, 1)): deals2 = [tuple(deals[p])[:topcards[p]] for p in (0, 1)] result = recursive_combat(deals2) winner = 0 if result[0] else 1 else: winner = 0 if topcards[0] > topcards[1] else 1 deals[winner].extend([topcards[winner], topcards[1 - winner]]) return deals def seen(deals, previously) -> bool: "Return True if we have seen this pair of deals previously; else just remember it." hasht = mapt(tuple, deals) if hasht in previously: return True else: previously.add(hasht) return False do(22, 31809, 32835) ``` # Day 23: Crab Cups A game involving moving around some cups that are labelled with positive integers. 1. Using your labeling, simulate 100 moves. What are the labels on the cups after cup 1? 2. With 1 million cups and 10 million moves, determine which two cups will end up immediately clockwise of cup 1. What do you get if you multiply their labels together? ``` in23 = '872495136' Cup = int # The label on a cup (not the index of the cup in the list of cups) def day23_1(cupstr: str, n=100): "Return the int representing the cups, in order, after cup 1; resulting from n moves." cups = list(map(int, cupstr)) current = cups[0] for i in range(n): picked = pickup(cups, current) dest = destination(cups, current) place(cups, picked, dest) current = clockwise(cups, current) return after(1, cups) def pickup(cups, current) -> List[Cup]: "Return the 3 cups clockwise of current; remove them from cups." i = cups.index(current) picked, cups[i+1:i+4] = cups[i+1:i+4], [] extra = 3 - len(picked) if extra: picked += cups[:extra] cups[:extra] = [] return picked def destination(cups, current) -> Cup: "The cup with label one less than current, or max(cups)." return max((c for c in cups if c < current), default=max(cups)) def clockwise(cups, current) -> Cup: "The cup one clockwise of current." return cups[(cups.index(current) + 1) % len(cups)] def place(cups, picked, dest): "Put `picked` after `dest`" i = cups.index(dest) + 1 cups[i:i] = picked def after(cup, cups) -> int: "All the cups after `cup`, in order." i = cups.index(cup) + 1 string = cat(map(str, cups + cups)) return int(string[i:i+len(cups)]) do(23, 278659341) ``` For Part 1, I aimed to be very explicit in my code, and the solution works fine for 9 cups and 100 moves (although it did end up being more lines of code than I wanted/expected). However, my approach would not be efficient enough to do Part 2; thus it was a poor choice. For now I'll skip Part 2; maybe I'll come back to it later. I had an idea for a representation where each entry in `cups` is either a `list` or a `range` of cups; that way we are only breaking up and/or shifting small lists, not million-element lists. # Day 24: Lobby Layout This puzzle involves a hexagonal grid. The input is a list of directions to follow to identify a destination hex tile that should be flipped from white to black. I recall that Amit Patel of Red Blob Games has [covered hex grids topic thoroughly](https://www.redblobgames.com/grids/hexagons/); I followed his recommendation to use a (pointy) **axial coordinate** system. 1. Go through the renovation crew's list and determine which tiles they need to flip. After all of the instructions have been followed, how many tiles are left with the black side up? 2. Another version of *Life*, but on a hex grid, where a tile is live (black) if it was white and has two black neighbors, or it was black and has 1 or 2 black neighbors. How many tiles will be black after 100 days (generations)? ``` in24 = data(24) def day24_1(lines: List[str]): "How many tiles are flipped an odd number of times?" counts = Counter(map(follow_hex, lines)) return quantify(counts[tile] % 2 for tile in counts) hexdirs = dict(e=(1, 0), w=(-1, 0), ne=(1, -1), sw=(-1, 1), se=(0, 1), nw=(0, -1)) def parse_hex(line) -> List[str]: return re.findall('e|w|ne|sw|se|nw', line) def follow_hex(directions: str): "What (x, y) location do you end up at after following directions?" x, y = 0, 0 for dir in parse_hex(directions): dx, dy = hexdirs[dir] x += dx y += dy return (x, y) assert parse_hex('wsweesene') == ['w', 'sw', 'e', 'e', 'se', 'ne'] assert follow_hex('eeew') == (2, 0) ``` I'll use `binding` to temporarily redefine `next_generation` and `cell_deltas` to work with this problem; then call `life`. ``` def day24_2(lines: List[str], days=100): "How many tiles are black after 100 days of Life?" counts = Counter(map(follow_hex, lines)) blacks = {tile for tile in counts if counts[tile] % 2} with binding(next_generation=next_generation24, cell_deltas=cell_deltas24): return len(life(blacks, 100)) def next_generation24(cells) -> Set[Cell]: "The set of live cells in the next generation." counts = neighbor_counts(cells) return ({c for c in cells if counts[c] in (1, 2)} | {c for c in counts if c not in cells and counts[c] == 2}) @lru_cache() def cell_deltas24(d) -> Iterable[Cell]: "The neighbors are the 6 surrounding hex squares." return hexdirs.values() do(24, 420, 4206) ``` # Day 25: Combo Breaker This puzzle involves breaking a cryptographic protocol (whose details I won't describe here). 1. What encryption key is the handshake trying to establish? 2. The last rule of AoC: there is no Part 2 for Day 25. ``` in25 = 1965712, 19072108 def transform(subj) -> Iterator[int]: "A stream of transformed values, according to the protocol." val = 1 while True: val = (val * subj) % 20201227 yield val def day25_1(keys): "Find the loopsize for the first key; transform the other key that number of times." loopsize = first(i for i, val in enumerate(transform(7)) if val == keys[0]) return first(val for i, val in enumerate(transform(keys[1])) if i == loopsize) do(25, 16881444) ``` # Postmortem: Timing Advent of Code suggests that each day's puzzle should run in [15 seconds or less](https://adventofcode.com/2020/about). I met that goal, with days 11 and 15 taking about 8 seconds each, days 22 and 25 about 2 seconds, and the average under a second per day. (However, I skipped Part 2 on days 20 and 23.) Here's a report, with stars in the first column indicating run times on a log scale: 0 stars for under 1/100 seconds up to 4 stars for over 10 seconds: ``` import time def timing(days=range(1, 26)): "Report on timing of `do(day)` for all days." print(' Day Secs. Answers') print(' === ===== =======') for day in days: t0 = time.time() answers = do(day) t = time.time() - t0 if answers != [None, None]: stars = '*' * int(3 + math.log(t, 10)) print(f'{stars:>4} {day:2} {t:6.3f} {answers}') %time timing() ```
github_jupyter
# ENEM 2016 ### Desafio da semana: prever o valor da nota de matemática para os inscritos no ENEM 2016. ## Bibliotecas ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from sklearn import metrics from sklearn.preprocessing import StandardScaler from sklearn.ensemble import RandomForestRegressor plt.style.use('grayscale') ``` ## Correlações ``` df_train = pd.read_csv('train.csv', sep="," , encoding="UTF8" ) df_test = pd.read_csv('test.csv', sep="," , encoding="UTF8" ) df_resposta = pd.DataFrame() print(set(df_test.columns).issubset(set(df_train.columns))) df_train.corr() df_train.head() df_test.head() ``` ## Dados ``` features_train = [ 'NU_NOTA_MT', 'NU_NOTA_CN', 'NU_NOTA_CH', 'NU_NOTA_LC', 'NU_NOTA_REDACAO', 'NU_NOTA_COMP1', 'NU_NOTA_COMP2', 'NU_NOTA_COMP3', 'NU_NOTA_COMP4', 'NU_NOTA_COMP5'] features_test = [ 'NU_NOTA_CN', 'NU_NOTA_CH', 'NU_NOTA_LC', 'NU_NOTA_REDACAO', 'NU_NOTA_COMP1', 'NU_NOTA_COMP2', 'NU_NOTA_COMP3', 'NU_NOTA_COMP4', 'NU_NOTA_COMP5'] ``` ## Graficos ``` %matplotlib inline corr = df_train[features_train].corr() plt.subplots(figsize=(11, 8)) sns.heatmap(corr, annot=True, annot_kws={"size": 15}, linecolor='black', cmap='Greens') df_test[features_test].isnull().sum() df_test = df_test.loc[ (df_test['NU_NOTA_CN'].notnull()) & (df_test['NU_NOTA_CH'].notnull()) & (df_test['NU_NOTA_LC'].notnull()) & (df_test['NU_NOTA_REDACAO'].notnull()) ] df_train = df_train.loc[ (df_train['NU_NOTA_CN'].notnull()) & (df_train['NU_NOTA_CH'].notnull()) & (df_train['NU_NOTA_LC'].notnull()) & (df_train['NU_NOTA_MT'].notnull()) & (df_train['NU_NOTA_REDACAO'].notnull()) ] df_test[features_test].isnull().sum() ``` ## Usando sklearn ``` y_train = df_train['NU_NOTA_MT'] x_train = df_train[features_test] x_test = df_test[features_test] sc = StandardScaler() x_train = sc.fit_transform(x_train) x_test = sc.transform(x_test) ``` ## Usando o RandomForestRegressor ``` regressor = RandomForestRegressor( criterion='mae', max_depth=8, max_leaf_nodes=None, min_impurity_split=None, min_samples_leaf=1, min_samples_split=2, min_weight_fraction_leaf=0.0, n_estimators= 500, n_jobs=-1, random_state=0, verbose=0, warm_start=False ) ``` ## realizando treino através do fit ``` regressor.fit(x_train, y_train) ``` ## Resultados ``` y_pred_test = regressor.predict(x_test) df_resposta['NU_INSCRICAO'] = df_test['NU_INSCRICAO'] df_resposta['NU_NOTA_MT'] = np.around(y_pred_test,2) df_resposta.to_csv('answer.csv', index=False, header=True) print('Finalizado') df_resposta.head() ```
github_jupyter
<a href="https://colab.research.google.com/github/cuongvng/neural-networks-with-PyTorch/blob/master/CNNs/ResNet/ResNet.ipynb" target="_parent"> <img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"> </a> ``` !pip install git+https://github.com/cuongvng/neural-networks-with-PyTorch.git !nvidia-smi import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torchvision import torchvision.transforms as transforms import sys sys.path.append("../..") from utils.training_helpers import train_cnn device = torch.device("cuda" if torch.cuda.is_available() else "cpu") print(device) ``` Load CIFAR dataset ``` transform = transforms.Compose([ transforms.Resize((224,224)), transforms.ToTensor() # convert data from PIL image to tensor ]) cifar_train = torchvision.datasets.CIFAR10(root="../data/", train=True, transform=transform, target_transform=None, download=True) cifar_test = torchvision.datasets.CIFAR10(root="../data/", train=False, transform=transform, target_transform=None, download=True) batch_size = 128 train_loader = torch.utils.data.DataLoader( dataset=cifar_train, batch_size=128, shuffle=True, ) test_loader = torch.utils.data.DataLoader( dataset=cifar_test, batch_size=128, shuffle=True, ) classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck') ``` Let's dive into ResNet's architechture. There are multiple types of ResNet, such as ResNet-18, ResNet-34, ResNet-50, ResNet-152, etc., but they has the same core: the **Residual Block**. In this notebook, I will demonstrate the ResNet-34. <figure> <center><img src="https://github.com/d2l-ai/d2l-en/blob/master/img/resnet-block.svg?raw=1"/></center> <center><figcaption class="center">Residual Block</figcaption></center> </figure> ``` class ResidualBlock(nn.Module): def __init__(self, in_channels, out_channels, stride=1, use_1x1_conv=False): super(ResidualBlock, self).__init__() self.use_1x1_conv = use_1x1_conv self.conv3x3_1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1, stride=stride) self.conv3x3_2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1) self.conv1x1 = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=stride) self.bn = nn.BatchNorm2d(num_features=out_channels) def forward(self, X): X_original = X.clone() X = self.conv3x3_1(X) X = F.relu(self.bn(X)) X = self.conv3x3_2(X) X = self.bn(X) if self.use_1x1_conv: X_original = self.conv1x1(X_original) return F.relu(X + X_original) ``` Let's see the structures of different ResNet variants. ![Structures of ResNets](https://github.com/cuongvng/neural-networks-with-PyTorch/blob/resnet/CNNs/ResNet/img/ResNetStructures.png?raw=1) Source: [the original ResNet paper](https://arxiv.org/pdf/1512.03385.pdf) As we can see, all the variants have the two `7x7 Conv` and `3x3 MaxPooling` layers at the beginning and the two `AvgPooling` and `Dense` Layers at the end. The difference lies in the intermediate layers, which contains multiple stacked Residual Blocks, which are denoted inside big square brackets. Note that we add a BatchNormalization layer after each Convolutional layer. Now let's implement the whole ResNet-34 model. ``` class ResNet34(nn.Module): def __init__(self): super(ResNet34, self).__init__() # Declare each layer on the table above: self.conv1 = nn.Sequential( nn.Conv2d(in_channels=3, out_channels=64, kernel_size=7, stride=2, padding=3), nn.BatchNorm2d(num_features=64), nn.ReLU() ) self.conv2_x = nn.Sequential( nn.MaxPool2d(kernel_size=3, stride=2, padding=1), ResidualBlock(in_channels=64, out_channels=64), ResidualBlock(in_channels=64, out_channels=64), ResidualBlock(in_channels=64, out_channels=64), ) # The first Residual Block in each subsequent layer use 1x1 convolutional layer and `stride=2` # to halve the height and width of the input tensor. # This does not apply to the above `self.conv2_x` because it already has the `MaxPool2d` layer to do so. self.conv3_x = nn.Sequential( ResidualBlock(in_channels=64, out_channels=128, stride=2, use_1x1_conv=True), ResidualBlock(in_channels=128, out_channels=128), ResidualBlock(in_channels=128, out_channels=128), ResidualBlock(in_channels=128, out_channels=128), ) self.conv4_x = nn.Sequential( ResidualBlock(in_channels=128, out_channels=256, stride=2, use_1x1_conv=True), ResidualBlock(in_channels=256, out_channels=256), ResidualBlock(in_channels=256, out_channels=256), ResidualBlock(in_channels=256, out_channels=256), ResidualBlock(in_channels=256, out_channels=256), ResidualBlock(in_channels=256, out_channels=256), ) self.conv5_x = nn.Sequential( ResidualBlock(in_channels=256, out_channels=512, stride=2, use_1x1_conv=True), ResidualBlock(in_channels=512, out_channels=512), ResidualBlock(in_channels=512, out_channels=512), ) # The Global Average Pooling layer will be replaced by an average pooling function in the `forward` method. # The reason why I do not declare it as a torch.nn layer here is that for Global Pooling, the kernel size is the # shape (height, width) of the input tensor, thus it outputs an 1x1 tensor (over the channel dimension). # And since I do not know (or just be lazy to calculate) its kernel size, I will print the input shape # at the `forward` method to get the kernel size. # The last dense layer will output 10 classes for the CIFAR dataset, not 1000 for the ImageNet dataset as on the table. self.fc = nn.Linear(in_features=512, out_features=10) def forward(self, X): X = X.type(torch.float) X = self.conv1(X) X = self.conv2_x(X) X = self.conv3_x(X) X = self.conv4_x(X) X = self.conv5_x(X) # Apply global avg pooling 2d (kernel size = (height, width) to get output's spatial dimension = (1,1)) X = F.avg_pool2d(X, kernel_size=(X.shape[2], X.shape[3])) X = torch.flatten(X, start_dim=1) X = self.fc(X) return X net = ResNet34() criterion = nn.CrossEntropyLoss() optimizer = optim.Adam(net.parameters(),lr=0.001) n_epochs = 10 train_cnn(net, device, train_loader, test_loader, optimizer, criterion, n_epochs) ```
github_jupyter
<a href="https://colab.research.google.com/github/NacerSebtiMS/P300-Data-Analysis/blob/main/P300_Data_Analysis.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Data-Analysis + The analysis consists in identifying the signals measured the presence of a wave called P300 + Studying the automation of this classification and implementing several pattern recognition techniques to evaluate them. ## The dataset + The first category includes signals that are pre-labeled as P300 or P300-free, and should be used to design and validate the recognition system. + The second category includes signals for which the category to which they belong is not known a priori (unknown). The recognition system will automatically classify them into the CP300 or CP300-free class. ### Study and analysis of the distributions (probability distributions) + Examine the shape of the probability laws (dispersion and distribution of points); + Examine the eigenvalues of the covariance matrices; + Study the relevance of decorrelation of coordinates; + In order to reduce computations and the duration of treatments, study the relevance of a dimension reduction by decorrelation; + Examine again the shape of the laws of probability after decorrelation. + Study the visual form of the boundary equations between CP300 and Non CP300 classes; + From previous work, deduce the advantages and disadvantages of direct estimation of probability densities by joint probabilities or by independent likelihood estimation for each of the dimensions. ### Implementation of three Bayesian classification algorithms All three algorithms must take into account the cost associated with poor detection of the P300. The cost of not detecting the presence of a P300 ("false negative") is 3, while the cost of not detecting the absence of a P300 ("false positive") is 1. + Implement a classification algorithm that uses the assumption that the laws are Gaussian; + Implement another algorithm that allows a classification without using the mathematical expression of the boundaries and without assuming the Gaussian character but using the risk as defined by Bayes. + Finally for the third algorithm use the mathematical expression of the boundaries assuming that the probability densities are Gaussian. #### Evaluation + Separate the data into two sets : + learning set; + Testing set. + With these sets, evaluate the average classification rate of the 3 systems, compare the results and comment ### K-NN & K-means Test now and experiment with non-parametric approaches. Document the classification of the same signals as before using two methods : + Classification by the k-nearest neighbors (k-NN); + Classification according to the k-NN algorithm but first using vector quantization (k-means) in order to reduce the size of the data used for the classification. Criticize and compare the two methods of using k-NN. ### Comparison Based on the average misclassification rate of the different techniques you used, comment, document and discuss the results by comparing the techniques. ### Image recognition Brain response is highly dependent on context and mood. It would therefore be important to match the EEG measurement with images from a camera to determine the person's mood (tense, angry, relaxed, etc.). We choose to classify the environments in which the subject finds himself or herself by assuming that the environment has an impact on mood. Evaluate the possibility of classifying the nature of images into three categories (beach, forest and town/road). For simplicity, only color information be used. You will design an image recognition system that will allow to classify the nature of images in the 3 categories (beach, forest and city) with only the color information. The system must be able to operate for different codings of the color characteristics of the images. ## Loading data and library imports Clonning the repository gives access to the data ``` !git clone https://github.com/NacerSebtiMS/P300-Data-Analysis.git import pandas as pd import matplotlib.pyplot as plt import numpy as np ``` All datasets are loaded and the columns are labeled with X1, X2, X3 and X4. ``` P300_PATH = "/content/P300-Data-Analysis/data/P300/" COLUMN_NAMES = ['X1','X2','X3','X4'] # Ref P300 data path_ref_P300 = P300_PATH + "ref_P300" ref_P300 = pd.read_csv(path_ref_P300, delim_whitespace=True) ref_P300.columns = COLUMN_NAMES # Ref NP300 data path_ref_NP300 = P300_PATH + "ref_NP300" ref_NP300 = pd.read_csv(path_ref_NP300, delim_whitespace=True) ref_NP300.columns = COLUMN_NAMES # Test P300 data path_test_P300 = P300_PATH + "test_P300" test_P300 = pd.read_csv(path_test_P300, delim_whitespace=True) test_P300.columns = COLUMN_NAMES # Test NP300 data path_test_NP300 = P300_PATH + "test_NP300" test_NP300 = pd.read_csv(path_test_NP300, delim_whitespace=True) test_NP300.columns = COLUMN_NAMES # prediction data path_unknown = P300_PATH + "Inconnus" unknown = pd.read_csv(path_unknown, delim_whitespace=True) unknown.columns = COLUMN_NAMES ``` ## Study and analysis of the distributions (probability distributions) ### Examine the shape of the probability laws (dispersion and distribution of points) ``` n = max(len(ref_P300), len(ref_NP300)) x_P300 = np.linspace(1, n, len(ref_P300)) x_NP300 = np.linspace(1, n, len(ref_NP300)) plt.plot(x_P300,ref_P300['X1'],'o') plt.plot(x_NP300, ref_NP300['X1'],'*') plt.show() plt.plot(x_P300,ref_P300['X2'],'o') plt.plot(x_NP300, ref_NP300['X2'],'*') plt.show() plt.plot(x_P300,ref_P300['X3'],'o') plt.plot(x_NP300, ref_NP300['X3'],'*') plt.show() plt.plot(x_P300,ref_P300['X4'],'o') plt.plot(x_NP300, ref_NP300['X4'],'*') plt.show() plt.plot(ref_P300['X1'],ref_P300['X2'],'o') plt.plot(ref_NP300['X1'],ref_NP300['X2'],'*') plt.plot(ref_P300['X1'],ref_P300['X3'],'o') plt.plot(ref_NP300['X1'],ref_NP300['X3'],'*') plt.plot(ref_P300['X1'],ref_P300['X4'],'o') plt.plot(ref_NP300['X1'],ref_NP300['X4'],'*') plt.plot(ref_P300['X2'],ref_P300['X3'],'o') plt.plot(ref_NP300['X2'],ref_NP300['X3'],'*') plt.plot(ref_P300['X2'],ref_P300['X4'],'o') plt.plot(ref_NP300['X2'],ref_NP300['X4'],'*') plt.plot(ref_P300['X3'],ref_P300['X4'],'o') plt.plot(ref_NP300['X3'],ref_NP300['X4'],'*') ``` ### Examine the eigenvalues of the covariance matrices Estimation of the average ``` # Ref P300 avg [avg_X1_P300,avg_X2_P300,avg_X3_P300,avg_X4_P300] = ref_P300.mean() print(ref_P300.mean()) # Ref NP300 avg [avg_X1_NP300,avg_X2_NP300,avg_X3_NP300,avg_X4_NP300] = ref_NP300.mean() print(ref_NP300.mean()) ``` Covariance matrices ``` # Coding the df.cov() method def avg(column): return column.sum()/len(column) def covariance(column1, column2): if(len(column1) != len(column2)): raise Exception("Column1 and Column2 don't have the same len") else : term1 = column1 - avg(column1) term2 = column2 - avg(column1) mult = term1 * term2.transpose() s = mult.sum() return s / (len(column1)-1) def covariance_matrice(df): col = df.columns cov_mat = pd.DataFrame(np.zeros([len(df.columns),len(df.columns)]), index=col,columns=col) for i in range(len(df.columns)): for j in range(i,len(col)): c = covariance(df[col[i]],df[col[j]]) cov_mat[col[i]][col[j]] = c cov_mat[col[j]][col[i]] = c return cov_mat cov_ref_P300 = covariance_matrice(ref_P300) cov_ref_NP300 = covariance_matrice(ref_NP300) cov_ref_P300 cov_ref_NP300 eigvals_ref_P300, eigvect_ref_P300 = np.linalg.eig(cov_ref_P300) print(eigvals_ref_P300) eigvals_ref_NP300, eigvect_ref_NP300 = np.linalg.eig(cov_ref_NP300) print(eigvals_ref_NP300) ``` ### Study the relevance of decorrelation of coordinates ### Study the relevance of a dimension reduction by decorrelation ### Examine again the shape of the laws of probability after decorrelation ### Study the visual form of the boundary equations between P300 and NP300 classes ### Deduce the advantages and disadvantages of direct estimation of probability densities by joint probabilities or by independent likelihood estimation for each of the dimensions ## Implementation of three Bayesian classification algorithms ### Classification algorithm that uses the assumption that the laws are Gaussian ### Bayes risk classification algorithm ### Mathematical expression of the boundaries assuming that the probability densities are Gaussian ### Evaluation #### Separate data #### Rvaluation of the average classification rate of the 3 systems, compare the results and comment ## K-NN & K-means Defining a distance ``` def euclidean_distance(p1,p2): try: s = 0 for i in range(len(p1)): s += abs(p1[i]-p2[i]) return s except: return abs(p1-p2) dist = lambda p1, p2 : euclidean_distance(p1,p2) ``` K-NN class ``` class K_nn: def __init__(self, k, distance=dist): self.k = k self.distance = distance self.x = None self.y = None def fit(self,x,y): self.x = x self.y = y self.columns = x_train.columns self.classes = y_train[y_train.columns[0]].unique() def calc_dist(self,row1,row2): s=0 for c in self.columns: s += self.distance(row1[c], row2[c]) return s def replace_min(self, mins, d, c): for i in range(len(mins)): if mins[i][0] > d or mins[i][0] == -1: mins[i] = (d,c) return mins return mins def choose_class(self, mins): dico = {} for couple in mins: if couple[1] in dico.keys(): dico[couple[1]] += 1 else: dico[couple[1]] = 1 max = -1 c = None for k in dico.keys(): if max < dico[k]: max = dico[k] c = k return c def predict(self,v): mins = [(-1,0)] * self.k for i in range(len(self.x)): d = self.calc_dist(self.x.loc[i],v) mins = self.replace_min(mins, d, self.y.loc[i].values[0]) return self.choose_class(mins) x_train_knn_P300 = ref_P300 y_train_knn_P300 = pd.DataFrame(np.empty(len(x_train_knn_P300)),columns=["class"]) y_train_knn_P300['class'] = 'P300' x_train_knn_NP300 = ref_NP300 y_train_knn_NP300 = pd.DataFrame(np.empty(len(x_train_knn_NP300)),columns=["class"], index=pd.RangeIndex(len(y_train_knn_P300),len(y_train_knn_P300)+len(x_train_knn_NP300),1)) y_train_knn_NP300['class'] = 'NP300' x_train = pd.concat([x_train_knn_P300,x_train_knn_NP300]) x_train.index = pd.RangeIndex(0,len(x_train),1) y_train = pd.concat([y_train_knn_P300,y_train_knn_NP300]) x_pred_knn = pd.concat([test_P300,test_NP300], keys=['P300','NP300']) predictions = {} k_range = [ 1 , 1 ] for k in range(k_range[0],k_range[1]+1,2): model = K_nn(k) model.fit(x_train,y_train) correct_predictions = 0 prediction_for_k = {} for index,row in x_pred_knn.iterrows(): prediction = model.predict(row) prediction_for_k[index] = prediction if prediction == index[0]: correct_predictions += 1 predictions[k] = prediction_for_k acc = correct_predictions / len(x_pred_knn) * 100 print("k =",k,"\t","accuracy:",acc,"%") predictions ``` #### Classification by the k-nearest neighbors (k-NN) #### Classification according to the k-NN algorithm but first using vector quantization (k-means) in order to reduce the size of the data used for the classification #### Comparaison between k-NN and k-NN using k-means ## Comparison ## Image recognition
github_jupyter
# TVB simulations in nipype! ``` # https://groups.google.com/forum/#!topic/tvb-users/ODsL9bkGLHQ import warnings warnings.filterwarnings('ignore') import os, sys, scipy.io, numpy as np from nipype import Node, Function, Workflow cwd = os.getcwd() # https://miykael.github.io/nipype_tutorial/notebooks/basic_workflow.html def make_model(model_name, parameters):# done import warnings, pickle, os warnings.filterwarnings('ignore') from tvb.simulator.lab import models import numpy as np mod = getattr(models, model_name) model_class = mod(**dict(parameters)) with open("model_class.p", "wb") as f: pickle.dump(model_class, f) model_class = os.path.abspath("model_class.p") return model_class def load_connectivity_mat(in_file, normalize=False): import scipy.io, pickle, os datamat = scipy.io.loadmat(in_file) sc_weights = datamat['sc_weights'] if normalize: sc_weights = sc_weights / sc_weights.max() tract_lengths = datamat['tract_lengths'] scipy.io.savemat('sc_weights.mat',{'sc_weights': sc_weights}) scipy.io.savemat('tract_lengths.mat',{'tract_lengths': tract_lengths}) sc_weights = os.path.abspath("sc_weights.mat") tract_lengths = os.path.abspath("tract_lengths.mat") return sc_weights, tract_lengths def make_connectivity(weights, lengths): import warnings, pickle, os, scipy.io warnings.filterwarnings('ignore') weights_mat = scipy.io.loadmat(weights); weights = weights_mat['sc_weights'] lengths_mat = scipy.io.loadmat(lengths); lengths = lengths_mat['tract_lengths'] from tvb.simulator.lab import connectivity conn_class = connectivity.Connectivity(weights=weights, tract_lengths=lengths) with open("conn_class.p", "wb") as f: pickle.dump(conn_class, f) conn_class = os.path.abspath("conn_class.p") return conn_class def make_integrator(integrator_name, base_dt, noise_type, noise_val): import sys, numpy, warnings, pickle, os warnings.filterwarnings('ignore') sys.modules['mtrand'] = numpy.random.mtrand from tvb.simulator.lab import integrators, noise temp_integrator = getattr(integrators,integrator_name) temp_noise = getattr(noise, noise_type) noise = temp_noise(nsig = numpy.array([noise_val])) integrator_class = temp_integrator(dt = base_dt, noise = noise) #integrator_class = temp_integrator(dt = base_dt) with open("integrator_class.p", "wb") as f: pickle.dump(integrator_class, f) integrator_class = os.path.abspath("integrator_class.p") return integrator_class def make_monitors(monitor_types, periods): import warnings, sys, numpy, pickle, os warnings.filterwarnings('ignore') sys.modules['mtrand'] = numpy.random.mtrand from tvb.simulator.lab import monitors monitor_class = [] for i in range(len(monitor_types)): monitor_tmp = getattr(monitors,monitor_types[i]) monitor_tmp2 = monitor_tmp(period = periods[i]) monitor_class.append(monitor_tmp2) monitor_class = tuple(monitor_class) with open("monitor_class.p", "wb") as f: pickle.dump(monitor_class, f) monitor_class = os.path.abspath("monitor_class.p") return monitor_class def run_simulation(model_input, conn_input, integrator_input, monitor_input, global_coupling = 0.1, conduction_speed=3.0, simulation_length=10000.0): import warnings, sys, numpy, pickle, os, scipy.io warnings.filterwarnings('ignore') sys.modules['mtrand'] = numpy.random.mtrand with open(model_input, "rb") as f: model_input = pickle.load(f) with open(conn_input, "rb") as f: conn_input = pickle.load(f) with open(integrator_input, "rb") as f: integrator_input = pickle.load(f) with open(monitor_input, "rb") as f: monitor_input = pickle.load(f) from tvb.simulator.lab import * wm_coupling = coupling.Linear(a = global_coupling) sim = simulator.Simulator(model = model_input, connectivity = conn_input, coupling = wm_coupling, integrator = integrator_input, monitors = monitor_input, simulation_length = simulation_length, conduction_speed = conduction_speed) sim.configure() sim_output = sim.run() scipy.io.savemat('sim_output.mat',{'sim_output': sim_output}) abs_out_file = os.path.abspath("sim_output.mat") # fix this return abs_out_file ##### NIPYPE PORTION # https://miykael.github.io/nipype_tutorial/notebooks/basic_function_interface.html model = Node( Function( input_names=['model_name', 'parameters'], output_names=['model_class'], function=make_model ), name='create_model' ) sc_loader = Node( Function( input_names=['in_file', 'normalize'], output_names=['sc_weights', 'tract_lengths'], function=load_connectivity_mat ), name='load_sc_mat' ) sc = Node( Function( input_names=['weights', 'lengths'], output_names=['conn_class'], function=make_connectivity ), name='create_sc' ) integrator = Node( Function( input_names=['integrator_name','base_dt','noise_type','noise_val'], output_names=['integrator_class'], function=make_integrator ), name='create_integrator' ) monitors = Node( Function( input_names=['monitor_types','periods'], output_names=['monitor_class'], function=make_monitors ), name='create_monitors' ) simulate = Node( Function( input_names=['model_input', 'conn_input', 'integrator_input', 'monitor_input', 'global_coupling', 'conduction_speed', 'simulation_length'], output_names=['abs_out_file'], function=run_simulation ), name='create_simulation' ) # https://miykael.github.io/nipype_tutorial/notebooks/basic_workflow.html workflow = Workflow(name='tvb_demo', base_dir=os.getcwd()) workflow.connect([ (model, simulate, [("model_class", "model_input")]), (sc_loader, sc, [("sc_weights", "weights"), ("tract_lengths", "lengths")]), (sc, simulate, [("conn_class", "conn_input")]), (integrator, simulate, [("integrator_class", "integrator_input")]), (monitors, simulate, [("monitor_class", "monitor_input")]) ]) # NOW DEFINE YOUR INPUTS model.inputs.model_name = 'Generic2dOscillator' model.inputs.parameters = [('a',1), ('b',1)] sc_loader.inputs.in_file = os.path.join(cwd, 'input', 'sub-01_connectivity.mat') sc_loader.inputs.normalize = False integrator.inputs.integrator_name = 'HeunStochastic' integrator.inputs.base_dt = 0.1 integrator.inputs.noise_type = 'Additive' #integrator.inputs.noise_val = 0.0001 monitors.inputs.monitor_types = ['Bold', 'TemporalAverage'] monitors.inputs.periods = [2000.0, 10.0] #simulate.inputs.global_coupling = 0.1 #simulate.inputs.conduction_speed = 2.0 simulate.inputs.simulation_length = 10000.0 # ITERABLES integrator.iterables = ("noise_val", [0.0001, 0.001, 0.01]) #simulate.iterables = [('global_coupling', [0.1, 0.5, 1.0])] #sc_loader.iterables = [('in_file', [os.path.join(cwd, 'input', 'sub-01_connectivity.mat'), os.path.join(cwd, 'input', 'sub-02_connectivity.mat'), os.path.join(cwd, 'input', 'sub-03_connectivity.mat')])] simulate.iterables = [('global_coupling', np.arange(0.0, 5.1, 0.5)), ('conduction_speed', [1,2])] # ^ move constants to top node; have initial node with subject list # make datasink at the end to clean things up #def run_simulation(out_file, model_input, conn_input, integrator_input, monitor_input, global_coupling = 0.1, conduction_speed=2.0, simulation_length=1000.0): # Write graph of type orig workflow.write_graph(graph2use='exec', dotfilename='./graph_orig.dot') from IPython.display import Image Image(filename="graph_orig_detailed.png") #workflow.run() workflow.run('MultiProc', plugin_args={'n_procs': 8}) !tree tvb_demo/ -I '*txt|*pklz|_report|*.json|*js|*.dot|*.html' ```
github_jupyter
``` import os import tensorflow as tf import matplotlib.pyplot as plt import numpy as np PATH = '/Users/stevenneira/Desktop/Work/studing/FlowersIA/' INPATH = PATH + 'inImages' OUTPATH = PATH + 'outImages' CHECKP = PATH + 'checkpoints' imgurls = os.listdir(INPATH) n=500 train_n=round(n*0.80) #Listado randomizado randurls=np.copy(imgurls) np.random.shuffle(randurls) #Particiom train/tet tr_urls=randurls[:train_n] ts_urls= randurls[train_n:n] print(len(imgurls),len(tr_urls),len(ts_urls)) #rescalar imagenes IMG_WIDTH=256 IMG_HEIGHT=256 def resize(inimg,tgimg,height,width): inimg=tf.image.resize(inimg,[height,width]) tgimg=tf.image.resize(tgimg,[height,width]) return inimg,tgimg #normaliza el rango[-1, +1] def normalize(inimg,tgimg): inimg=(inimg/127.5)-1 tgimg=(tgimg/127.5)-1 return inimg,tgimg #aumentacion de datos :random crop+flip def random_jitter(inimg,tgimg): inimg,tgimg = resize(inimg,tgimg,286,286) stacked_image=tf.stack([inimg,tgimg], axis=0) cropped_image = tf.image.random_crop(stacked_image, size=[2,IMG_HEIGHT,IMG_WIDTH,3]) inimg,tgimg=cropped_image[0],cropped_image[1] if np.random.uniform(0,1) > 0.5 : inimg=tf.image.flip_left_right(inimg) tgimg=tf.image.flip_left_right(tgimg) return inimg,tgimg def load_image(filename,augment=True): inimg=tf.cast(tf.image.decode_jpeg(tf.io.read_file(INPATH+'/'+filename)),tf.float32)[..., :3] tgimg=tf.cast(tf.image.decode_jpeg(tf.io.read_file(OUTPATH+'/'+filename)),tf.float32)[..., :3] inimg,tgimg=resize(inimg,tgimg,IMG_HEIGHT,IMG_WIDTH) if augment: inimg,tgimg = random_jitter(inimg,tgimg) inimg,tgimg= normalize(inimg,tgimg) return inimg, tgimg def load_train_image(filename): return load_image(filename,True) def load_test_image(filename): return load_image(filename,False) plt.imshow(((load_train_image(randurls[0])[1]) + 1) / 2) train_dataset=tf.data.Dataset.from_tensor_slices(tr_urls) train_dataset=train_dataset.map(load_train_image, num_parallel_calls=tf.data.experimental.AUTOTUNE) train_dataset=train_dataset.batch(1) for inimg,tgimg in train_dataset.take(5): plt.imshow(((tgimg[0,...]) + 1) / 2) plt.show() test_dataset=tf.data.Dataset.from_tensor_slices(ts_urls) test_dataset=test_dataset.map(load_test_image, num_parallel_calls=tf.data.experimental.AUTOTUNE) test_dataset=test_dataset.batch(1) from tensorflow.keras.layers import * from tensorflow.keras import * def downsample(filters,apply_batchnorm=True): initializer=tf.random_normal_initializer(0,0.02) result=Sequential() #capa convolucional result.add(Conv2D(filters, kernel_size=4, strides=2, padding="same", kernel_initializer=initializer, use_bias=not apply_batchnorm)) if apply_batchnorm: #capa de batch normalization result.add(BatchNormalization()) #capa de activacion result.add(LeakyReLU()) return result downsample(64) def upsample(filters,apply_dropout=False): initializer=tf.random_normal_initializer(0,0.02) result=Sequential() #capa convolucional result.add(Conv2DTranspose(filters, kernel_size=4, strides=2, padding="same", kernel_initializer=initializer, use_bias=False)) result.add(BatchNormalization()) if apply_dropout: #capa de batch normalization result.add( Dropout(0.5)) #capa de activacion result.add(ReLU()) return result upsample(64) def Generator(): inputs=tf.keras.layers.Input(shape=[None,None,3]) down_stack=[ downsample(64, apply_batchnorm=False), downsample(128), downsample(256), downsample(512), downsample(512), downsample(512), downsample(512), downsample(512), ] up_stack=[ upsample(512,apply_dropout=True), upsample(512,apply_dropout=True), upsample(512,apply_dropout=True), upsample(512), upsample(256), upsample(128), upsample(64), ] initializer=tf.random_normal_initializer(0,0.02) last=Conv2DTranspose(filters=3, kernel_size=4, strides=2, padding="same", kernel_initializer=initializer, activation="tanh") x=inputs s= [] concat=Concatenate() for down in down_stack: x= down(x) s.append(x) s =reversed(s[:-1]) for up ,sk in zip (up_stack,s): x=up(x) x=concat([x,sk]) last=last(x) return Model(inputs=inputs,outputs=last ) generator=Generator() gen_output=generator(((inimg+1)*255), training=False) plt.imshow(((inimg[0,...]) + 1) /2) plt.show() plt.imshow(gen_output[0,...]) def Discriminator(): ini=Input(shape=[None,None,3],name="input_img") gen=Input(shape=[None,None,3],name="gener_img") con=concatenate([ini,gen]) initializer=tf.random_normal_initializer(0,0.2) down1=downsample(64,apply_batchnorm=False)(con) down2=downsample(128)(down1) down3=downsample(256)(down2) down4=downsample(512)(down3) last=tf.keras.layers.Conv2D(filters=1, kernel_size=4, strides=1, kernel_initializer=initializer, padding="same")(down4) return tf.keras.Model(inputs=[ini,gen],outputs=last) discriminator=Discriminator() disc_out=discriminator([((inimg+1)*255),gen_output], training=False) plt.imshow(disc_out[0,...,-1],vmin=20,vmax=20,cmap='RdBu_r') plt.colorbar() disc_out.shape generator_optimizer = tf.keras.optimizers.Adam(2e-4, beta_1=0.5) discriminator_optimizer=tf.keras.optimizers.Adam(2e-4, beta_1=0.5) loss_object=tf.keras.losses.BinaryCrossentropy(from_logits=True) def discriminator_loss(disc_real_output, disc_generated_output): #Diferencia entre los true por ser real y el detectado por el discriminador real_loss=loss_object(tf.ones_like(disc_real_output),disc_real_output) #Diferencia entre los false por ser generado y el detectado por el discriminador generated_loss=loss_object(tf.zeros_like(disc_generated_output),disc_generated_output) total_disc_loss=real_loss + generated_loss return total_disc_loss LAMBDA=100 def generator_loss(disc_generated_output,gen_output,target): gan_loss=loss_object(tf.ones_like(disc_generated_output),disc_generated_output) #mean absolute error l1_loss=tf.reduce_mean(tf.abs(target - gen_output)) total_gen_loss= gan_loss + (LAMBDA* l1_loss) return total_gen_loss def generate_images(model,test_input, tar, save_filename=False,display_imgs=True): prediction=model(test_input,training=True) if save_filename: tf.keras.preprocessing.image.save_img(CHECKP + '/'+save_filename +'.jpg', prediction[0,...]) plt.figure(figsize=(10,10)) display_list=[test_input[0],tar[0],prediction[0]] title=['Input image','Ground Truth','Predicted Image'] if display_imgs: for i in range(3): plt.subplot(1,3,i+1) plt.title(title[i]) plt.imshow(display_list[i]*0.5+0.5) plt.axis('off') plt.show() @tf.function() def train_step(input_image,target): with tf.GradientTape() as gen_tape, tf.GradientTape() as discr_tape: output_image =generator(input_image,training=True) output_gen_discr=discriminator([output_image,input_image],training=True) output_trg_discr=discriminator([output_image,input_image],training=True) discr_loss=discriminator_loss(output_trg_discr,output_gen_discr) gen_loss=generator_loss(output_gen_discr,output_image,target) generator_grads=gen_tape.gradient(gen_loss,generator.trainable_variables) discriminator_grads=discr_tape.gradient(discr_loss,discriminator.trainable_variables) generator_optimizer.apply_gradients(zip(generator_grads,generator.trainable_variables)) discriminator_optimizer.apply_gradients(zip(discriminator_grads,discriminator.trainable_variables)) from IPython.display import clear_output def train(dataset, epochs): for epoch in range (epochs): imgi=0 for input_image, target in dataset: print('epoch'+str(epoch)+'-train:' +str(imgi)+'/'+str(len(tr_urls))) imgi+=1 train_step(input_image,target) clear_output(wait=True) imgi=0 for inp,tar in test_dataset.take(5): generate_images(generator,inp,tar,str(imgi)+'_'+str(epoch),display_imgs=True) imgi+=1 train(train_dataset,100) ```
github_jupyter
# Introduction to Machine Learning with Scikit-Learn Today's workshop, which is presented by the [KAUST Visualization Core Lab (KVL)](https://corelabs.kaust.edu.sa/visualization/), is the first of two *Introduction to Machine Learning with Scikit-Learn* workshops. These workshops will largely follow Chapter 2 of [*Hands-on Machine Learning with Scikit-Learn, Keras, and TensorFlow*](https://learning.oreilly.com/library/view/hands-on-machine-learning/9781492032632/) which walks through the process of developing an end-to-end machine learning project with [Scikit-Learn](https://scikit-learn.org/stable/index.html). ## Today's schedule * Working with Real Data * Understanding the Big Picture * Getting the Data * Discovering and Visualizing the Data to Gain Insights ## Next Thursday's Schedule * Preparing the Data for Machine Learning Algorithms * Selecting and Training a Model * Fine Tuning Your Model # Working with Real Data When you are just getting started with machine learning it is best to experiment with real-world data (as opposed to artificial data). The following are some good resources of open-source data that you can use for practice or research. * [University of California-Irvine Machine Learning Repository](http://archive.ics.uci.edu/ml/) * [Kaggle](https://www.kaggle.com/datasets) * [OpenDataMonitor](http://opendatamonitor.eu/) * [Wikipedia's list of Machine Learning datasets](https://en.wikipedia.org/wiki/List_of_datasets_for_machine-learning_research) * [Datasets subreddit](https://www.reddit.com/r/datasets/) * [Quora's list of open datasets](https://www.quora.com/Where-can-I-find-large-datasets-open-to-the-public) Major cloud providers all have repositories of publically available datasets. * [Open Data on AWS](https://registry.opendata.aws/) * [Open Data on GCP](https://cloud.google.com/public-datasets/) * [Open Data on Azure](https://azure.microsoft.com/en-us/services/open-datasets/) Finally, [Pandas DataReader](https://pydata.github.io/pandas-datareader/) provides a unified API to a [number of datasets](https://pydata.github.io/pandas-datareader/remote_data.html). Note that many of these data sources require you to create an account and get an API key. ## 1990 U.S. California Census Data Today we will be working with a 1990 U.S. Census dataset from California. This dataset contains socioeconomic data on groups of California residents include. While this dataset is a bit "dated" it will allow us to explore many different aspects of a typical machine learning project. The California census data includes metrics such as population, median income, median house prices for each census block group in the state of California. Census block groups are the smallest geographical unit for which the U.S. Census Bureau publishes public data (for reference a census block group typically has a population of between 600 and 3000 people). Sometime census block groups are called districts for short. The figure below (reproduced from *Chapter 2* of *Hands on Machine Learning with Scikit-Learn, Keras, and TensorFlow*). <center><img src="./assets/figure-2-1.png" alt="Figure 2.1" title="California housing used to be affordable!" align="center" width="750" height="750" /></center> # Look at the Big Picture Our goal over these two workshops will be to build a machine learning modeling pipeline that uses the California census data to predict housing prices. Today we will mostly focus on getting the data, exploring the data to gain insights,. Believe it or not these initial steps are what data scientists and machine learning engineers spend the majority of their time doing! Next Thursday we will prepare our data for machine learning see how to fit a variety of machine learning models to our dataset and shortlist a few candidate models for further analysis. We will then use hyper-parameter tuning to improve the performance of our shortlisted models to arrive at an overall "best" model. We will finish with a discussion of model how to present the results of your model and talk about some of the aspects of deploying a trained model to make predictions. ## Framing the problem ### What is the business/research objective? Typically building the model is *not* the overall objective but rather the model itself is only one part of a larger process used to answer a business/research question. Knowing the overall objective is important because it will determine your choice of machine learning algorithms to train, your measure(s) of model performance, and how much time you will spend tweaking the hyper-parameters of your model. In our example today, the overall business objective is to make money investing in houses. Our house price prediction model with be one of potentially many other models whose predictions are taken as inputs into another machine learning model that will be used to determine whether or not investing in houses in a particular area is a good idea. This hypothetical ML pipeline is shown in the figure below (reproduced from *Chapter 2* of *Hands on Machine Learning with Scikit-Learn, Keras, and TensorFlow*). <center><img src="./assets/figure-2-2.png" alt="Figure 2.2" title="Hypothetical ML pipeline" align="center" width="1000" height="250" /></center> ### What is the *current* solution? Always a good idea to know what the current solution to the problem you are trying to solve. Current solution gives a benchmark for performance. Note that the current "best" solution could be *very* simple or could be *very* sophisticated. Understanding the current solution helps you think of a good place to start. Example: suppose that the current solution for predicting the price of a house in a given census block is to ignore all the demographic information and predict a simple average of house prices in nearby census blocks. In this case it would probably *not* make sense to start building a complicated [deep learning model](https://en.wikipedia.org/wiki/Deep_learning) to predict housing prices. However, if the current solution was a tuned [gradient boosted machine](https://en.wikipedia.org/wiki/Gradient_boosting) then it probably would *not* make sense to try a much simpler [linear regression](https://en.wikipedia.org/wiki/Linear_regression) model. With all this information, you are now ready to start designing your system. First, you need to frame the problem by answering the following questions. * Is our problem [supervised](https://en.wikipedia.org/wiki/Supervised_learning), [unsupervised](https://en.wikipedia.org/wiki/Unsupervised_learning), or [reinforcement](https://en.wikipedia.org/wiki/Reinforcement_learning) learning? * Is our problem a [classification](https://en.wikipedia.org/wiki/Statistical_classification) task, a [regression](https://en.wikipedia.org/wiki/Regression_analysis) task, or something else? If our problem is a classification task are we trying to classify samples into 2 categories (binary classification) or more than 2 (multi-class classification) categories? If our problem is a regression task, are we trying to predict a single value (univariate regression) or multiple values (multivariate regression) for each sample? * Should you use batch learning or [online learning](https://en.wikipedia.org/wiki/Online_machine_learning) techniques? ## Select a Performance Measure Next we want to select a performance measure. A typical performance measure for regression problems of this type is the root mean square error (RMSE). $$ \mathrm{RMSE}(X, h) = \sqrt{\frac{1}{N}\sum_{i=1}^N (h(x_i) - y_i)^2} $$ In the above formula $X$ is the dataset, $h$ is the decision function or model (which we will train on the dataset!), $x_i$ is the $i$ training sample from the dataset (variables used to predict house prices in our problem), $y_i$ is the $i$ target value from the dataset (house prices in order problem). ### Exercise: Scikit-Learn has a number of different [possible metrics](https://scikit-learn.org/stable/modules/model_evaluation.html) that you can choose from (or you can create your own custom metric if required). Can you find at least one other metric that seems appropriate for our house price prediction model? ``` from sklearn import metrics ``` ## Check Assumptions! Always a good idea to check any assumptions that you have made about either the inputs to your machine learning model or about how the outputs of your machine learning model will be used. Currently we have formulated our machine learning problem as a *supervised*, *univariate regression* problem suitable for *batch* learning. What if the downstream model doesn't actually use the numerical predictions from our model but rather converts the predicted prices into categories "cheap", "fair", "expensive"? Maybe it would be better to change the design of our machine learning model so that it predicts these categories directly? If so, then we would need to use completely different algorithms as the machine learning problem would then be a classification problem and not a regression problem. # Get the Data Time to get our hands dirty with the data! ## Create the Workspace For this training the workspace has already been created for you so there is nothing to install! However, if you would like to understand how to install the software stack used in this training then please see the instructions in the [README](../README.md) file of this repository. There are three files that define the software dependencies to be installed. * [`environment.yml`](../environment.yml) for [Conda](https://docs.conda.io/en/latest/) installed dependencies. * [`requirements.txt`](../requirements.txt) for [Pip](https://pip.pypa.io/en/stable/) installed dependencies. * [`postBuild`](../postBuild) which contains instructions for installing any required [Jupyter](https://jupyter.org/) extensions. The process for creating the virtual environment has been automated using the [`create-conda-env.sh`](../bin/create-conda-env.sh) script. For more on using Conda (+pip) to create virtual environments and manage your data science and machine learning software stacks you can check out our [Introduction to Conda for (Data) Scientists](https://carpentries-incubator.github.io/introduction-to-conda-for-data-scientists/) training materials and watch our recent training workshops on the KAUST Visualization Core Lab (KVL) [YouTube Channel](https://www.youtube.com/channel/UCR1RFwgvADo5CutK0LnZRrw). ## Download the data ``` import os import tarfile import urllib HOUSING_URL = "https://raw.githubusercontent.com/ageron/handson-ml2/master/datasets/housing/housing.tgz" def fetch_data(): if not os.path.isfile('../data/housing/housing.tgz'): os.makedirs("../data/housing/", exist_ok=True) urllib.request.urlretrieve(HOUSING_URL, "../data/housing/housing.tgz") with tarfile.open("../data/housing/housing.tgz") as tf: tf.extractall(path="../data/housing/") fetch_data() ``` ## Load the data We will load the data using the [Pandas](https://pandas.pydata.org/) library. Highly recommend the most recent edition of [*Python for Data Analysis*](https://learning.oreilly.com/library/view/python-for-data/9781491957653/) by Pandas creator Wes Mckinney for anyone interested in learning how to use Pandas. ``` import pandas as pd housing_df = pd.read_csv("../data/housing/housing.csv") ``` ## Take a quick look at the data Each row represents a census block group or district. ``` housing_df.head() ``` ### Do we have any non-numeric attributes? ``` housing_df.info() (housing_df.loc[:, "ocean_proximity"] .value_counts()) ``` ### Compute descriptive statistics ``` housing_df.describe() ``` ### Plot histograms of your numeric attributes Another good way to get a feel for your data is to plot histograms of your numerical attributes. Histograms show the number of instances (on the vertical axis) that have a given value range (on the horizontal axis). Can plot histograms of attributes one at a time... ``` import matplotlib.pyplot as plt fig, ax = plt.subplots(1, 1, figsize=(10,10)) (housing_df.loc[:, "median_house_value"] .hist(bins=50, ax=ax)) plt.show() ``` ...or can call the [`hist`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.hist.html) method on the entire `DataFrame`! ``` fig, ax = plt.subplots(3, 3, figsize=(20,15)) housing_df.hist(bins=50, ax=ax) plt.show() ``` ### Discussion Do you notice anything unusual or interesting about the above histrograms? 1. The `median_income` attribute does not appear to be expressed in USD. Maybe 10k USD? Important to always know the units of the attributes in your dataset. Also the values appear to be capped at both the lower and upper ends. Working with processed data is very common in machine learning and is not necessarily a problem (you just need to be aware of how the raw data was transformed). 2. Looks like the `housing_median_age` and `median_house_value` were also capped at the upper end. The latter *might* be a serious problem as house prices is the target that we are trying to predict. What to do? First, check with teams downstream (i.e., teams using your prediction as an input to their own model/process). If they need predictions that go beyond 500k USD then you have two options: either collect proper target values for the data (may not be feasible!) or drop the training samples from the dataset (so your model will not be evaulated poorly for predicting prices greater than 500k USD). 3. Attributes have very different scales! `housing_median_age` ranges from 0 to 50 but `total_rooms` ranges from 0 to 40000! Many machine learning algorithms will perform poorly when input attributes have wildly different scales. We will discuss this later when we come to feature scaling. 4. Many of these histograms are skewed to the right (i.e., have a "heavy" tail). Theory underlying many machine learning algorithms often assumes that attributes have Normal/Gaussian, "Bell-shaped" distribution. Maybe we can find some tranformations that will make these attributes appear to be more "Bell-shaped." ## Creating a Test Set Before we look at the data any further, we need to create a test set, put it aside, and never look at it (until we are ready to test our trainined machine learning model!). Why? We don't want our machine learning model to memorize our dataset (this is called overfitting). Instead we want a model that will generalize well (i.e., make good predictions) for inputs that it didn't see during training. To do this we hold split our dataset into training and testing datasets. The training dataset will be used to train our machine learning model(s) and the testing dataset will be used to make a final evaluation of our machine learning model(s). ### If you might refresh data in the future... ...then you want to use some particular hashing function to compute the hash of a unique identifier for each observation of data and include the observation in the test set if resulting hash value is less than some fixed percentage of the maximum possible hash value for your algorithm. This way even if you fetch more data, your test set will never include data that was previously included in the training data. ``` import zlib def in_testing_data(identifier, test_size): _hash = zlib.crc32(bytes(identifier)) return _hash & 0xffffffff < test_size * 2**32 def split_train_test_by_id(data, test_size, id_column): ids = data[id_column] in_test_set = ids.apply(lambda identifier: in_testing_data(identifier, test_size)) return data.loc[~in_test_set], data.loc[in_test_set] ``` ### If this is all the data you will ever have... ...then you can just set a seed for the random number generator and then randomly split the data. Scikit-Learn has a [`model_selection`](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html) module that contains tools for splitting datasets into training and testing sets. ``` import numpy as np from sklearn import model_selection _seed = 42 _random_state = np.random.RandomState(_seed) training_data, testing_data = model_selection.train_test_split(housing_df, test_size=0.2, random_state=_random_state) _ = (housing_df.loc[:, "median_income"] .hist()) ``` Suppose that we are told that `median_income` is a very important feature which determines house prices. We might want to make sure that the distribution of `median_income` in our testing dataset closely matches the distribution of `median_income` in our entire dataset. ``` # current distribution of median income in testing dataset is not quite the same as in the overall dataset _ = (testing_data.loc[:, "median_income"] .hist()) ``` We can accomplish this by creating a temporary variable that bins samples according to the value of `median_income`. This technique is called [stratified sampling](https://en.wikipedia.org/wiki/Stratified_sampling). ``` pd.cut? _seed = 42 _prng = np.random.RandomState(_seed) _median_income_strata = pd.cut(housing_df.loc[:, "median_income"], bins=[0., 1.5, 3.0, 4.5, 6., np.inf], labels=[1, 2, 3, 4, 5]) training_data, testing_data = model_selection.train_test_split(housing_df, test_size=0.2, random_state=_prng, stratify=_median_income_strata) _ = (testing_data.loc[:, "median_income"] .hist()) _ = (housing_df.loc[:, "median_income"] .hist()) # where possible I like to write out the training and testing data sets to disk training_data.to_csv("../data/housing/training.csv", index_label="id") testing_data.to_csv("../data/housing/testing.csv", index_label="id") ``` # Explore and visualize the data to gain insights ``` fig, ax = plt.subplots(1, 1, figsize=(12, 10)) _ = training_data.plot.scatter(x="longitude", y="latitude", ax=ax) plt.show() fig, ax = plt.subplots(1, 1, figsize=(12, 10)) _ = training_data.plot.scatter(x="longitude", y="latitude", ax=ax, alpha=0.1) plt.show() fig, ax = plt.subplots(1, 1, figsize=(12, 10)) _size = (training_data.loc[:, "population"] .div(100)) _color = training_data.loc[:, "median_house_value"] _cmap = plt.get_cmap("viridis") _ = (training_data.plot .scatter(x="longitude", y="latitude", ax=ax, alpha=0.4, s=_size, c=_color, cmap=_cmap, label="population", colorbar=True)) _ = ax.legend() ``` ## Looking for correlations Since our dataset is not too large we can compute the [correlation coefficient](https://en.wikipedia.org/wiki/Correlation_coefficient) between every pair of attributes in our dataset. ``` training_data.corr() # correlations between attributes are our target (training_data.corr() .loc[:, "median_house_value"] .sort_values(ascending=False)) ``` ### Correlation coefficient only measures *linear* correlations Correlation coefficient only captures *linear* relationships between variables (i.e., if $x$ goes up, then $y$ generally goes up/down). It may completely miss any non-linear relationships between variables. The figure below (reproduced from *Chapter 2* of *Hands on Machine Learning with Scikit-Learn, Keras, and TensorFlow*) shows correlation coefficients for various datasets. Check out the bottom row! <center><img src="./assets/figure-2-14.png" alt="Figure 2.14" title="Correlation coefficient only captures linear dependence" align="center" width="750" height="750" /></center> ``` from pandas import plotting attributes = ["median_house_value", "median_income", "total_rooms", "housing_median_age"] _ = plotting.scatter_matrix(training_data.loc[:, attributes], figsize=(12, 8)) fig, ax = plt.subplots(1, 1, figsize=(12, 10)) _ = training_data.plot.scatter(x="median_income", y="median_house_value", alpha=0.1, ax=ax) ``` ## Experimenting with attribute combinations One last thing you may want to do before preparing the data for Machine Learning algorithms is to try out various attribute combinations. This process is called [feature engineering](https://en.wikipedia.org/wiki/Feature_engineering). Understanding how to engineer features that are useful for solving a particular machine learning problem often requires a significant amount of domain expertise. However a number of libraries, such as [featuretools](https://www.featuretools.com/), have been developed to (partially) automate the process of feature engineering. We will start next week's tutorial with more on feature engineering. ``` _rooms_per_household = (training_data.loc[:, "total_rooms"] .div(training_data.loc[:, "households"])) _bedrooms_per_room = (training_data.loc[:, "total_bedrooms"] .div(training_data.loc[:, "total_rooms"])) _population_per_household = (training_data.loc[:, "population"] .div(training_data.loc[:, "households"])) new_attributes = {"rooms_per_household": _rooms_per_household, "bedrooms_per_room": _bedrooms_per_room, "population_per_household": _population_per_household} # correlations are now stronger (training_data.assign(**new_attributes) .corr() .loc[:, "median_house_value"] .sort_values(ascending=False)) ``` # Thanks! See you next week for part 2 of our Introduction to Machine Learning with Scikit Learn workshop! **12 November 2020, 1-5 pm AST (UTC+3)** * Preparing the Data for Machine Learning Algorithms * Selecting and Training a Model * Fine Tuning Your Model
github_jupyter
``` import json import re import pandas as pd from sklearn.feature_extraction.text import CountVectorizer from sklearn.linear_model import LogisticRegression #from sklearn.naive_bayes import MultinomialNB #from sklearn.neural_network import MLPClassifier f = open("__data_export.json") data = json.load(f) ``` #### data and category We create two lists - one to hold the text, and the other to hold a value representing which category it belongs in. 0: Not tagged with surgery keyword 1: Tagged with the surgery keyword ``` is_surgery = [] trial_text = [] for d in data.keys(): if 'surgery' in data[d]['keywords']: is_surgery.append(1) else: is_surgery.append(0) data_text = "" for k in data[d].keys(): if type(data[d][k]) is list or data[d][k] is None: continue else: data_text += str(data[d][k]) + ' ' data_text = re.sub('<[^<]+?>', '', data_text) data_text = re.sub("[^a-zA-Z0-9]"," ", data_text) data_text = ' '.join(data_text.split()) trial_text.append(data_text) ``` #### visualize in a data frame ``` df = pd.DataFrame({'trial_text': trial_text, 'is_surgery': is_surgery}) #notice that we are matching on very few #df # we can sort #df.sort_values(by=['is_surgery'], ascending=False) # let's take a very few to train a model train_set = df.sort_values(by=['is_surgery'], ascending=False).head(24) train_set vectorizer = CountVectorizer(analyzer = "word", tokenizer = None, preprocessor = None, stop_words = 'english', max_features = 100) train_data_features = vectorizer.fit_transform(train_set['trial_text']) train_data_features.toarray() ``` #### visualize the positive and negative graphs ``` %matplotlib inline import matplotlib.pyplot as plt import pandas as pd surgery = {} surgery['word'] = vectorizer.get_feature_names() for i in range(12): surgery['R' + str(i)] = train_data_features.toarray()[i] df = pd.DataFrame(surgery) df = df.set_index('word') plt.style.use('ggplot') plt.rcParams["figure.figsize"] = [14,7] df.plot(kind='bar') plt.xticks(rotation=90) surgery = {} surgery['word'] = vectorizer.get_feature_names() for i in range(12,24): surgery['R' + str(i)] = train_data_features.toarray()[i] df = pd.DataFrame(surgery) df = df.set_index('word') plt.style.use('ggplot') plt.rcParams["figure.figsize"] = [14,7] df.plot(kind='bar') plt.xticks(rotation=90) train_data_features.toarray()[:12] clf = LogisticRegression() #clf= MLPClassifier() #clf = MultinomialNB() train_set["is_surgery"] clf.fit(train_data_features, train_set["is_surgery"] ) # overfitted clf.score(train_data_features,train_set['is_surgery']) # make a prediction cancer_trial = "There is a critical need for physical activity interventions in CRC. The investigators \ have developed a digital health physical activity intervention, Smart Pace, which includes a wearable \ tracker (Fitbit) and text messaging and aims to have patients build up to 150 min/wk of moderate activity" cancer_trial = [re.sub("[^a-zA-Z0-9]"," ", cancer_trial)] test_data_features = vectorizer.transform(cancer_trial) binary_predictions = clf.predict_proba(test_data_features) print(binary_predictions) surgery_trial = "Myocardial injury after non-cardiac surgery (MINS) is common in patients undergoing\ major surgery. Many of the events are undetected and associated with a high 30-day mortality risk. \ Knowledge of which perioperative factors that predicts MINS is lacking. Decrease in tissue \ oxygenation (StO2) is common in patients undergoing major spine surgery and is associated \ with postoperative complications in these patients." surgery_trial = [re.sub("[^a-zA-Z0-9]"," ", surgery_trial)] test_data_features = vectorizer.transform(surgery_trial) clf.predict_proba(test_data_features) wikipedia_surgery = "is a medical specialty that uses operative manual and instrumental techniques\ on a patient to investigate or treat a pathological condition such as a disease or injury, to help\ improve bodily function or appearance or to repair\ unwanted ruptured areas" wikipedia_surgery = [re.sub("[^a-zA-Z0-9]"," ", wikipedia_surgery)] test_data_features = vectorizer.transform(wikipedia_surgery) clf.predict_proba(test_data_features) repeated_word = "operative " * 10 print(repeated_word) test_data_features = vectorizer.transform([repeated_word]) clf.predict_proba(test_data_features) ```
github_jupyter
# Gaia DR2 variability catalogs ## Part IV: Compare K2-derived period with Gaia-periods In this notebook we quantify the rotation period differences between Gaia and K2. gully May 3, 2018 ``` # %load /Users/obsidian/Desktop/defaults.py import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline %config InlineBackend.figure_format = 'retina' df_single = pd.read_csv('../data/analysis/k2_gaia_rotmod_single.csv') df_single.shape df_single.head() ``` Let's determine the K2 period for each source and plot it against the Gaia period. ``` df_single['k2_period'] = 0.0 from lightkurve import KeplerLightCurveFile k2_lc = KeplerLightCurveFile.from_archive(201103864.0) lc = k2_lc.get_lightcurve('SAP_FLUX') lc.plot() from gatspy import periodic import lightkurve x_lims = (11.8/3, 11.8*3) model = periodic.LombScargle() model.optimizer.period_range = x_lims gi = (lc.time == lc.time) & (lc.flux == lc.flux) time = lc.time[gi] flux = lc.flux[gi] flux_err = flux*0.0+np.nanmedian(flux) model.fit(time, flux, flux_err) periods = np.linspace(*x_lims, 10000) import warnings with warnings.catch_warnings(): warnings.simplefilter("ignore") scores = model.score(periods) # Plot the results fig, ax = plt.subplots(figsize=(8, 3)) fig.subplots_adjust(bottom=0.2) ax.plot(periods, scores) ax.set(xlabel='period (days)', ylabel='Lomb Scargle Power', xlim=x_lims); ``` Gaia [Documentation section 14.3.6](https://gea.esac.esa.int/archive/documentation/GDR2/Gaia_archive/chap_datamodel/sec_dm_variability_tables/ssec_dm_vari_rotation_modulation.html) explains that some of the columns are populated with *arrays*! So this catalog can be thought of as a **table-of-tables**. The typical length of the tables are small, usually just 3-5 entries. ``` df0.num_segments.describe() df0.loc[1] ``` I think the segments further consist of lightcurves, for which merely the summary statistics are listed here, but I'm not sure. Since all the files are still only 150 MB, we can just read in all the files and concatenate them. ``` import glob fns = glob.glob('../data/dr2/Gaia/gdr2/vari_rotation_modulation/csv/VariRotationModulation_*.csv.gz') n_files = len(fns) ``` This step only takes a few seconds. Let's use a progress bar to keep track. ``` from astropy.utils.console import ProgressBar df_rotmod = pd.DataFrame() with ProgressBar(n_files, ipython_widget=True) as bar: for i, fn in enumerate(fns): df_i = pd.read_csv(fn) df_rotmod = df_rotmod.append(df_i, ignore_index=True) bar.update() df_rotmod.shape ``` We have 147,535 rotationally modulated variable stars. What is the typical number of segments across the entire catalog? ``` df_rotmod.num_segments.hist(bins=11) plt.yscale('log') plt.xlabel('$N_{\mathrm{segments}}$') plt.ylabel('occurence'); ``` What are these segments? Are they the arbitrary Gaia segments, or are they something else? Let's ask our first question: **What are the distribution of periods?** >`best_rotation_period` : Best rotation period (double, Time[day]) >this field is an estimate of the stellar rotation period and is obtained by averaging the periods obtained in the different segments ``` df_rotmod.best_rotation_period.hist(bins=30) plt.yscale('log') plt.xlabel('$P_{\mathrm{rot}}$ [days]') plt.ylabel('$N$') ``` Next up: **What are the distribution of amplitudes?** We will use the `segments_activity_index`: > segments_activity_index : Activity Index in segment (double, Magnitude[mag]) >this array stores the activity indexes measured in the different segments. In a given segment the amplitude of variability A is taken as an index of the magnetic activity level. The amplitude of variability is measured by means of the equation: $$A=mag_{95}−mag_{5}$$ > where $mag_{95}$ and $mag_{5}$ are the 95-th and the 5-th percentiles of the G-band magnitude values. ``` df_rotmod.max_activity_index.hist(bins=30) plt.yscale('log') plt.xlabel('$95^{th} - 5^{th}$ variability percentile[mag]') plt.ylabel('$N$'); ``` Wow, $>0.4$ magnitudes is a lot! Most have much lower amplitudes. The problem with *max* activity index is that it may be sensitive to *flares*. Instead, let's use the $A$ and $B$ coefficients of the $\sin{}$ and $\cos{}$ functions: >`segments_cos_term` : Coefficient of cosine term of linear fit in segment (double, Magnitude[mag]) >if a significative period T0 is detected in a time-series segment, then the points of the time-series segment are fitted with the function $$mag(t) = mag_0 + A\cos(2\pi T_0 t) + B \sin(2\pi T_0 t)$$ Let's call the total amplitude $\alpha$, then we can apply: $\alpha = \sqrt{A^2+B^2}$ ``` val = df_rotmod.segments_cos_term[0] val ``` Gasp! The arrays are actually stored as strings! We need to first convert them to numpy arrays. ``` np.array(eval(val)) NaN = np.NaN #Needed for all the NaN values in the strings. clean_strings = lambda str_in: np.array(eval(str_in)) ``` Only run this once: ``` if type(df_rotmod['segments_cos_term'][0]) == str: df_rotmod['segments_cos_term'] = df_rotmod['segments_cos_term'].apply(clean_strings) df_rotmod['segments_sin_term'] = df_rotmod['segments_sin_term'].apply(clean_strings) else: print('Skipping rewrite.') amplitude_vector = (df_rotmod.segments_sin_term**2 + df_rotmod.segments_cos_term**2)**0.5 df_rotmod['mean_amplitude'] = amplitude_vector.apply(np.nanmean) ``` Let's compare the `max_activity_index` with the newly determined mean amplitude. The $95^{th}$ to $5^{th}$ percentile should be almost-but-not-quite twice the amplitude: ``` amp_conv_factor = 1.97537 x_dashed = np.linspace(0,1, 10) y_dashed = amp_conv_factor * x_dashed plt.figure(figsize=(5,5)) plt.plot(df_rotmod.mean_amplitude, df_rotmod.max_activity_index, '.', alpha=0.05) plt.plot(x_dashed, y_dashed, 'k--') plt.xlim(0,0.5) plt.ylim(0,1); plt.xlabel(r'Mean cyclic amplitude, $\alpha$ [mag]') plt.ylabel(r'$95^{th} - 5^{th}$ variability percentile[mag]'); ``` The lines track decently well. There's some scatter! Probably in part due to non-sinusoidal behavior. Let's convert the mean magnitude amplitude to an unspotted-to-spotted flux ratio: ``` df_rotmod['amplitude_linear'] = 10**(-df_rotmod.mean_amplitude/2.5) df_rotmod['amplitude_linear'].hist(bins=500) plt.xlim(0.9, 1.01) plt.figure(figsize=(5,5)) plt.plot(df_rotmod.best_rotation_period, df_rotmod.amplitude_linear, '.', alpha=0.01) plt.xlim(0, 60) plt.ylim(0.9, 1.04) plt.xlabel('$P_{\mathrm{rot}}$ [days]') plt.text(1, 0.92, ' Rapidly rotating\n spot dominated') plt.text(36, 1.02, ' Slowly rotating\n facular dominated') plt.ylabel('Flux decrement $(f_{\mathrm{spot, min}})$ '); ``` Promising! Let's read in the Kepler data and cross-match! This cross-match with Gaia and K2 data comes from Meg Bedell. ``` from astropy.table import Table k2_fun = Table.read('../../K2-metadata/metadata/k2_dr2_1arcsec.fits', format='fits') len(k2_fun), len(k2_fun.columns) ``` We only want a few of the 95 columns, so let's select a subset. ``` col_subset = ['source_id', 'epic_number', 'tm_name', 'k2_campaign_str'] k2_df = k2_fun[col_subset].to_pandas() ``` The `to_pandas()` method returns byte strings. Arg! We'll have to clean it. Here is a reuseable piece of code: ``` def clean_to_pandas(df): '''Cleans a dataframe converted with the to_pandas method''' for col in df.columns: if type(k2_df[col][0]) == bytes: df[col] = df[col].str.decode('utf-8') return df k2_df = clean_to_pandas(k2_df) df_rotmod.columns keep_cols = ['source_id', 'num_segments', 'best_rotation_period', 'amplitude_linear'] ``` We can **merge** (e.g. SQL *join*) these two dataframes on the `source_id` key. ``` k2_df.head() df_rotmod[keep_cols].head() ``` We'll only keep columns that are in both catalogs. ``` df_comb = pd.merge(k2_df, df_rotmod[keep_cols], how='inner', on='source_id') df_comb.head() df_comb.shape ``` Only 524 sources appear in both catalogs! Boo! Well, better than nothing! It's actually even fewer K2 targets, since some targets are single in K2 but have two or more matches in Gaia. These could be background stars or bona-fide binaries. Let's flag them. ``` multiplicity_count = df_comb.groupby('epic_number').\ source_id.count().to_frame().\ rename(columns={'source_id':'multiplicity'}) df = pd.merge(df_comb, multiplicity_count, left_on='epic_number', right_index=True) df.head(20) ``` Let's cull the list and just use the "single" stars, which is really the sources for which Gaia did not identify more than one target within 1 arcsecond. ``` df_single = df[df.multiplicity == 1] df_single.shape ``` A mere 224 sources! Boo hoo! ``` plt.figure(figsize=(5,5)) plt.plot(df_single.best_rotation_period, df_single.amplitude_linear, '.', alpha=0.1) plt.xlim(0, 60) plt.ylim(0.9, 1.04) plt.xlabel('$P_{\mathrm{rot}}$ [days]') plt.text(1, 0.92, ' Rapidly rotating\n spot dominated') plt.text(36, 1.02, ' Slowly rotating\n facular dominated') plt.ylabel('Flux decrement $(f_{\mathrm{spot, min}})$ ') plt.title('K2 x Gaia x rotational modulation'); ``` The points look drawn from their parent population. ``` df_single.sort_values('amplitude_linear', ascending=True).head(25).style.format({'source_id':"{:.0f}", 'epic_number':"{:.0f}"}) ``` Let's see if we can examine some of these Gaia lightcurves and compare them to K2 lightcurves. We'll do that in the next notebook.
github_jupyter
### OmicsDI This notebook helps you to generate an `omics.xml` file to integrate Cell Collective with [omics.org](omicsdi.org). Begin by importing the ccapi module into your workspace. ``` import ccapi from html import escape from lxml import etree from datetime import datetime from IPython.display import FileLink from ccapi.limits import MAX_UNSIGNED_SHORT from ccapi.util.string import safe_decode from ccapi.util.array import squash, flatten ``` Now, let’s try creating a client object in order to interact with services provided by [Cell Collective](https://cellcollective.org). ``` client = ccapi.Client(cache_timeout = 24 * 60 * 60) models = client.get("model", size = MAX_UNSIGNED_SHORT, filters = { "domain": "research" }) models ``` ### OmicsDI XML Format ``` def format_datetime(datetime): return datetime.strftime("%Y-%m-%d") def get_updated_date(model): if model.updated["biologic"] and model.updated["knowledge"]: return model.updated["biologic"] if model.updated["biologic"] > model.updated["knowledge"] \ else model.updated["knowledge"] return model.updated["biologic"] if model.updated["biologic"] else model.updated["knowledge"] def get_entry(model): entries = [ ] for version in model.versions: entry = f"""\ <entry id="{model.id}"> <name>{escape(model.name)}</name> <description>{escape(model.description or "")}</description> <dates> <date type="created" value="{format_datetime(version.created)}"/> <date type="last_modified" value="{get_updated_date(model)}"/> <date type="submission" value="{get_updated_date(model)}"/> <date type="publication" value=""/> </dates> <additional_fields> <field name="submitter">{escape(model.user.name or "")}</field> <field name="submitter_email">{model.user.email or ""}</field> <field name="submitter_affiliation">{escape(model.user.institution or "")}</field> <field name="repository">Cell Collective</field> <field name="ModelFormat">SBML</field> <field name="omics_type">Models</field> <field name="full_dataset_link">{escape(model.url)}</field> <field name="version_id">{version.version}</field> <field name="version_name">{escape(version.name or "")}</field> <field name="version_description">{escape(version.description or "")}</field> <field name="version_url">{escape(version.url)}</field> <field name="default_version">{model.default_version.version}</field> <field name="model_created">{model.created}</field> <field name="model_score">{model.score}</field> </additional_fields> </entry>\ """ entries.append(entry) return entries entries = "\n".join(flatten(map(get_entry, models))) xml = etree.fromstring(f""" <database> <name>Cell Collective</name> <description>Interactive Modelling of Biological Networks</description> <contact>support@cellcollective.org</contact> <url>https://cellcollective.org</url> <release>{client.version}</release> <release_date></release_date> <entry_count>{len(models)}</entry_count> <entries> {entries} </entries> </database> """) with open("_data/omics.xml", "w") as f: f.write(safe_decode(etree.tostring(xml))) FileLink("_data/omics.xml") ```
github_jupyter
# My first neural network Today we're gonna utilize the dark magic from previous assignment to write a neural network `in pure numpy`. ``` import numpy as np %matplotlib inline import matplotlib.pyplot as plt from classwork_auxiliary import eval_numerical_gradient,eval_numerical_gradient_array,rel_error ``` # Module template We will implement our neural network as a set of layers. Basically, you can think of a module as of a something (black box) that can process `input` data and produce `ouput` data. * affine transform: f(x) = w*x + b * nonlinearity: f(x) = max(0,x) * loss function This is like applying a function which is called `forward`: * `output = module.forward(input)` The module should be able to perform a __backward pass__: to differentiate the `forward` function. More, it should be able to differentiate it if is a part of chain (chain rule). The latter implies there is a gradient from previous step of a chain rule. * `gradInput = module.backward(input, gradOutput)` Below is a base class for all future modudes. _You're not required to modify it ``` class Module(object): def __init__ (self): self.output = None self.gradInput = None def forward(self, input): """ Takes an input object, and computes the corresponding output of the module. """ return self.updateOutput(input) def backward(self,input, gradOutput): """ Performs a backpropagation step through the module, with respect to the given input. This includes - computing a gradient w.r.t. `input` (is needed for further backprop), - computing a gradient w.r.t. parameters (to update parameters while optimizing). """ self.updateGradInput(input, gradOutput) self.accGradParameters(input, gradOutput) return self.gradInput def updateOutput(self, input): """ Computes the output using the current parameter set of the class and input. This function returns the result which is stored in the `output` field. Make sure to both store the data in `output` field and return it. """ # The easiest case: # self.output = input # return self.output pass def updateGradInput(self, input, gradOutput): """ Computing the gradient of the module with respect to its own input. This is returned in `gradInput`. Also, the `gradInput` state variable is updated accordingly. The shape of `gradInput` is always the same as the shape of `input`. Make sure to both store the gradients in `gradInput` field and return it. """ # The easiest case: # self.gradInput = gradOutput # return self.gradInput pass def accGradParameters(self, input, gradOutput): """ Computing the gradient of the module with respect to its own parameters. No need to override if module has no parameters (e.g. ReLU). """ pass def zeroGradParameters(self): """ Zeroes `gradParams` variable if the module has params. """ pass def getParameters(self): """ Returns a list with its parameters. If the module does not have parameters return empty list. """ return [] def getGradParameters(self): """ Returns a list with gradients with respect to its parameters. If the module does not have parameters return empty list. """ return [] def __repr__(self): """ Pretty printing. Should be overrided in every module if you want to have readable description. """ return "Module" ``` ## Linear layer a.k.a. affine or dense layer We will now implement this layer by __filling the gaps in code__ ``` class Linear(Module): """ A module which applies a linear transformation A common name is fully-connected layer, InnerProductLayer in caffe. The module should work with 2D input of shape (n_samples, n_feature). """ def __init__(self, n_in, n_out): super(Linear, self).__init__() self.W = <initialize a random weight matrix of size (n_out,n_in).> self.b = <initialize bias vector of size (n_out)> #here we initialize gradients with zeros. We'll accumulate them later. self.gradW = np.zeros_like(self.W) self.gradb = np.zeros_like(self.b) def updateOutput(self, input): """given X input, produce output""" self.output = <affine transform of input using self.W and self.b. Remember to transpose W> return self.output def updateGradInput(self, input, gradOutput): """given input and dL/d_output, compute dL/d_input""" self.gradInput = <gradient of this layer w.r.t. input. You will need gradOutput and self.W> assert self.gradOutput.shape == input.shape,"wrong shape" return self.gradInput def accGradParameters(self, input, gradOutput): """given input and dL/d_output, compute""" self.gradW = <compute gradient of loss w.r.t. weight matrix. You will need gradOutput and input> assert self.gradW.shape == self.W.shape self.gradb = <compute gradient of loss w.r.t. bias vector> assert self.gradb.shape == self.b.shape return self.gradW, self.gradb def zeroGradParameters(self): self.gradW.fill(0) self.gradb.fill(0) def getParameters(self): return [self.W, self.b] def getGradParameters(self): return [self.gradW, self.gradb] ``` ### Test linear layer ``` n_in, n_out = 5, 6 x = np.random.randn(10, 6) w = np.random.randn(17, 6) b = np.random.randn(17) dout = np.random.randn(10, 17) dx_num = eval_numerical_gradient_array(lambda x: Linear(n_in, n_out, w, b).updateOutput(x), x, dout) dw_num = eval_numerical_gradient_array(lambda w: Linear(n_in, n_out, w, b).updateOutput(x), w, dout) db_num = eval_numerical_gradient_array(lambda b: Linear(n_in, n_out, w, b).updateOutput(x), b, dout) dx = Linear(n_in, n_out, w, b).updateGradInput(x, dout) dw, db = Linear(n_in, n_out, w, b).accGradParameters(x, dout) print 'Testing Linear (errors should be < 1e-6):' print '\t dx error: ', rel_error(dx_num, dx) print '\t dw error: ', rel_error(dw_num, dw) print '\t db error: ', rel_error(db_num, db) ``` ## Softmax layer ``` class SoftMax(Module): def __init__(self): super(SoftMax, self).__init__() def updateOutput(self, input): """forward pass of softmax nonlinearity""" # substract max for numerical stability input = input - input.max(axis=1, keepdims=True) self.output = <compute softmax forward pass> return self.output def updateGradInput(self, input, gradOutput): """backward pass of the same thing""" exp = np.exp(np.subtract(input, input.max(axis=1, keepdims=True))) denom = exp.sum(axis=1, keepdims=True) e = np.diag(exp.dot(gradOutput.T)) self.gradInput = - np.diag(e).dot(exp) self.gradInput += exp * denom * gradOutput self.gradInput /= denom**2 return self.gradInput x = np.random.randn(10, 6) dout = np.random.randn(10, 6) dx_num = eval_numerical_gradient_array(SoftMax().updateOutput, x, dout) dx = SoftMax().updateGradInput(x, dout) print 'Testing SoftMax(errors should be < 1e-6):' print '\t dx error: ', rel_error(dx_num, dx) ``` ## Loss function You task is to implement the **ClassNLLCriterion**. It should implement [multiclass log loss](https://www.kaggle.com/wiki/MultiClassLogLoss). Nevertheless there is a sum over `y` (target) in that formula, remember that targets are one-hot encoded. This fact simplifies the computations a lot. ``` from classwork_auxiliary import Criterion class ClassNLLCriterion(Criterion): def updateOutput(self, input, target): self.output = <Your code goes here> return self.output def updateGradInput(self, input, target): self.gradInput = <Your code goes here> return self.gradInput x = np.random.randn(10, 6)+5 target = np.random.randint(0, 10, x.shape[0]).reshape((-1, 1)) dx_num = eval_numerical_gradient(lambda x: ClassNLLCriterion().updateOutput(x, target), x, verbose=False) dx = ClassNLLCriterion().updateGradInput(x, target) print 'Testing ClassNLLCriterion (errors should be < 1e-6):' print '\t dx error: ', rel_error(dx_num, dx) ``` # Toy example Use this example to debug your code, start with logistic regression and then test other layers. You do not need to change anything here. This code is provided for you to test the layers. Also it is easy to use this code in MNIST task. ``` # Generate some data N = 500 X1 = np.random.randn(N,2) + np.array([2,2]) X2 = np.random.randn(N,2) + np.array([-2,-2]) Y = np.concatenate([np.ones(N), np.zeros(N)])[:,None] Y = np.hstack([Y, 1-Y]) X = np.vstack([X1,X2]) plt.scatter(X[:,0],X[:,1], c = Y[:,0], cmap='hot') ``` Here we define a **logistic regression** for debugging. ``` from classwork_auxiliary import Sequential,sgd_momentum net = Sequential() net.add(Linear(2, 2)) net.add(SoftMax()) criterion = ClassNLLCriterion() ``` Start with batch_size = 1000 to make sure every step lowers the loss, then try stochastic version. ``` # Iptimizer params optimizer_config = {'learning_rate' : 1e-1, 'momentum': 0.9} optimizer_state = {} # Looping params n_epoch = 100 batch_size = 1000 # batch generator def get_batches( (X, Y) , batch_size): n_samples = X.shape[0] # Shuffle at the start of epoch indices = np.arange(n_samples) np.random.shuffle(indices) for start in range(0, n_samples, batch_size): end = min(start + batch_size, n_samples) batch_idx = indices[start:end] yield X[batch_idx], Y[batch_idx] ``` ### Train Basic training loop. Examine it. ``` loss_history = [] for i in range(n_epoch): for x_batch, y_batch in get_batches( (X,Y) , batch_size): net.zeroGradParameters() # Forward predictions = net.forward(x_batch) loss = criterion.forward(predictions, y_batch) # Backward dp = criterion.backward(predictions, y_batch) net.backward(x_batch, dp) # Update weights sgd_momentum(net.getParameters(), net.getGradParameters(), optimizer_config, optimizer_state) loss_history.append(loss) print('Current loss: %f' % loss) if loss <= 0.01: print ("Well done") else: print ("Something's wrong!") ``` ## Rectified linear unit Here you will define a nonlinearity function used to build neural networks. For starters, let't build rectified linear unit. ``` class ReLU(Module): def __init__(self): super(ReLU, self).__init__() def updateOutput(self, input): self.output = <Your code. Please remember to use np.maximum and not np.max> return self.output def updateGradInput(self, input, gradOutput): self.gradInput = <gradient of loss w.r.t. input (passing through ReLU)> return self.gradInput x = np.random.randn(10, 6)-0.5 dout = np.random.randn(10, 6)-0.5 dx_num = eval_numerical_gradient_array(ReLU().updateOutput, x, dout) dx = ReLU().updateGradInput(x, dout) print 'Testing ReLU (should be < 1e-6):' print '\t dx error: ', rel_error(dx_num, dx) ``` # Digit classification Let's not try to build actuall neural network on a mnist dataset. ``` import os from classwork_auxiliary import load_dataset X_train,y_train,X_test,y_test = load_dataset() ``` ## Build neural network By default the code below runs logistic regression. After you made sure it runs, __modify it__ to train a neural network. Evaluate how it fares with different number of hidden units. ``` from classwork_auxiliary import Sequential,sgd_momentum net = Sequential() net.add(Linear(28*28, 10)) #you may want to replace this guy with more layers once you got the basic setup working net.add(SoftMax()) criterion = ClassNLLCriterion() loss_train_history = [] loss_validation_history = [] optimizer_config = {'learning_rate' : 1e-1, 'momentum': 0.9} optimizer_state = {} n_epoch=40 batch_size=1000 learning_rate=0.001 #try decreasing over time for i in range(n_epoch): for x_batch, y_batch in get_batches((X_train, y_train ), batch_size): net.zeroGradParameters() predictions = net.forward(x_batch) loss_train = criterion.forward(predictions, y_batch) loss_train_history.append(loss_train) dp = criterion.backward(predictions, y_batch) net.backward(x_batch, dp) sgd_momentum(net.getParameters(), net.getGradParameters(), optimizer_config, optimizer_state) test_idx = np.random.randint(0, X_test.shape[0], batch_size) loss_test = criterion.forward(net.forward(X_test[test_idx]),y_test[test_idx]) loss_validation_history.append(loss_test) print('epoch %s: rate = %f, loss_train = %f, loss_test = %f' % (i, learning_rate, loss_train, loss_test)) ``` ### Once you got it working Go to HW3_* notebook. The homework starts there. You're welcome to re-use code for modules (liner, softmax, relu and loss) in the homework.
github_jupyter
# Stochastic Block Model (SBM) ``` import graspy import matplotlib.pyplot as plt import numpy as np %matplotlib inline ``` Unlike [Erdos-Renyi (ER) models](./erdos_renyi.ipynb), SBM tends to produce graphs containing communities, subsets characterized by being connected with one another with particular edge densities. For example, edges may be more common within communities than between communities <sup>[1](https://en.wikipedia.org/wiki/Stochastic_block_model)</sup>. SBM is parametrized by $n$, which specifies the number of vertices in each community, and a block probability matrix, $P$, where each element specifies the probability of an edge in a particular block and has size that is number of communites by number of communities. One can think of SBM as a collection of ER graphs where each block corresponds to an ER graph. Below, we sample a two-block SBM (undirected, no self-loops) with following parameters: \begin{align*} n &= [50, 50]\\ P &= \begin{bmatrix} 0.5 & 0.2\\ 0.2 & 0.05 \end{bmatrix} \end{align*} The diagonals correspond to probability of an edge within blocks and the off-diagonals correspond to probability of an edge across blocks. ``` from graspy.simulations import sbm n = [50, 50] p = [[0.5, 0.2], [0.2, 0.05]] np.random.seed(1) G = sbm(n=n, p=p) ``` ## Visualize the graph using heatmap ``` from graspy.plot import heatmap heatmap(G, title ='SBM Simulation') ``` ## Weighted SBM Graphs Similar to ER simulations, *sbm* functions provide ways to sample weights for all edges that were sampled via a probability distribution function. In order to sample with weights, you can either: 1. Provide *single* probability distribution function with corresponding keyword arguments for the distribution function. All weights will be sampled using the same function. 2. Provide a probability distribution function with corresponding keyword arguments for each block. Below we sample a SBM (undirected, no self-loops) with the following parameters: \begin{align*} n &= [50, 50]\\ P &= \begin{bmatrix}0.5 & 0.2\\ 0.2 & 0.05 \end{bmatrix} \end{align*} and the weights are sampled from the following probability functions: \begin{align*} PDFs &= \begin{bmatrix}Normal & Poisson\\ Poisson & Normal \end{bmatrix}\\ Parameters &= \begin{bmatrix}{\mu=3, \sigma^2=1} & {\lambda=5}\\ {\lambda=5} & {\mu=3, \sigma^2=1} \end{bmatrix} \end{align*} ``` from numpy.random import normal, poisson n = [50, 50] p = [[0.5, 0.2], [0.2, 0.05]] wt = [[normal, poisson], [poisson, normal]] wtargs = [[dict(loc=3, scale=1), dict(lam=5)], [dict(lam=5), dict(loc=3, scale=1)]] G = sbm(n=n, p=p, wt=wt, wtargs=wtargs) ``` ## Visualize the graph using heatmap ``` heatmap(G, title='Weighted SBM Simulation') ```
github_jupyter
``` %matplotlib inline ``` # Arrow guide Adding arrow patches to plots. Arrows are often used to annotate plots. This tutorial shows how to plot arrows that behave differently when the data limits on a plot are changed. In general, points on a plot can either be fixed in "data space" or "display space". Something plotted in data space moves when the data limits are altered - an example would the points in a scatter plot. Something plotted in display space stays static when data limits are altered - an example would be a figure title or the axis labels. Arrows consist of a head (and possibly a tail) and a stem drawn between a start point and end point, called 'anchor points' from now on. Here we show three use cases for plotting arrows, depending on whether the head or anchor points need to be fixed in data or display space: 1. Head shape fixed in display space, anchor points fixed in data space 2. Head shape and anchor points fixed in display space 3. Entire patch fixed in data space Below each use case is presented in turn. ``` import matplotlib.patches as mpatches import matplotlib.pyplot as plt x_tail = 0.1 y_tail = 0.1 x_head = 0.9 y_head = 0.9 dx = x_head - x_tail dy = y_head - y_tail ``` Head shape fixed in display space and anchor points fixed in data space ----------------------------------------------------------------------- This is useful if you are annotating a plot, and don't want the arrow to to change shape or position if you pan or scale the plot. Note that when the axis limits change In this case we use `.patches.FancyArrowPatch` Note that when the axis limits are changed, the arrow shape stays the same, but the anchor points move. ``` fig, axs = plt.subplots(nrows=2) arrow = mpatches.FancyArrowPatch((x_tail, y_tail), (dx, dy), mutation_scale=100) axs[0].add_patch(arrow) arrow = mpatches.FancyArrowPatch((x_tail, y_tail), (dx, dy), mutation_scale=100) axs[1].add_patch(arrow) axs[1].set_xlim(0, 2) axs[1].set_ylim(0, 2) ``` Head shape and anchor points fixed in display space --------------------------------------------------- This is useful if you are annotating a plot, and don't want the arrow to to change shape or position if you pan or scale the plot. In this case we use `.patches.FancyArrowPatch`, and pass the keyword argument ``transform=ax.transAxes`` where ``ax`` is the axes we are adding the patch to. Note that when the axis limits are changed, the arrow shape and location stays the same. ``` fig, axs = plt.subplots(nrows=2) arrow = mpatches.FancyArrowPatch((x_tail, y_tail), (dx, dy), mutation_scale=100, transform=axs[0].transAxes) axs[0].add_patch(arrow) arrow = mpatches.FancyArrowPatch((x_tail, y_tail), (dx, dy), mutation_scale=100, transform=axs[1].transAxes) axs[1].add_patch(arrow) axs[1].set_xlim(0, 2) axs[1].set_ylim(0, 2) ``` Head shape and anchor points fixed in data space ------------------------------------------------ In this case we use `.patches.Arrow` Note that when the axis limits are changed, the arrow shape and location changes. ``` fig, axs = plt.subplots(nrows=2) arrow = mpatches.Arrow(x_tail, y_tail, dx, dy) axs[0].add_patch(arrow) arrow = mpatches.Arrow(x_tail, y_tail, dx, dy) axs[1].add_patch(arrow) axs[1].set_xlim(0, 2) axs[1].set_ylim(0, 2) plt.show() ```
github_jupyter
# Summary `# TODO: summary here` ``` %load_ext autoreload %autoreload 3 from abc import ABC, abstractmethod from collections.abc import Iterable, Mapping import gc import matplotlib.pyplot as plt import numpy as np import os from pathlib import Path import torch from transformers import PegasusForConditionalGeneration, PegasusTokenizer, \ PegasusTokenizerFast, pipeline from htools import * from incendio.utils import DEVICE, gpu_setup gpu_setup(False) version = 'tuner007/pegasus_paraphrase' net = PegasusForConditionalGeneration.from_pretrained(version).to(DEVICE) tok = PegasusTokenizerFast.from_pretrained(version) texts = [ 'Educational games and digital learning materials to provide K-12 ' 'students with enriching experiences.', 'The world\'s largest social network. Helping people build and maintain ' 'relationships in a disconnected world.', 'I hate school. I wish my teacher would leave me alone. I don\'t think ' ' he likes me.', 'Today the president announced new plans to revamp the private ' 'healthcare system. Pundits questioned how he would manage to pass the ' 'bill.' ] res = tok.prepare_seq2seq_batch(texts, truncation=True, padding='longest') res gen = net.generate(**res) tok.batch_decode(gen.tolist(), skip_special_tokens=True) @add_docstring(net.generate) def paraphrase(text, n=1, temperature=1.5, **gen_kwargs): batch = tok.prepare_seq2seq_batch([text], truncation=True, padding='longest').to(DEVICE) paraphrased = net.generate(**batch, num_return_sequences=n, temperature=temperature, **gen_kwargs) return tok.batch_decode(paraphrased.tolist(), skip_special_tokens=True) paraphrase(texts[3], n=5, num_beams=10) texts[-1] net.generate() ``` ## ParaphrasePipeline ``` class ParaphrasePipeline: def __init__(self, name='tuner007/pegasus_paraphrase', net=None, tok=None): self.name = name self.net = (net or PegasusForConditionalGeneration.from_pretrained(name))\ .to(DEVICE) self.tok = tok or PegasusTokenizerFast.from_pretrained(self.name) @add_docstring(PegasusForConditionalGeneration.generate) def __call__(self, text, n=1, temperature=1.5, **kwargs): # TODO: not sure how many rows of text can be done in a single batch. # Maybe look at other pipelines to see what they do. I'm thinking we # could auto-batch longer sequences (e.g. a list w/ 10_000 strings # might become 100 batches of 100). texts = tolist(text) batch = self.tok.prepare_seq2seq_batch(texts, truncation=True, padding='longest').to(DEVICE) # Number of beams must be >= number of sequences to return. num_beams = max(n, self.net.config.num_beams, kwargs.pop('num_beams', -1)) gen_tokens = self.net.generate(**batch, num_return_sequences=n, temperature=temperature, num_beams=num_beams, **kwargs) gen = self.tok.batch_decode(gen_tokens.tolist(), skip_special_tokens=True) if not isinstance(text, str) and len(text) > 1: gen = [gen[i*n:(i+1)*n] for i in range(len(text))] return gen # Slightly updated version (if at all) from incendio. Ended up deleting this # # because I found we can use Text2TextGenerationPipeline. # class ParaphrasePipeline: # """Similar to a transformers Pipeline, this provides a high level # interface for paraphrasing text. It's pretty slow so it's worth using this # on a GPU when processing many examples. # """ # def __init__(self, name='tuner007/pegasus_paraphrase', net=None, # tok=None): # """ # Parameters # ---------- # name: str # Name of pretrained model to load. This will download weights from # Huggingface's model hub (https://huggingface.co/models. In # practice the name should rarely change but we want to give users # the option in case you train a better paraphrasing model. # Name Parameters Download Size # tuner007/pegasus_paraphrase 568,822,784 2.28 GB # ramsrigouthamg/t5_paraphraser 222,903,936 892 MB # net: None or nn.Module # Pytorch model, usually PegasusForConditionalGeneration. If None, # a new model will be instantiated. # tok: None or transformers tokenizer # A new one will be instantiated by default, but you can also pass # one in. This must be the correct tokenizer for the `net` being # used. # """ # self.name = name # self.net = (net # or PegasusForConditionalGeneration.from_pretrained(name))\ # .to(DEVICE) # self.tok = tok or PegasusTokenizerFast.from_pretrained(self.name) # @add_docstring(PreTrainedModel.generate) # def __call__(self, text, n=1, **kwargs): # """Paraphrase one or more pieces of text. We do no auto-batching yet # so you may need to split your data up into mini batches when working # with many rows. # Parameters # ---------- # text: str or Iterable[str] # n: int # Number of variations to generate per sample. # kwargs: any # Passed on to net's generate function. Its docstring is included # below for convenience. # Returns # ------- # list: If input is a single string, a list of n strings is returned. # If input is a lsit of strings, a list of nested lists, each of length # n, is returned. # """ # texts = tolist(text) # batch = self.tok.prepare_seq2seq_batch(texts, truncation=True, # padding='longest').to(DEVICE) # # Number of beams must be >= number of sequences to return. # num_beams = max(n, self.net.config.num_beams, # kwargs.pop('num_beams', -1)) # gen_tokens = self.net.generate(**batch, num_return_sequences=n, # num_beams=num_beams, # **{'temperature': 1.5, **kwargs}) # gen = self.tok.batch_decode(gen_tokens.tolist(), # skip_special_tokens=True) # if not isinstance(text, str) and len(text) > 1: # gen = [gen[i*n:(i+1)*n] for i in range(len(text))] # return gen p_pipe = ParaphrasePipeline(net=net, tok=tok) p_pipe.net.config.num_beams p_pipe('It was a beautiful rainy day.') p_pipe('It was a beautiful rainy day.', n=3) p_pipe(['It was a beautiful rainy day.', 'The duck was yellow and fluffy.']) p_pipe(['It was a beautiful rainy day.', 'The duck was yellow and fluffy.'], n=3) p_pipe(['It was a beautiful rainy day.'], n=2) # Decided to abandon this. Too many ways children differ: paraphrase pipeline # can't create pipe with pipeline(name) because it's not part of huggingface, # paraphrase transform doesn't need to check if listlike because preprocess # does nothing and __call__ literally just calls pipe. Leaving this here as # an examle of init_subclass. class TransformerTransformBase(ABC): def __init__(self): pass def __call__(self, text, **kwargs): if listlike(text): return [self.transform(t, **kwargs) for t in text] return self.transform(text, **kwargs) @abstractmethod def transform(self, text, **kwargs): pass def __init_subclass__(cls, **kwargs): if not hasattr(cls, 'pipe_name'): raise RuntimeError(f'{cls} must have class attr "pipe_name".') with assert_raises(RuntimeError): class Tmp(TransformerTransformBase): """a""" ``` ## FillMaskTransform ``` @auto_repr class FillMaskTransform: MASK = '<mask>' name = 'fill-mask' def __init__(self, pipe=None, n=1, max_n=3): """ Parameters ---------- n: int n is intentionally bigger than the default n in __call__. This is the number of candidates generated, so if we use strategy='random' it makes sense for this to be larger. """ self.pipe = pipe or pipeline(self.name) self.n = n self.max_n = max_n assert type(self.pipe).__name__ == 'FillMaskPipeline' def _preprocess(self, text, min_keep=3, errors='raise'): """ errors: str If 'warn', we show a warning when min_keep is violated but allow masking to take place. """ if listlike(text): return [self._preprocess(row, min_keep, errors) for row in text] tokens = text.split() if len(tokens) < min_keep + 1: msg = (f'Text "{text[:25]}..." is too short to mask while ' f'enforcing min_keep={min_keep}.') if errors == 'warn': warnings.warn(msg) else: raise ValueError(msg) idx = np.random.choice(range(len(tokens))) return ' '.join(self.MASK if i == idx else t for i, t in enumerate(tokens)) def __call__(self, text, n=None, n_mask=1, min_keep=3, return_all=False, errors:('warn', 'raise')='raise', strategy:('random', 'best')='best'): """ n: int or None If -1, return all generated examples for the given mask count. This can become very large when n_mask is large. Recall pipeline can only fill a single mask at a time. e.g. if self.max_n is 3, n=-1, and n_mask is 4, we first mask once and generate 3 samples. Then we mask each of those 3 and generate a total of 9 samples, then 27, then finally 81 which is what will be returned. The intermediate samples can be returned with `return_all=True`. """ # Make sure we generate adequate number of sequences. Model topk must # be >= our desired n. n = n or self.n if n > self.max_n: self.max_n = n # Each item will be a list of strings. Each string in res[i] # will have i words changed. If text is a sequence of strings, we must # handle each one separately because each is passed through pipeline # repeatedly. if listlike(text): return [self(row, n, n_mask, min_keep, return_all, errors) for row in text] res = [[text]] for i in range(n_mask): seqs = self.pipe(self._preprocess(res[-1], min_keep=min_keep, errors=errors)) # Transformers returns either list of dicts or list of list of # dicts depending on whether input list has 1 item or multiple. if isinstance(seqs[0], list): seqs = [seq for group in seqs for seq in group] text = [seq['sequence'].replace('<s>', '').replace('</s>', '') for seq in seqs] # Keep all generated samples when n is -1. if n != -1: if strategy == 'random': text = np.random.choice(text, n, replace=False) elif strategy == 'best': text = text[:n] res.append(text) if not return_all: res = res[n_mask] return res @property def max_n(self): return self.pipe.topk @max_n.setter def max_n(self, max_n): if not isinstance(max_n, int): raise TypeError('max_n must be an integer.') if max_n < self.n: raise ValueError(f'max_n must be >= self.n (currently {self.n}.') self.pipe.topk = max_n t = 'I went to the store today to buy eggs.' ts = [t, 'The bird swooped down onto the picnic table and squawked loudly.'] # m_pipe = pipeline('fill-mask') m_tfm = FillMaskTransform(m_pipe) m_tfm m_tfm._preprocess(t) m_tfm._preprocess(ts) m_tfm(t, 2) m_tfm(t, 3, return_all=True) m_tfm(t, 4, n_mask=2, strategy='best') m_tfm(t, 4, n_mask=2, strategy='random') m_tfm(t, 3, n_mask=2, return_all=True) m_tfm(t, 1, return_all=True) m_tfm(ts) m_tfm(ts, 2) m_tfm(ts, n=None, n_mask=2) m_tfm(ts, n=None, n_mask=2, return_all=True) m_tfm = FillMaskTransform(m_pipe, 2, 5) m_tfm(t) m_tfm(ts) m_tfm(ts, n=6) ``` ## ParaphraseTransform ``` @auto_repr class ParaphraseTransform: """Not sure how useful this will really be but this basically just wraps ParaphrasePipeline to share a more similar interface with the other NLP transforms. """ name = 'tuner007/pegasus_paraphrase' def __init__(self, pipe=None, n=1): # We let user pass in pipe at least for now since re-instantiating the # class can be very slow during development. Need to consider whether # I want this behavior to remain. self.pipe = pipe or ParaphrasePipeline(self.name) self.n = n assert type(self.pipe).__name__ == 'ParaphrasePipeline' def _preprocess(self, text): """Does nothing (just want shared interface with other transforms).""" return text def __call__(self, text, n=None, **kwargs): return self.pipe(text, n=n or self.n, **kwargs) p_tfm = ParaphraseTransform(p_pipe) p_tfm p_tfm('The beach is loud and crowded today.', n=3) p_tfm(ts) p_tfm(ts, n=2) def listlike(x): """Checks if an object is a list/tuple/set/array etc. Strings and mappings (e.g. dicts) are not considered list-like. """ return isinstance(x, Iterable) and not isinstance(x, (str, Mapping)) for obj in ('a', 6, [], (), {}, set(), [3, 4], ['a', 'b'], ('a',), {'a': 'b'}, {'a', 'b'}, np.arange(5)): print(type(obj), listlike(obj)) ``` ## GenerativeTransform ``` @auto_repr class GenerativeTransform: name = 'text-generation' def __init__(self, pipe=None, n=1): # Allow user to pass in n here to reduce likelihood of needing to # create a partial from __call__. Maybe should add other __call__ # kwargs here? self.pipe = pipe or pipeline(self.name) self.n = n assert type(self.pipe).__name__ == 'TextGenerationPipeline' def _preprocess(self, text, drop=None, drop_pct=None, rand_low=None, rand_high=None, min_keep=3, return_tuple=False): """Truncate text.""" if listlike(text): return [self._preprocess(row, drop, drop_pct, rand_low, rand_high, min_keep, return_tuple) for row in text] tokens = text.split() if len(tokens) <= min_keep: n_drop = 0 else: # Default is to truncate the last 20% of the sequence. if drop: n_drop = drop elif drop_pct: n_drop = int(drop_pct * len(tokens)) elif rand_low is not None and rand_high is not None: n_drop = np.random.randint(rand_low, rand_high) else: n_drop = int(np.ceil(.2 * len(tokens))) n_drop = np.clip(n_drop, 0, len(tokens) - min_keep) tokens = tokens[:-n_drop] truncated = ' '.join(tokens) return (truncated, n_drop) if return_tuple else truncated def __call__(self, text, n=None, min_length=2, max_length=7, **generate_kwargs): n = n or self.n if listlike(text): return [self(row, n, min_length, max_length, **generate_kwargs) for row in text] # `generate` counts current length as part of min_length. text = self._preprocess(text) n_curr = len(self.pipe.tokenizer.tokenize(text)) res = self.pipe(text, min_length=n_curr + min_length, max_length=n_curr + max_length, num_return_sequences=n, **generate_kwargs) return [row['generated_text'] for row in res] # g_pipe = pipeline('text-generation') g_tfm = GenerativeTransform(g_pipe) g_tfm g_tfm._preprocess(t) g_tfm._preprocess(ts, return_tuple=True) g_tfm(t) g_tfm(t, n=2) g_tfm(ts) g_tfm(ts, n=2) # I'm now thinking this isn't that useful. It also loses our kwarg names # unless I pull some tricks altering signatures. Don't think this offers # enough benefit to justify that. class TransformerTransform: def __init__(self, mode, pipe=None): self.mode = mode self._transformer = self._get_transformer(pipe) def _preprocess(self, text, **kwargs): return self._transformer._preprocess(text, **kwargs) def __call__(self, text, **kwargs): return self._transformer(text, **kwargs) def _get_transformer(self, pipe): if self.mode == 'mask': return FillMaskTransform(pipe) elif self.mode == 'generate': return GenerativeTransform(pipe) elif self.mode == 'paraphrase': return ParaphraseTransform(pipe) else: raise ValueError('mode must be in (mask, generate, paraphrase).') mt = TransformerTransform('mask', m_pipe) mt._preprocess(t) mt._preprocess(ts, n=2) mt(t) mt(ts) ``` ## BackTranslationTransform Realized Huggingface provides no models for translating back to English. ``` class BackTranslationTransform: def __init__(self, pipe=None, n=1, from_lang='en', to_lang='fr', pipe_rev=None): self.name = f'translation_{from_lang}_to_{to_lang}' self.name_rev = f'translation_{to_lang}_to_{from_lang}' self.pipe = pipe or pipeline(self.name) self.pipe_rev = pipe_rev or pipeline(self.name_rev) def _preprocess(self, text): return text def __call__(self, text): trans = self.pipe(text) print(trans) return self.pipe_rev(trans) # b_tfm = BackTranslationTransform() ``` ## ParaphraseTransform v2 Found there actually is a built-in version of the pipeline that I think will work. Try it out. ``` from transformers import Text2TextGenerationPipeline, PreTrainedModel Text2TextGenerationPipeline.__name__ # export @auto_repr class ParaphraseTransform: """Text transform that paraphrases input text as a method of data augmentation. This is rather slow so it's recommended to precompute samples and save them, but you could generate samples on the fly if desired. One further downside of that approach is you'll have a huge paraphrasing model on the GPU while (presumably) training another model. Note: This just wraps ParaphrasePipeline to share a more similar interface with the other NLP transforms. Since no preprocessing is required, it's basically identical to ParaphrasePipeline. """ def __init__(self, pipe=None, n=1, name='tuner007/pegasus_paraphrase'): """ Parameters ---------- pipe: ParaphrasePipeline or None n: int Default number of samples to generate. You can override this in __call__. """ if pipe: self.pipe = pipe self.name = pipe.model.config._name_or_path else: self.pipe = Text2TextGenerationPipeline( PegasusForConditionalGeneration.from_pretrained(name), PegasusTokenizer.from_pretrained(name), device=0 if torch.cuda.is_available() else -1 ) self.name = name self.n = n assert type(self.pipe).__name__ == 'Text2TextGenerationPipeline' if 'cuda' not in str(self.pipe.device) and torch.cuda.is_available(): warnings.warn('The pipeline passed in is not using cuda. ' 'Did you mean to use the available GPU?') def _preprocess(self, text): """Does nothing (just want shared interface with other transforms).""" return text @add_docstring(PreTrainedModel.generate) def __call__(self, text, n=None, **kwargs): """ Parameters ---------- text: str or Iterable[str] Raw text to transform. n: int or None If None, use the default self.n. kwargs: any Additional kwargs are passed to the model's text generation method. Its docstring is included below for convenience. Returns ------- list: either a list of n strings (if input text is a single string) or a list of lists, each of length n. """ n = n or self.n rows = [row['generated_text'] for row in self.pipe(text, num_return_sequences=n, **kwargs)] if listlike(text): rows = [rows[i*n:(i+1)*n] for i in range(len(text))] return rows ``` ## Test on data ``` lines = [line.strip() for line in '\n'.join(load(f'/Users/hmamin/data/bbc/tech/{n:03}.txt') for n in range(1, 402)).split('.') if line] len(lines) m_res = m_tfm(lines[:100], errors='warn') len(flatten(m_res)) m_res[:2] g_res = g_tfm(lines[:100]) len(flatten(g_res)) lines[:2] g_res[:2] p_res = p_tfm(lines[:25]) len(flatten(p_res)) lines[:5] p_res[:5] ``` Note: with GPU, paraphrase transform takes ~9 seconds to generate variations of 100 input sentences. (Different inputs than used here but I don't think the length differs dramatically.) ## RandomPipeline Considering the idea of making a pipeline that accepts multiple callables and applies each one in order with a different (or same) probability P. We could construct this with RandomTransform manually but it seems like if everything or most things are random transforms, we might as well obscure this from the user. Trying to brainstorm what desired interface might look like. ``` pipeline = RandomPipeline(fill_mask, paraphrase, back_translate, p=.5) pipeline = RandomPipeline(fill_mask, paraphrase, back_translate, p=[.5, 1., .5]) pipeline = RandomPipeline.from_dict( {fill_mask: .5, paraphrase: 1., back_translate: .25} ) ``` Leaning towards no inverse_transform, or at least making it optional. Some transforms, like ParaphraseTransform, aren't really meant to be reversible. I suppose I could keep a mapping between original and transformed items but that might become infeasible as we process more data. Could also use pipeline.transform(text) ```augmented = pipeline(text) text = pipeline.inverse_transform(text) ``` ``` from numbers import Real from incendio.data import RandomTransform def tolist(x, length_like=None, length=None, error_message='x length does not match desired length.'): """Helper to let a function accept a single value or a list of values for a certain parameter. WARNING: if x is a primitive and you specify a length (either via `length_like` or `length`, the resulting list will contain multiple references to the same item). This is mostly intended for use on lists of floats or ints so I don't think it's a problem, but keep this in mind when considering using this on mutable objects. Parameters ---------- x: Iterable Usually an object that could either be a list/tuple or a primitive, depending on what user passed in. strict: bool If True, returned value will always be a list. If False, we allow tuples/sets/etc. to retain their initial type. Returns ------- Iterable: list if strict is True or if x is a primitive. If strict is False and x is already a tuple/set/something similar, its type will be retained. Examples -------- def train(lrs): lrs = tolist(lrs) ... >>> train(3e-3) >>> train([3e-4, 3e-3]) """ if length_like is not None: length = len(length_like) # Case 1. List-like x if listlike(x): if length: assert len(x) == length, error_message return list(x) # Case 2. Dict-like x if isinstance(x, Mapping): raise ValueError('x must not be a mapping. It should probably be a ' 'primitive (str, int, etc.) or a list-like object ' '(tuple, list, set).') # Case 3. Primitive x return [x] * (length or 1) p = .5 t = [1, 2, 3] # p = p if listlike(p) and len(p) == len(t) else [p] * len(t) p tolist(.5) tolist(.5, length=2) tolist(.5, length_like=t) tolist({3, 4, -1}) with assert_raises(AssertionError): tolist({3, 4}, length_like=t) tolist({3, 4, -1}, length_like=t) with assert_raises(ValueError): tolist({3: 1}) class RandomPipeline(BasicPipeline): """Create a pipeline of callables that are applied in sequence, each with some random probability p (this can be the same or different for each step). This is useful for on-the-fly data augmentation (think in the __getitem__ method of a torch Dataset). """ def __init__(self, *transforms, p=.5): """ Parameters ---------- transforms: callable Functions or callable classes that accept a single argument (use functools.partial if necessary). They will be applied in the order you pass them in. p: float or Iterable[float] Probability that each transform will be applied. If a single float, each transform will have the same probability. If a list, its length msut match the number of transforms passed in: p[0] will be assigned to transforms[0], p[1] to transforms[1], and so on. """ p = tolist(p, transforms, error_message='p must be a float or a list ' 'with one float for each transform.') if any(n <= 0 or n > 1 for n in p): raise ValueError('p must be in range (0, 1]. I.E. you can choose ' 'to always apply a transform, but if you never ' 'want to apply it there\'s no need to include ' 'it in the pipeline.') super().__init__(*[RandomTransform(t, p_) for t, p_ in zip(transforms, p)]) @classmethod def from_dict(cls, t2p): """ Parameters ---------- t2p: dict[callable, float] Maps transform to its corresponding probability. Examples -------- transforms = {times_3: .33, to_string: 1.0, dashed_join: .67, to_upper: .95} pipeline = RandomPipeline.from_dict(transforms) """ return cls(*t2p.keys(), p=t2p.values()) def to_upper(t): return t.upper() def times_3(t): return t * 3 def join(t, sep='---'): return sep.join(t) t = 'dog' rp = RandomPipeline(to_upper, times_3, join) rp for i in range(10): print(rp(t)) for i in range(10): print(rp(t)) t = 'dog' rp = RandomPipeline(to_upper, times_3, join, p=[1., .6, 1]) rp for i in range(10): print(rp(t)) t = 'dog' with assert_raises(ValueError): rp = RandomPipeline(join, p=0) rp with assert_raises(AssertionError): rp = RandomPipeline(to_upper, times_3, join, p=[.2, 1]) rp t = 'dog' tfms = {times_3: .33, join: .67, to_upper: .95} rp = RandomPipeline.from_dict(tfms) rp rp.funcs for i in range(10): print(rp(t)) class BacktranslateTransform: names = ['Helsinki-NLP/opus-mt-en-ROMANCE', 'Helsinki-NLP/opus-mt-ROMANCE-en'] language_codes = { 'es': 'spanish', 'it': 'italian', 'pt': 'portuguese', 'pt_br': 'portuguese (brazil)', 'ro': 'romanian', 'ca': 'catalan', 'gl': 'galician', 'pt_BR': 'portuguese (brazil?)', 'la': 'latin', 'wa': 'walloon', 'fur': 'friulian (?)', 'oc': 'occitan', 'fr_CA': 'french (canada)', 'sc': 'sardianian', 'es_ES': 'spanish', 'es_MX': 'spanish (mexico)', 'es_AR': 'spanish (argentina)', 'es_PR': 'spanish (puerto rico)', 'es_UY': 'spanish (uruguay)', 'es_CL': 'spanish (chile)', 'es_CO': 'spanish (colombia)', 'es_CR': 'spanish (croatia)', 'es_GT': 'spanish (guatemala)', 'es_HN': 'spanish (honduras)', 'es_NI': 'spanish (nicaragua)', 'es_PA': 'spanish (panama)', 'es_PE': 'spanish (peru)', 'es_VE': 'spanish (venezuela)', 'es_DO': 'spanish (dominican republic)', 'es_EC': 'spanish (ecuador)', 'es_SV': 'spanish (el salvador)', 'an': 'aragonese', 'pt_PT': 'portuguese (portugal)', 'frp': 'franco provencal', 'lad': 'ladino', 'vec': 'venetian', 'fr_FR': 'france (france)', 'co': 'corsican', 'it_IT': 'italian (italy)', 'lld': 'ladin', 'lij': 'ligurian', 'lmo': 'lombard', 'nap': 'neapolitan', 'rm': 'rhaetian (?)', 'scn': 'sicilian', 'mwl': 'mirandese' } def __init__(self, to_langs, pipes=()): if not pipes: pipes = [ TranslationPipeline( model=AutoModelForSeq2SeqLM.from_pretrained(name), tokenizer=AutoTokenizer.from_pretrained(name), device=1 - torch.cuda.is_available() ) for name in names ] self.pipes = pipes self.to_langs = tolist(to_langs) # def __call__(self, text, to_langs=()): # text = tolist(text) # to_langs = tolist(to_langs) or self.to_langs # for lang in to_langs: # text = [f'>>{lang}<< {t}' for t in text] # text = [row['translation_text'] for row in self.pipes[0](text)] # text = [row['translation_text'] for row in self.pipes[1](text)] # return text def __call__(self, text, to_langs=()): text = tolist(text) to_langs = tolist(to_langs) or self.to_langs steps = [] for lang in to_langs: text = [f'>>{lang}<< {t}' for t in text] text = [row['translation_text'] for row in self.pipes[0](text)] text = [row['translation_text'] for row in self.pipes[1](text)] steps.append(text) return steps def __repr__(self): lang_str = ", ".join(repr(lang) for lang in self.to_langs) return f'{func_name(self)}(to_langs=[{lang_str}])' ```
github_jupyter
# Getting colors for plotting and evaluating clustering ``` # Baked-in within python modules from collections import defaultdict # Alphabetical order for nonstandard python modules is conventional # We're doing "import superlongname as abbrev" for our laziness - this way we don't have to type out the whole thing each time. # Python plotting library import matplotlib as mpl import matplotlib.pyplot as plt # Numerical python library (pronounced "num-pie") import numpy as np # Dataframes in Python import pandas as pd # T-test of independent samples from scipy.stats import ttest_ind # Statistical plotting library we'll use import seaborn as sns sns.set(style='whitegrid') # Matrix decomposition from sklearn.decomposition import PCA, FastICA # Manifold learning from sklearn.manifold import MDS, TSNE # Clustering from sklearn.cluster import KMeans, MiniBatchKMeans # Plotting dendrograms from scipy.cluster import hierarchy # This is necessary to show the plotted figures inside the notebook -- "inline" with the notebook cells %matplotlib inline macaulay2016_expression = pd.read_csv('../data/macaulay2016/gene_expression_s.csv', index_col=0) # Set maximum columns to display as 50 because the dataframe has 49 columns pd.options.display.max_columns = 50 macaulay2016_metadata = pd.read_csv('../data/macaulay2016/sample_info_qc.csv', index_col=0) # Add column for gfp macaulay2016_metadata['gfp_color'] = ['#31a354' if c == 'HIGH' else '#e5f5e0' for c in macaulay2016_metadata['condition']] # Necessary step for converting the parsed cluster color to be usable with matplotlib macaulay2016_metadata['cluster_color'] = macaulay2016_metadata['cluster_color'].map(eval) # --- Filter macaulay2016 data --- # ensembl_genes = [x for x in macaulay2016_expression.index if x.startswith('ENS')] cells_pass_qc = macaulay2016_metadata["Pass QC"].index[macaulay2016_metadata["Pass QC"]] macaulay2016_expression_filtered = macaulay2016_expression.loc[ensembl_genes, cells_pass_qc] # Recalculate TPM macaulay2016_expression_filtered = 1e6 * macaulay2016_expression_filtered / macaulay2016_expression_filtered.sum() # Transpose so it's machine learning format macaulay2016_expression_filtered = macaulay2016_expression_filtered.T # Take only "expressed genes" with expression greater than 1 in at least 3 cells mask = (macaulay2016_expression_filtered > 1).sum() >= 3 macaulay2016_expression_filtered = macaulay2016_expression_filtered.loc[:, mask] print('macaulay2016_expression_filtered.shape', macaulay2016_expression_filtered.shape) # Add 1 and log10 macaulay2016_expression_log10 = np.log10(macaulay2016_expression_filtered + 1) # Macaulay2016 plotting colors macaulay2016_gfp_colors = macaulay2016_metadata.loc[macaulay2016_expression_log10.index, 'gfp_color'] # Get cluster colors from the paper macaulay2016_cluster_colors_from_paper = macaulay2016_metadata.loc[macaulay2016_expression_log10.index, 'cluster_color'] macaulay2016_clusters_from_paper = macaulay2016_metadata.loc[macaulay2016_expression_log10.index, 'cluster'] macaulay2016_cluster_to_color_from_paper = dict(zip(macaulay2016_clusters_from_paper, macaulay2016_cluster_colors_from_paper)) ``` ## Clarification of hierarchical clustering goals Use hierarchical clustering on either PCA or ICA to assign clusters to the Macaulay data and plot the PCA (or ICA) plot with the reduced clusters. **Are you able to recover the original clusters?** Use as many code cells as you need. To clarify, the full steps for evaluating your hierarchical clustering on the Macaulay2016 dataset are: 1. Perform dimensionality reduction 2. Cluster the reduced data 3. Cut the dendrogram from the clustered data 4. Get the cluster colors and assignments 5. Re-plot the data with the sample colors 6. See how your clusters match with the Macaulay dataset ## How to get any number of colors for your data ``` kmeans = KMeans(n_clusters=6) kmeans.fit(macaulay2016_expression_log10) macaulay2016_smusher = PCA(n_components=2) macaulay2016_smushed = pd.DataFrame( macaulay2016_smusher.fit_transform(macaulay2016_expression_log10), index=macaulay2016_expression_log10.index) macaulay2016_kmeans_centroids = pd.DataFrame(macaulay2016_smusher.transform( kmeans.cluster_centers_)) macaulay2016_kmeans_centroids fig, ax = plt.subplots() ax.scatter(macaulay2016_smushed[0], macaulay2016_smushed[1], color="Teal", linewidth=1, edgecolor='white') ax.scatter(macaulay2016_kmeans_centroids[0], macaulay2016_kmeans_centroids[1], color='k', marker='x', s=100, linewidth=3) kmeans.predict(macaulay2016_expression_log10) sns.choose_colorbrewer_palette('qualitative') husl_palette = sns.color_palette('husl', n_colors=20) sns.palplot(husl_palette) kmeans_palette = sns.color_palette('Set1', n_colors=6) sns.palplot(kmeans_palette) labels = pd.Series(kmeans.predict(macaulay2016_expression_log10), index=macaulay2016_expression_log10.index) colors = [kmeans_palette[i] for i in labels] print(len(labels)) print(len(colors)) fig, ax = plt.subplots() ax.scatter(macaulay2016_smushed[0], macaulay2016_smushed[1], color=colors, linewidth=1, edgecolor='grey') ax.scatter(macaulay2016_kmeans_centroids[0], macaulay2016_kmeans_centroids[1], color='k', marker='x', s=100, linewidth=3) ``` ### Exercise 1 Change the number of clusters to 20 and use the `"husl"` palette for coloring ## Evaluating clustering How do we evaluate the clusters that we found versus the clusters from the paper? ``` # Get the unique names of the original Macaulay2016 clusters cluster_names = macaulay2016_metadata.cluster.unique() # Sort them in alphabetical order so that they're in the order we want cluster_names.sort() # Map the cluster name to an integer number cluster_name_to_integer = dict(zip(cluster_names, range(len(cluster_names)))) paper_cluster_integers = macaulay2016_metadata.cluster.map(cluster_name_to_integer) paper_cluster_integers.head() macaulay2016_palette = [macaulay2016_cluster_to_color_from_paper[x] for x in cluster_names] from sklearn.metrics import confusion_matrix confusion = pd.DataFrame(confusion_matrix(paper_cluster_integers, labels), index=cluster_names) confusion.index.name = 'Macaulay2016 Labels' confusion.columns.name = 'K-Means Predicted' confusiongrid = sns.clustermap(confusion, annot=True, fmt='d', figsize=(4, 4), col_cluster=False, row_cluster=False, row_colors=macaulay2016_palette, col_colors=kmeans_palette) # rotate the ylabels to be horizontal instead of vertical plt.setp(confusiongrid.ax_heatmap.get_yticklabels(), rotation=0); ``` ### Evaluating clustering: Rand score The [Rand index](https://en.wikipedia.org/wiki/Rand_index) is a numeric value indicating ``` from sklearn.metrics.cluster import adjusted_rand_score adjusted_rand_score([0, 0, 1, 1], [0, 0, 1, 1]) adjusted_rand_score([0, 0, 1, 1], [1, 1, 0, 0]) ``` ### Exercise 2 Try your own labels and values to see the rand score. You can try as many samples or classes as you want ``` # adjusted_rand_score([XXXX], [XXXX]) ``` ### Exercise 3 Get the Rand score of your clustering ``` # YOUR CODE HERE ```
github_jupyter
# Analyze Watson Assistant Effectiveness <img src="https://raw.githubusercontent.com/watson-developer-cloud/assistant-improve-recommendations-notebook/master/notebook/imgs/analyze_process.png" alt="Analyze Process" width="600"/> ### Introduction As described in <a href="https://github.com/watson-developer-cloud/assistant-improve-recommendations-notebook/raw/master/notebook/IBM%20Watson%20Assistant%20Continuous%20Improvement%20Best%20Practices.pdf" target="_blank" rel="noopener noreferrer">Watson Assistant Continuous Improvement Best Practices</a>, this notebook will help you understand relative performance of each intent and entity, the confusion between your intents, as well as the root cause of utterance issues. This information helps you prioritize your improvement effort. The pre-requisite for running this notebook is a collection of annotated utterances. This notebook assumes familiarity with Watson Assistant and concepts such as skills, workspaces, intents and training examples. ### Programming language and environment Some familiarity with Python is recommended. This notebook runs on Python 3.5+ environment. ## Table of contents 1. [Configuration and setup](#setup)<br> 1.1 [Apply global CSS styles](#setup1)<br> 1.2 [Install Assistant Improve Toolkit](#setup2)<br> 1.3 [Import functions used in the notebook](#setup3)<br> 1.4 [Specify annotation file](#setup4)<br> 2. [Load and format data](#load)<br> 3. [Generate summary metrics](#summ_metrics)<br> 3.1 [Generate confusion matrix](#summ_metrics1)<br> 3.2 [Calculate True Positive (TP), False Positive (FP), False Negative (FN), and True Negative (TN)](#summ_metrics2)<br> 3.3 [Calculate the total number of utterances, as well as the numbers of correct and wrong utterances](#summ_metrics3)<br> 3.4 [Calculate average helpfulness and its variance over different intents](#summ_metrics4)<br> 3.5 [Calculate average precision and variance](#summ_metrics5)<br> 3.6 [Display the summarized results](#summ_metrics6)<br> 3.7 [Summarize the root cause](#summ_metrics7)<br> 4. [Perform intent analysis](#intent_analysis)<br> 4.1 [Determine worst overall performing intents](#intent_analysis1)<br> 4.2 [Determine the worst precision intents](#intent_analysis2)<br> 4.3 [Determine the worst recall intents](#intent_analysis3)<br> 4.4 [Determine confused intent pairs](#intent_analysis4)<br> 5. [Perform entity analysis](#entity_analysis)<br> 6. [Perform dialog analysis](#dialog_analysis)<br> 7. [Summary and recommendation](#summary)<br> ## <a id="setup"></a> 1. Configuration and setup In this section, we import required libraries and functions and add data access credentials. ### <a id="setup1"></a> 1.1 Import and apply global CSS styles ``` from IPython.display import display, HTML !curl -O https://raw.githubusercontent.com/watson-developer-cloud/assistant-improve-recommendations-notebook/master/src/main/css/custom.css HTML(open('custom.css', 'r').read()) ``` ### <a id="setup2"></a> 1.2 Install Assistant Improve Toolkit ``` !pip3 install --user --upgrade "assistant-improve-toolkit"; ``` ### <a id="setup3"></a> 1.3 Import functions used in the notebook ``` import pandas as pd from sklearn.metrics import confusion_matrix import numpy as np from collections import OrderedDict from IPython.display import Markdown as md import re import ast from assistant_improve_toolkit.cos_op import generate_link, generate_excel_effectiveness from assistant_improve_toolkit.computation_func import round_decimal from assistant_improve_toolkit.visualize_func import table_styles, make_bar ``` ### <a id="setup4"></a> 1.4 Specify annotation file In order to run the effectiveness analysis, you will need to specify the path of your annotated file. ``` # For using demo annotation data import requests print('Loading annotated data from Watson developer cloud GitHub repo ... ', end='') annotated_data = requests.get("https://raw.githubusercontent.com/watson-developer-cloud/assistant-improve-recommendations-notebook/master/notebook/data/annotation.xlsx").content with open('annotation.xlsx', 'wb') as out: out.write(annotated_data) print('completed!') annotation_file = 'annotation.xlsx' # Comment out to use your annotation file # annotation_file = '' ``` ## <a id="load"></a> 2. Load and format data Here, we load the annotated problematic logs for analysis. Remember add your sheet name into `sheet_name=''`. ``` column_list = [ 'log_id', 'conversation_id', 'timestamp', 'customer_id', 'utterance_text', 'response_text', 'top_intent', 'top_confidence', 'intent_2', 'intent_2_confidence', 'confidence_gap', 'intent_3', 'intent_3_confidence', 'entities', 'is_escalated', 'is_convered', 'not_convered_cause', 'dialog_flow', 'dialog_stack', 'dialog_request_counter', 'dialog_turn_counter', 'correctness', 'helpfulness', 'root_cause', 'correct_intent', 'new_intent', 'add_train', 'missed_entity', 'new_entity', 'new_entity_value', 'new_dialog_logic', 'wrong_dialog_node', 'no_dialog_node_triggered' ] annotated_data = pd.read_excel(annotation_file, sheet_name='data', names=column_list) ``` ## 3. Generate summary metrics<a id="summ_metrics"></a> Here, we generate the confusion matrix, calculate TP, FP, FN and TN, the total number of utterances, average helpfulness, precision and variance, summarize the possible root causes and display the results. ### <a id="summ_metrics1"></a> 3.1 Generate confusion matrix A confusion matrix is a table that is often used to describe the performance of a classification model. ``` # Get intent list print('Found {} entries in the annotation file'.format(len(annotated_data))) annotated_data['top_intent'] = annotated_data['top_intent'].replace(r'^\s+$', np.nan, regex=True) print('Dropped {} empty or invalid entries in top detected intents'.format(len(annotated_data[annotated_data['top_intent'].isnull()].index.values))) annotated_data = annotated_data[annotated_data['top_intent'].notnull()].reset_index(drop=True) annotated_data['correct_intent'] = annotated_data['correct_intent'].replace(r'^\s+$', np.nan, regex=True) intents = pd.unique(annotated_data[['top_intent', 'correct_intent']].values.ravel()) # Remove NaN intents=sorted(intents[~pd.isnull(intents)]) # add a ground truth column annotated_data['ground_truth'] = annotated_data['correct_intent'].fillna(annotated_data['top_intent']) # calculate number of count per intent based on top intent num_total_per_intent = pd.DataFrame(annotated_data.groupby('top_intent').size(), intents).fillna(0) # calculate number of count per intent based on ground truth num_total_per_intent_gt = pd.DataFrame(annotated_data.groupby('ground_truth').size(), intents).fillna(0) # Generate confusion matrix confusion_matrix = confusion_matrix(annotated_data['ground_truth'], annotated_data['top_intent'], labels=intents) ``` <a id="summ_metrics2"></a> ### 3.2 Calculate True Positive (TP), False Positive (FP), False Negative (FN), and True Negative (TN) - __True Positives__ of an intent describe cases where the intent classifier correctly classifies utterances as this intent. - __False Positives__ of an intent describe cases where the intent classifier incorrectly classifies utterances as this intent. - __False Negatives__ of an intent describe cases where the intent classifier fails to identify utterances as this intent. - __True Negatives__ of an intent describe cases where the intent classifier correctly identifies that utterances don't belong to this intent. ``` # Calculate True Positive (TP) TP = np.diag(confusion_matrix) # Calculate False Positive (FP) FP = np.sum(confusion_matrix, axis=0) - TP # Calculate False Negative (FN) FN = np.sum(confusion_matrix, axis=1) - TP # Calculate True Negative (TN) TN = [] for i in range(len(intents)): row_del = np.delete(confusion_matrix, i, 0) col_del = np.delete(row_del, i, 1) TN.append(sum(sum(col_del))) ``` <a id="summ_metrics3"></a> ### 3.3 Calculate the total number of utterances, as well as the numbers of correct and wrong utterances ``` # Get total number of utterances total_num = np.sum(TP+FP) # Get total number of correctly classified utterances total_correct = np.sum(TP) # Get total number of incorrectly classified utterances total_wrong = np.sum(FP) ``` <a id="summ_metrics4"></a> ### 3.4 Calculate average helpfulness and its variance over different intents Helpfulness is a metric that identifies responses that may be considered technically correct, but the wording of the response is not satisfying to the user. It could be too long, too general, or just worded awkwardly, thus resulting in an overall ineffective response. <br> **Note:** The exact definition of helpfulness is subjective and can be defined based on your business goals. ``` # Get number of utterances that labeled as helpful per class num_helpfulness_per_intent = annotated_data.loc[annotated_data['helpfulness']== 'Y'].groupby('ground_truth').size() num_unhelpfulness_per_intent = annotated_data.loc[annotated_data['helpfulness']== 'N'].groupby('ground_truth').size() # Get number of utterances per class num_total_per_intent_helpfulness = num_helpfulness_per_intent.add(num_unhelpfulness_per_intent, fill_value=0) # Get total number of utterances that labeled as helpful num_helpfulness = sum(num_helpfulness_per_intent) num_unhelpfulness = sum(num_unhelpfulness_per_intent) # Calculate averaged helpfulness avg_help = np.average(num_helpfulness_per_intent.divide(num_total_per_intent_helpfulness, fill_value=0)) # Calculate helpfulness variance var_help = np.var(num_helpfulness_per_intent.divide(num_total_per_intent_helpfulness, fill_value=0)) # Calculate helpful utterance percentage per intents percentage_helpful_intent = num_helpfulness_per_intent.divide(num_total_per_intent_helpfulness, fill_value=0) # Collect invalid intent for helpfulness metric invalid_intent_helpfulness = list(set(intents) - set(num_total_per_intent_helpfulness.index.tolist())) ``` <a id="summ_metrics5"></a> ### 3.5 Calculate average precision and variance Precision is a metric measuring the performance of intent classifier. ``` # Calculate precision by intents TP_FP = TP+FP precision_list = pd.DataFrame({'True Positives': TP, 'True&False Positive': TP_FP, 'Intents': intents}) # Remove invalid intent invalid_intent_precision = precision_list[precision_list['True&False Positive']==0]['Intents'] precision_list = precision_list[precision_list['True&False Positive']>0] # Calculate precision per intent precision_list['Precision'] = precision_list['True Positives'] / precision_list['True&False Positive'] # Calculate averaged precision avg_prec = np.average(precision_list['Precision']) # Calculate precision variance var_prec = np.var(precision_list['Precision']) ``` <a id="summ_metrics6"></a> ### 3.6 Display the summarized results Here, we take a look at the summarized results - in text and bar chart form. #### 3.6.1 Print performance summary ``` # print Performance Summary print('===== Performance Summary =====\n') print('Number of intents: {}'.format(len(intents))) print('Number of Utterances: {}'.format(total_num)) print('\n\tTop 5 intents based on count of top detected intent:\n') for intent, value in num_total_per_intent.sort_values(by=0, ascending=False).head(5)[0].iteritems(): print('\t\t{:<30}\t{}'.format(intent, value)) print('\n\tBottom 5 intents based on count in top detected intent:\n') for intent, value in num_total_per_intent.sort_values(by=0, ascending=True).head(5)[0].iteritems(): print('\t\t{:<30}\t{}'.format(intent, value)) print('\n\tTop 5 intents based on count of ground truth intent:\n') for intent, value in num_total_per_intent_gt.sort_values(by=0, ascending=False).head(5)[0].iteritems(): print('\t\t{:<30}\t{}'.format(intent, value)) print('\n\tBottom 5 intents based on count of ground truth intent:\n') for intent, value in num_total_per_intent_gt.sort_values(by=0, ascending=True).head(5)[0].iteritems(): print('\t\t{:<30}\t{}'.format(intent, value)) print('\nCorrect Classified Utterances: {}'.format(total_correct)) print('Incorrectly Classified Utterances: {}\n'.format(total_wrong)) print('- Helpfulness\n') print('\tHelpful Utterances: {}'.format(num_helpfulness)) print('\tUnhelpful Utterances: {}'.format(num_unhelpfulness)) print('\tAverage Helpfulness Percentage: {}'.format(round_decimal(avg_help,3))) print('\tHelpfulness Variance: {}\n'.format(round_decimal(var_help,3))) print('\tTop 5 best performed intents:\n') for intent, value in percentage_helpful_intent.sort_values(ascending=False).head(5).iteritems(): print('\t\t{:<30}\t{:4.3f}'.format(intent, round_decimal(value,3))) print('\n\tTop 5 worst performed intents:\n') for intent, value in percentage_helpful_intent.sort_values(ascending=True).head(5).iteritems(): print('\t\t{:<30}\t{:4.3f}'.format(intent, round_decimal(value,3))) print('\n- Precision\n') print('\tTrue Positive: {}'.format(sum(TP))) print('\tFalse Positive: {}'.format(sum(FP))) print('\tFalse Negative: {}'.format(sum(FP))) print('\tAverage Precision: {}'.format(round_decimal(avg_prec,3))) print('\tPrecision Variance: {}\n'.format(round_decimal(var_prec,3))) print('\tTop 5 best performed intents:\n') for row in precision_list.sort_values(by=['Precision'], ascending=False).head(5).iterrows(): print('\t\t{:<30}\t{:4.3f}'.format(row[1]['Intents'], round_decimal(row[1]['Precision'],3))) print('\n\tTop 5 worst performed intents:\n') for row in precision_list.sort_values(by=['Precision'], ascending=True).head(5).iterrows(): print('\t\t{:<30}\t{:4.3f}'.format(row[1]['Intents'], round_decimal(row[1]['Precision'],3))) if len(invalid_intent_helpfulness) > 0: print('\n*Note*: the following intents are ignored when calculating Helpfulness due to missing values\n') for intent in invalid_intent_helpfulness: print('\t{}'.format(intent)) if len(invalid_intent_precision) > 0: print('\n*Note*: the following intents are ignored when calculating Precision due to the sum of True and False Positive is zero\n') for intent in invalid_intent_precision: print('\t{}'.format(intent)) ``` #### 3.6.2 Bar graph to visualize precision and helpfulness percentage The red lines on the bars indicate value variances. Note that if your variance is very small, the line may appear as a dot at the top of the bar. Here a smaller variance is preferred which indicates that the performance of your intent classifer is more stable across different intents. ``` make_bar(avg_prec*100, avg_help*100, var_prec*100, var_help*100) ``` <a id="summ_metrics7"></a> ### 3.7 Summarize the root cause Root causes describe issues caused by an incorrect or absent intent, entity, or dialog response. #### 3.7.1 Display root causes summary ``` # Group by root causes and display count root_cause = annotated_data['root_cause'].replace(r'^\s+$', np.nan, regex=True).dropna().value_counts().rename_axis('Root Causes').reset_index(name='Utterances') # Apply style on dataframe root_cause.style.set_table_styles(table_styles).set_properties(**{'text-align': 'center'}).set_properties( subset=['Root Causes'], **{'width': '700px', 'text-align': 'left'}).format( {'Utterances': lambda x: "{:.0f}".format(x)}) ``` #### 3.7.2 Save the results into a dataframe ``` # Create a dataframe to enclose the statistics computed so far df = pd.DataFrame(OrderedDict( ( ('Intents', intents), ('True Positives', TP), ('False Positives', FP), ('True Negatives', TN), ('False Negatives', FN), ('Total Utterances (top intent)', num_total_per_intent[0]),('Total Utterances (ground truth)', num_total_per_intent_gt[0]), ('Total Errors', FP + FN)))) ``` ## 4. Perform intent analysis<a id="intent_analysis"></a> Intent analysis is performed by looking for the dominant patterns of intent errors. An effective way to perform this analysis is to focus on four main categories of errors: - **Worst overall performing intents:** these are intents that are most involved in a wrong answer, whether due to precision or recall.<p> - **Worst recall intents:** this identifies intents that are being missed most often. This intent should have been given out, but other intent(s) are matching instead. These intents likely need more training examples. <p> - **Worst precision intents:** this identifies intents that are frequently matching when they should not be, thus hiding the correct intent(s). These intents likely have training examples that clash with training of other intents. <p> - **Most confused intent pairs:** these are pairs of intents that are often confused with each other. These intents likely have training examples that overlap. ### <a id="intent_analysis1"></a> 4.1 Determine worst overall performing intents These are intents that are most involved in a wrong answer, whether due to precision or recall. Here are the metrics we recommend measuring: - __False Positives__ of an intent describe cases where the intent classifier incorrectly classifies utterance as this intent. - __False Negatives:__ of an intent describe cases where the intent classifier fails to classify an utterance as this intent. ``` output_file_path = 'WorstOverallIntents.csv' display(md('<p>')) display(md('<div style="max-width: 1300px;"><div style="float: left;">View the whole list here: <b><a href="{}" style="color:black" target="_blank">WorstOverallIntents.csv</a></b></div><div style="float: right"> 25 Worst Intents </div></div>'.format(output_file_path))) # Sort dataframe by number of errors and add related columns worst_overall = df.sort_values('Total Errors', ascending=False)[['Intents','Total Utterances (top intent)','Total Utterances (ground truth)','Total Errors', 'False Positives', 'False Negatives' ]].reset_index(drop=True) # Save the output CSV file worst_overall.to_csv(output_file_path, sep=',', encoding='utf-8') # Apply style on dataframe table worst_overall.head(15).style.set_table_styles(table_styles).set_properties(**{'text-align': 'center'}).set_properties( subset=['Total Utterances (top intent)'], **{'width': '140px'}).set_properties( subset=['Total Utterances (ground truth)'], **{'width': '160px'}).set_properties( subset=['Total Errors'], **{'width': '100px'}).set_properties(subset=['Intents'], **{'width': '450px', 'text-align': 'left'}) ``` ### <a id="intent_analysis2"></a> 4.2 Determine the worst precision intents This identifies intents that are frequently matching when they should not be, thus hiding the correct intent(s). These intents likely have training examples that clash with training of other intents. Here are the metrics we recommend measuring: - __True Positives__ of an intent describe cases where the intent classifier correctly classifies utterance as this intent. - __False Positives__ of an intent describe cases where the intent classifier incorrectly classifies utterance as this intent. ``` output_file_path = 'WorstPrecisionIntents.csv' # Calculate precision by intents TP_FP = TP+FP percentile_list = pd.DataFrame({'True Positives': TP,'False Positives': FP, 'True&False Positive': TP_FP, 'Intents': intents}) # Remove invalid intent invalid_intent_precision = percentile_list[percentile_list['True&False Positive']==0]['Intents'] percentile_list = percentile_list[percentile_list['True&False Positive']>0] # Calculate precision per intent percentile_list['Precision'] = percentile_list['True Positives'].divide(percentile_list['True&False Positive']).values percentile_list = percentile_list.join(df[['Total Utterances (top intent)', 'Total Utterances (ground truth)']], on='Intents') display(md('<p>')) display(md('<div style="max-width: 1500px;"><div style="float: left">View the whole list here: <b><a href="{}" style="color:black" target="_blank">WorstPrecisionIntents.csv</a></b></div><div style="float: right"> 25 Worst Intents </div> </div>'.format(output_file_path))) # Sort dataframe by precision and add related columns worst_prec = percentile_list.sort_values(['Precision', 'False Positives'], ascending=[True, False])[['Intents','Total Utterances (top intent)', 'Total Utterances (ground truth)', 'True Positives', 'False Positives', 'Precision']].reset_index(drop=True) # Save the output CSV file worst_prec.to_csv(output_file_path, sep=',', encoding='utf-8') # Apply style on dataframe table table = worst_prec.head(25).style.set_table_styles(table_styles).set_properties(**{'text-align': 'center'}).set_properties( subset=['Total Utterances (top intent)'], **{'width': '140px'}).set_properties( subset=['Total Utterances (ground truth)'], **{'width': '180px'}).set_properties( subset=['Intents'], **{'width': '400px', 'text-align': 'left'}).format( {"Precision": lambda x: "{:.0f}%".format(x*100)}).set_properties( subset=['Precision'], **{'width': '350px', 'text-align': 'center'}).render() # Apply CSS style style = '.meter { height: 6px; width: 50%; position: relative; background: #fff; border-radius: 20px; border-color: rgb(0, 76, 192); border-style: solid; border-width: 1px; float: left; margin-top: 8px; margin-left: 50px;margin-right: 15px; } .meter>span { display: block; height: 100%; background-color: rgb(0, 76, 192); position: relative; overflow: hidden; } ' table = table[:table.find('>') + 1] + style + table[table.find('>') + 1:] # Insert percentage bar pattern = r'(data row)(.*?)( col5" >)(.*?)(%)(</td>)' bar_code = r'<div class="meter" style="float: left;margin-left: 30px;"> <span style="width: \4%"></span> </div><div style="float: left;margin-left: 0px;">' regex = re.compile(pattern, re.IGNORECASE) table = re.sub(pattern, r'\1\2\3'+bar_code+r'\4\5</div>\6', table) if len(invalid_intent_precision) > 0: invalid_note = '<br><b>Note<b>: the following intents are ignored when calculating Precision due to the sum of True Positive and False Positive is zero<p>' for intent in invalid_intent_precision: invalid_note += '&emsp;{}<br>'.format(intent) table += invalid_note # Show table HTML(table) ``` ### <a id="intent_analysis3"></a> 4.3 Determine the worst recall intents This identifies intents that are being missed most often. This intent should have been given out, but other intent(s) are matching instead. These intents likely need more training examples. - __True Positives__ of an intent describe cases where the intent classifier correctly classifies utterance as this intent. - __False Negative__ of an intent describe cases where the intent classifier fails to classify utterance as this intent. ``` output_file_path = 'WorstRecallIntents.csv' # Calculate recall by intents TP_FN = TP+FN percentile_recall_list = pd.DataFrame({'True Positives': TP,'False Negatives': FN, 'Intents': intents, 'True Positive&False Negative': TP_FN}) # Remove invalid intent invalid_intent_recall = percentile_recall_list[percentile_recall_list['True Positive&False Negative']==0]['Intents'] percentile_recall_list = percentile_recall_list[percentile_recall_list['True Positive&False Negative']>0] # Calculate precision per intent percentile_recall_list['Recall'] = percentile_recall_list['True Positives'].divide(percentile_recall_list['True Positive&False Negative']).values percentile_recall_list = percentile_recall_list.join(df[['Total Utterances (top intent)', 'Total Utterances (ground truth)']], on='Intents') display(md('<p>')) display(md('<div style="max-width: 1500px;"><div style="float: left">View the whole list here: <b><a href="{}" style="color:black" target="_blank">WorstRecallIntents.csv</a></b></div><div style="float: right"> 25 Worst Intents </div></div>'.format(output_file_path))) # Sort dataframe by recall and add related columns worst_recall = percentile_recall_list.sort_values(['Recall', 'False Negatives'], ascending=[True, False])[['Intents','Total Utterances (top intent)','Total Utterances (ground truth)', 'True Positives', 'False Negatives', 'Recall']].reset_index(drop=True) # Save the output CSV file worst_recall.to_csv(output_file_path, sep=',', encoding='utf-8') # Apply style on dataframe table table = worst_recall.head(25).style.set_table_styles(table_styles).set_properties(**{'text-align': 'center'}).set_properties( subset=['Total Utterances (top intent)'], **{'width': '140px'}).set_properties( subset=['Total Utterances (ground truth)'], **{'width': '180px'}).set_properties( subset=['Intents'], **{'width': '400px', 'text-align': 'left'}).format( {"Recall": lambda x: "{:.0f}%".format(x*100)}).set_properties( subset=['Recall'], **{'width': '350px', 'text-align': 'center'}).render() # Apply CSS style style = '.meter { height: 6px; width: 50%; position: relative; background: #fff; border-radius: 20px; border-color: rgb(0, 76, 192); border-style: solid; border-width: 1px; float: left; margin-top: 8px; margin-left: 50px;margin-right: 15px; } .meter>span { display: block; height: 100%; background-color: rgb(0, 76, 192); position: relative; overflow: hidden; } ' table = table[:table.find('>') + 1] + style + table[table.find('>') + 1:] # Insert percentage bar pattern = r'(data row)(.*?)( col5" >)(.*?)(%)(</td>)' bar_code = r'<div class="meter" style="float: left;margin-left: 30px;"> <span style="width: \4%"></span> </div><div style="float: left;margin-left: 0px;">' regex = re.compile(pattern, re.IGNORECASE) table = re.sub(pattern, r'\1\2\3'+bar_code+r'\4\5</div>\6', table) if len(invalid_intent_recall) > 0: invalid_note = '<br><b>Note</b>: the following intents are ignored when calculating Recall due to the sum of True Positive and False Negative is zero<p>' for intent in invalid_intent_recall: invalid_note += '&emsp;{}<br>'.format(intent) table += invalid_note # Show table HTML(table) ``` ### <a id="intent_analysis4"></a> 4.4 Determine confused intent pairs Most confused intent pairs: these are pairs of intents that are often confused with each other. Here is a description of the columns we focus on: - __Intent 1, Intent 2:__ The pair of confused intents. - __Incorrectly in Intent 1:__ Number of utterances where intent 1 was identified instead of intent 2. - __Incorrectly in Intent 2:__ Number of utterances where intent 2 was identified instead of intent 1. ``` output_file_path = 'ConfusedIntentPairs.csv' display(md('<p>')) display(md('<div style="max-width: 1200px;"><div style="float: left">View the whole list here: <b><a href="{}" style="color:black" target="_blank">ConfusedIntentPairs.csv</a></b></div><div style="float: right"> 25 Worst Intents </div></div>'.format(output_file_path))) # Calculate confused intents # Merge two copies of the dataframe on ground truth and intent copy1 = annotated_data.loc[annotated_data['top_intent']!=annotated_data['ground_truth'], ['ground_truth','top_intent']].groupby(['ground_truth','top_intent']).size().reset_index(name="Count").sort_values(by='Count', ascending = False) copy2 = annotated_data.loc[annotated_data['top_intent']!=annotated_data['ground_truth'], ['ground_truth','top_intent']].groupby(['ground_truth','top_intent']).size().reset_index(name="Count").sort_values(by='Count', ascending = False) result = pd.merge(copy1, copy2, left_on='ground_truth', right_on = 'top_intent') if len(result) == 0: confused_intents = copy1.rename(columns={'ground_truth':'Intent 1', 'top_intent':'Intent 2', 'Count':'Incorrectly in Intent 2'}) confused_intents['Incorrectly in Intent 1']=0 else: # Filter and rename columns confused_intents = result.loc[(result['ground_truth_x']==result['top_intent_y']) & (result['top_intent_x']==result['ground_truth_y'])].rename(columns={'ground_truth_x':'Intent 1', 'top_intent_x':'Intent 2', 'Count_x':'Incorrectly in Intent 2','Count_y':'Incorrectly in Intent 1'}).drop(['ground_truth_y','top_intent_y'], axis=1) # Sort results helper = pd.DataFrame(np.sort(confused_intents[['Intent 1', 'Intent 2']], axis=1), confused_intents[['Intent 1', 'Intent 2']].index, confused_intents[['Intent 1', 'Intent 2']].columns) # Remove duplicates helper.drop_duplicates(inplace = True) # Perform an inner join to get most confused intents most_confused_intents = pd.merge(helper, confused_intents, on=['Intent 1', 'Intent 2'], how = 'inner') # Calculate 'Total wrong' column most_confused_intents.insert(loc=0, column='Total Wrong', value=most_confused_intents['Incorrectly in Intent 1']+most_confused_intents['Incorrectly in Intent 2']) # Get confused intent pairs - sorted by 'Total wrong' column confused_intent_pairs = most_confused_intents[['Total Wrong','Intent 1', 'Intent 2', 'Incorrectly in Intent 1','Incorrectly in Intent 2']].sort_values(by = 'Total Wrong', ascending = False).reset_index(drop=True) # Save the output CSV file confused_intent_pairs.to_csv(output_file_path, sep=',', encoding='utf-8') # Apply style on dataframe table table = confused_intent_pairs.head(25).style.set_table_styles(table_styles).set_properties(**{'text-align': 'center'}).set_properties( subset=['Intent 1', 'Intent 2'], **{'width': '300px', 'text-align': 'left'}).format( {"Incorrectly in Intent 1": lambda x: "{:.0f}".format(x)}).set_properties( subset=['Incorrectly in Intent 1','Incorrectly in Intent 2'], **{'width': '250px', 'text-align': 'center'}).render() # Apply CSS style style = '.dot {float: left; margin-left: 90px;margin-top: 4px; height: 10px; width: 10px; background-color: #4eaaf7; border-radius: 50%; display: inline-block; } .dot_mid {float: left; margin-left: 85px;margin-top: 4px; height: 10px; width: 10px; background-color: #fff; border-radius: 50%; display: inline-block; border-style: solid; border-width: 3px; border-color: #c819e0; }' table = table[:table.find('>') + 1] + style + table[table.find('>') + 1:] # Insert blue dots pattern = r'(data row)(.*?)( col3" >)(.*?)(</td>)' dot = r'<span class="dot"></span><div style="float: middle;margin-right: 40px;">' regex = re.compile(pattern, re.IGNORECASE) table = re.sub(pattern, r'\1\2\3'+dot+r'\4\5</div>', table) # Insert pink dots pattern = r'(data row)(.*?)( col4" >)(.*?)(</td>)' dot = r'<span class="dot_mid"></span><div style="float: middle;margin-right: 40px;">' regex = re.compile(pattern, re.IGNORECASE) table = re.sub(pattern, r'\1\2\3'+dot+r'\4\5</div>', table) # Insert blue dot into header pattern = r'(col_heading level0 col1" >)(.*?)(</th>)' dot = r'</div><div style="float:left;margin-left: -70px;"><span class="dot"></span></div>' regex = re.compile(pattern, re.IGNORECASE) table = re.sub(pattern, r'\1<div style="float:left;margin-left: 80px;">\2'+dot+r'\3', table) # Insert pink dot into header pattern = r'(col_heading level0 col2" >)(.*?)(</th>)' dot = r'</div><div style="float:left;margin-left: -65px;"><span class="dot_mid"></span></div>' regex = re.compile(pattern, re.IGNORECASE) table = re.sub(pattern, r'\1<div style="float:left;margin-left: 80px;">\2'+dot+r'\3', table) # Show table HTML(table) ``` ## 5. Perform entity analysis<a id="entity_analysis"></a> Entity analysis highlights the entities and entity values that are particularly problematic, so they can be targeted for further investigation and improvement. ``` output_file_path = 'EntitiesMissed.csv' # Get missed entity data from annotated_data dataframe all_entities = annotated_data['missed_entity'].dropna().reset_index(drop = True) # Convert the value into dict object try: all_entities = all_entities.apply(lambda x: ast.literal_eval(x)) except: print("Malformed JSON annotation for entities, please check your annotation") for annotation in all_entities: print(annotation) raise # There are multiple entities in a single column. Separate them so that there is only a single entity in a column # Separate entities into different columns entities_sep = pd.DataFrame(all_entities.values.tolist(), all_entities.index).add_prefix('entity_') # Append all non-empty entities to a Series series1 = pd.Series(dtype=object) for col in entities_sep.columns: series1 = series1.append(entities_sep[entities_sep[col].notnull()][col]) missed_entity_df = series1.to_frame('entities').reset_index(drop = True) # Extract 'Entity' and 'Entity value' from dictionary to missed_entity missed_entity_df['Entity'] = missed_entity_df['entities'].apply(lambda x: x['entity']) missed_entity_df['Entity Value'] = missed_entity_df['entities'].apply(lambda x: x['value']) missed_entity_df['Synonym'] = missed_entity_df['entities'].apply(lambda x: x['synonym']) missed_entity = missed_entity_df[['Entity','Entity Value','Synonym']] # Calculate the number of times an entity with a value was missed missed_entity['Value Missed Count']=missed_entity.groupby(['Entity','Entity Value'])['Entity'].transform('count') # Calculate the total number of times an entity was missed missed_entity['Total Missed']= missed_entity.groupby(['Entity'])['Entity'].transform('count') # Remove duplicates missed_entity.drop_duplicates(keep = 'first', inplace=True)#sort_values(by='missed_entity') # Create a pivot table with counts df_pivot = pd.pivot_table(missed_entity, ['Value Missed Count'], ['Entity', 'Total Missed', 'Entity Value']) # Sort the table by total missed count missed_entities_all = df_pivot.reset_index().sort_values(['Total Missed','Entity','Value Missed Count'], ascending=False) # Get the first 25 entities in a list cols = missed_entities_all['Entity'].unique()[:25] # Set index of dataframe missed_entities_all = missed_entities_all.reset_index(drop = True).set_index(['Entity','Total Missed','Entity Value']) idx = pd.IndexSlice # Save the output CSV file missed_entities_all.to_csv(output_file_path, sep=',', encoding='utf-8') display(md('<p>')) display(md('<div style="max-width: 800px;"><div style="float: left">View the whole list here: <b><a href="{}" style="color:black" target="_blank">EntitiesMissed.csv</a></b></div><div style="float: right"> </div></div>'.format(output_file_path))) # Show the first 25 most missed entities missed_entities_all ``` ## 6. Perform dialog analysis<a id="dialog_analysis"></a> Dialog analysis highlights instances where dialog problems were the root cause of the ineffectiveness. Dialog could be the problem because either the wrong response condition was triggered or because there was no response condition in place to handle the user message. These situations are used as candidates for improvement. ``` # Get dialog data from annotated_data dataframe wrong_node_df = annotated_data['wrong_dialog_node'].value_counts().rename_axis('Node Name').reset_index(name='Node Count') table = '' if len(wrong_node_df) > 0: # Add a new column with reason for 'wrong dialog node' wrong_node_df.insert(loc=0, column='Dialog', value='Wrong node response triggered') # Find the number of times 'wrong node response' was triggered wrong_node_df['Utterances'] = wrong_node_df.groupby('Dialog')['Node Count'].transform(sum) else: print('No annotation data for \'Wrong node response triggered\'') if len(annotated_data['no_dialog_node_triggered'].dropna()) > 0: # Find the number of times 'no node response' was triggered wrong_node_df.loc[len(wrong_node_df)] = ['No node response triggered', 'N/A', 0, annotated_data['no_dialog_node_triggered'].value_counts()['Y']] else: print('No annotation data for \'No node response triggered\'') if len(wrong_node_df) > 0: # Create a pivot table with counts table = pd.pivot_table(wrong_node_df, ['Node Count'], ['Dialog','Utterances','Node Name']).to_html() HTML(table) ``` <a id="summary"></a> ## 7. Summary and recommendation This Notebook shows you the following summary metrics based on your assessment: 1. The overall precision and helpfulness of your assistant’s responses 2. Intent analysis 3. Entity analysis 4. Dialog analysis<br> To improve the performance of your assistant service, based on the above results, we provide the following recommendations and resources: #### Recommendations: - Entity * Use <a href="https://cloud.ibm.com/docs/assistant?topic=assistant-entities#entities-create-dictionary-based" target="_blank">Synonym Recommender</a> to improve the top missed entities indentified in [Entity Analysis](#entity_analysis). * Check and add the newly marked entities from <em>entity</em> sheet in [recommendation.xlsx](#improvement_recommendation) into your skill or workspace and use <a href="https://cloud.ibm.com/docs/assistant?topic=assistant-entities#entities-create-dictionary-based" target="_blank">Synonym Recommender</a> to enrich the list of various entity values. * Check and import newly identified entity values, from <em>entity_value</em> sheet in [recommendation.xlsx](#improvement_recommendation), into your skill or workspace. * Check and import the missed entity value synonyms, from <em>synonym</em> sheet in [recommendation.xlsx](#improvement_recommendation), into your skill or workspace. - Intent * Use intent <a href="https://cloud.ibm.com/docs/assistant?topic=assistant-intents#intents-resolve-conflicts" target="_blank">Conflict Resolver</a> to improve the top confused intent pair indentified in [Confused Intent Analysis](#intent_analysis4). * Check and import newly marked intent training utterance list, from <em>intent</em> sheet in [recommendation.xlsx](#improvement_recommendation), into your skill or workspace. - Dialog * Check the top problematic dialog nodes identified in [Dialog Analysis](#dialog_analysis). After those updates have been performed, you have the option to continue focusing your improvement efforts on any trouble spots identified during the Analyze phase. For more information, please check <a href="https://github.com/watson-developer-cloud/assistant-improve-recommendations-notebook/raw/master/notebook/IBM%20Watson%20Assistant%20Continuous%20Improvement%20Best%20Practices.pdf" target="_blank" rel="noopener noreferrer">Watson Assistant Continuous Improvement Best Practices</a>. Run the step below to generate `recommendation.xlsx`. ``` # Collect newly identified entities for training new_entity = annotated_data['new_entity'].dropna().reset_index(drop = True) # Convert the value into dict object new_entity = new_entity.apply(lambda x: ast.literal_eval(x)) # Separate entities into different columns new_entity_sep = pd.DataFrame(new_entity.values.tolist(), new_entity.index).add_prefix('entity_') # Append all non-empty entities to a Series series1 = pd.Series(dtype=object) for col in new_entity_sep.columns: series1 = series1.append(new_entity_sep[new_entity_sep[col].notnull()][col]) new_entity = series1.to_frame('entities').reset_index(drop = True) # Extract 'Entity' and 'Entity value' from dictionary to missed_entity new_entity['Entity'] = new_entity['entities'].apply(lambda x: x['entity']).drop_duplicates() # Collect newly identified entity values for training new_entity_value = annotated_data['new_entity_value'].dropna().reset_index(drop = True) # Convert the value into dict object new_entity_value = new_entity_value.apply(lambda x: ast.literal_eval(x)) # Separate entities into different columns new_entity_value_sep = pd.DataFrame(new_entity_value.values.tolist(), new_entity_value.index).add_prefix('entity_') # Append all non-empty entities to a Series series1 = pd.Series(dtype=object) for col in new_entity_value_sep.columns: series1 = series1.append(new_entity_value_sep[new_entity_value_sep[col].notnull()][col]) new_entity_value = series1.to_frame('entities').reset_index(drop = True) # Extract 'Entity' and 'Entity value' from dictionary to missed_entity new_entity_value['Entity'] = new_entity_value['entities'].apply(lambda x: x['entity']) new_entity_value['Entity Value'] = new_entity_value['entities'].apply(lambda x: x['value']) new_entity_value = new_entity_value[['Entity', 'Entity Value']].drop_duplicates() try: missed_entity except NameError: new_entity_synonym = pd.DataFrame(columns=['Entity','Entity Value','Synonym']) print('No missing entity in annotation') else: # Collect newly identified synonyms for training new_entity_synonym = missed_entity[['Entity','Entity Value','Synonym']].drop_duplicates() # Collect utterance marked as adding for training new_train_utterance = annotated_data.loc[annotated_data['add_train'] == 'Y'][['utterance_text','top_intent']].reset_index(drop = True) generate_excel_effectiveness([new_entity['Entity'], new_entity_value, new_entity_synonym, new_train_utterance], ['entity', 'entity_value','synonym', 'intent'], filename = 'recommendation.xlsx', project_io = None) display(md('### Resources:')) display(md('- <a id="improvement_recommendation"></a>Improvement recommendation: <a href="{}" target="_blank">recommendation.xlsx</a>'.format('recommendation.xlsx'))) ``` ### <a id="authors"></a>Authors **Zhe Zhang**, Ph.D. in Computer Science, is a Data Scientist for IBM Watson AI. Zhe has a research background in Natural Language Processing, Sentiment Analysis, Text Mining, and Machine Learning. His research has been published at leading conferences and journals including ACL and EMNLP. **Sherin Varughese** is a Data Scientist for IBM Watson AI. Sherin has her graduate degree in Business Intelligence and Data Analytics and has experience in Data Analysis, Warehousing and Machine Learning. ### <a id="acknowledgement"></a> Acknowledgement The authors would like to thank the following members of the IBM Research and Watson Assistant teams for their contributions and reviews of the notebook: Matt Arnold, Adam Benvie, Kyle Croutwater, Eric Wayne. Copyright © 2020 IBM. This notebook and its source code are released under the terms of the MIT License.
github_jupyter
# Deep Learning & Art: Neural Style Transfer Welcome to the second assignment of this week. In this assignment, you will learn about Neural Style Transfer. This algorithm was created by Gatys et al. (2015) (https://arxiv.org/abs/1508.06576). **In this assignment, you will:** - Implement the neural style transfer algorithm - Generate novel artistic images using your algorithm Most of the algorithms you've studied optimize a cost function to get a set of parameter values. In Neural Style Transfer, you'll optimize a cost function to get pixel values! ``` import os import sys import scipy.io import scipy.misc import matplotlib.pyplot as plt from matplotlib.pyplot import imshow from PIL import Image from nst_utils import * import numpy as np import tensorflow as tf %matplotlib inline ``` ## 1 - Problem Statement Neural Style Transfer (NST) is one of the most fun techniques in deep learning. As seen below, it merges two images, namely, a "content" image (C) and a "style" image (S), to create a "generated" image (G). The generated image G combines the "content" of the image C with the "style" of image S. In this example, you are going to generate an image of the Louvre museum in Paris (content image C), mixed with a painting by Claude Monet, a leader of the impressionist movement (style image S). <img src="images/louvre_generated.png" style="width:750px;height:200px;"> Let's see how you can do this. ## 2 - Transfer Learning Neural Style Transfer (NST) uses a previously trained convolutional network, and builds on top of that. The idea of using a network trained on a different task and applying it to a new task is called transfer learning. Following the original NST paper (https://arxiv.org/abs/1508.06576), we will use the VGG network. Specifically, we'll use VGG-19, a 19-layer version of the VGG network. This model has already been trained on the very large ImageNet database, and thus has learned to recognize a variety of low level features (at the earlier layers) and high level features (at the deeper layers). Run the following code to load parameters from the VGG model. This may take a few seconds. ``` model = load_vgg_model("pretrained-model/imagenet-vgg-verydeep-19.mat") print(model) ``` The model is stored in a python dictionary where each variable name is the key and the corresponding value is a tensor containing that variable's value. To run an image through this network, you just have to feed the image to the model. In TensorFlow, you can do so using the [tf.assign](https://www.tensorflow.org/api_docs/python/tf/assign) function. In particular, you will use the assign function like this: ```python model["input"].assign(image) ``` This assigns the image as an input to the model. After this, if you want to access the activations of a particular layer, say layer `4_2` when the network is run on this image, you would run a TensorFlow session on the correct tensor `conv4_2`, as follows: ```python sess.run(model["conv4_2"]) ``` ## 3 - Neural Style Transfer We will build the NST algorithm in three steps: - Build the content cost function $J_{content}(C,G)$ - Build the style cost function $J_{style}(S,G)$ - Put it together to get $J(G) = \alpha J_{content}(C,G) + \beta J_{style}(S,G)$. ### 3.1 - Computing the content cost In our running example, the content image C will be the picture of the Louvre Museum in Paris. Run the code below to see a picture of the Louvre. ``` content_image = scipy.misc.imread("images/louvre.jpg") imshow(content_image) ``` The content image (C) shows the Louvre museum's pyramid surrounded by old Paris buildings, against a sunny sky with a few clouds. ** 3.1.1 - How do you ensure the generated image G matches the content of the image C?** As we saw in lecture, the earlier (shallower) layers of a ConvNet tend to detect lower-level features such as edges and simple textures, and the later (deeper) layers tend to detect higher-level features such as more complex textures as well as object classes. We would like the "generated" image G to have similar content as the input image C. Suppose you have chosen some layer's activations to represent the content of an image. In practice, you'll get the most visually pleasing results if you choose a layer in the middle of the network--neither too shallow nor too deep. (After you have finished this exercise, feel free to come back and experiment with using different layers, to see how the results vary.) So, suppose you have picked one particular hidden layer to use. Now, set the image C as the input to the pretrained VGG network, and run forward propagation. Let $a^{(C)}$ be the hidden layer activations in the layer you had chosen. (In lecture, we had written this as $a^{[l](C)}$, but here we'll drop the superscript $[l]$ to simplify the notation.) This will be a $n_H \times n_W \times n_C$ tensor. Repeat this process with the image G: Set G as the input, and run forward progation. Let $$a^{(G)}$$ be the corresponding hidden layer activation. We will define as the content cost function as: $$J_{content}(C,G) = \frac{1}{4 \times n_H \times n_W \times n_C}\sum _{ \text{all entries}} (a^{(C)} - a^{(G)})^2\tag{1} $$ Here, $n_H, n_W$ and $n_C$ are the height, width and number of channels of the hidden layer you have chosen, and appear in a normalization term in the cost. For clarity, note that $a^{(C)}$ and $a^{(G)}$ are the volumes corresponding to a hidden layer's activations. In order to compute the cost $J_{content}(C,G)$, it might also be convenient to unroll these 3D volumes into a 2D matrix, as shown below. (Technically this unrolling step isn't needed to compute $J_{content}$, but it will be good practice for when you do need to carry out a similar operation later for computing the style const $J_{style}$.) <img src="images/NST_LOSS.png" style="width:800px;height:400px;"> **Exercise:** Compute the "content cost" using TensorFlow. **Instructions**: The 3 steps to implement this function are: 1. Retrieve dimensions from a_G: - To retrieve dimensions from a tensor X, use: `X.get_shape().as_list()` 2. Unroll a_C and a_G as explained in the picture above - If you are stuck, take a look at [Hint1](https://www.tensorflow.org/versions/r1.3/api_docs/python/tf/transpose) and [Hint2](https://www.tensorflow.org/versions/r1.2/api_docs/python/tf/reshape). 3. Compute the content cost: - If you are stuck, take a look at [Hint3](https://www.tensorflow.org/api_docs/python/tf/reduce_sum), [Hint4](https://www.tensorflow.org/api_docs/python/tf/square) and [Hint5](https://www.tensorflow.org/api_docs/python/tf/subtract). ``` # GRADED FUNCTION: compute_content_cost def compute_content_cost(a_C, a_G): """ Computes the content cost Arguments: a_C -- tensor of dimension (1, n_H, n_W, n_C), hidden layer activations representing content of the image C a_G -- tensor of dimension (1, n_H, n_W, n_C), hidden layer activations representing content of the image G Returns: J_content -- scalar that you compute using equation 1 above. """ ### START CODE HERE ### # Retrieve dimensions from a_G (≈1 line) m, n_H, n_W, n_C = a_G.get_shape().as_list() # Reshape a_C and a_G (≈2 lines) a_C_unrolled = tf.reshape(a_C,shape=(n_H * n_W, n_C)) a_G_unrolled = tf.reshape(a_G,shape=(n_H * n_W, n_C)) # compute the cost with tensorflow (≈1 line) J_content = tf.reduce_sum(tf.square(tf.subtract(a_C_unrolled,a_G_unrolled)))/(4 * n_H * n_W * n_C) ### END CODE HERE ### return J_content tf.reset_default_graph() with tf.Session() as test: tf.set_random_seed(1) a_C = tf.random_normal([1, 4, 4, 3], mean=1, stddev=4) a_G = tf.random_normal([1, 4, 4, 3], mean=1, stddev=4) J_content = compute_content_cost(a_C, a_G) print("J_content = " + str(J_content.eval())) ``` **Expected Output**: <table> <tr> <td> **J_content** </td> <td> 6.76559 </td> </tr> </table> <font color='blue'> **What you should remember**: - The content cost takes a hidden layer activation of the neural network, and measures how different $a^{(C)}$ and $a^{(G)}$ are. - When we minimize the content cost later, this will help make sure $G$ has similar content as $C$. ### 3.2 - Computing the style cost For our running example, we will use the following style image: ``` style_image = scipy.misc.imread("images/monet_800600.jpg") imshow(style_image) ``` This painting was painted in the style of *[impressionism](https://en.wikipedia.org/wiki/Impressionism)*. Lets see how you can now define a "style" const function $J_{style}(S,G)$. ### 3.2.1 - Style matrix The style matrix is also called a "Gram matrix." In linear algebra, the Gram matrix G of a set of vectors $(v_{1},\dots ,v_{n})$ is the matrix of dot products, whose entries are ${\displaystyle G_{ij} = v_{i}^T v_{j} = np.dot(v_{i}, v_{j}) }$. In other words, $G_{ij}$ compares how similar $v_i$ is to $v_j$: If they are highly similar, you would expect them to have a large dot product, and thus for $G_{ij}$ to be large. Note that there is an unfortunate collision in the variable names used here. We are following common terminology used in the literature, but $G$ is used to denote the Style matrix (or Gram matrix) as well as to denote the generated image $G$. We will try to make sure which $G$ we are referring to is always clear from the context. In NST, you can compute the Style matrix by multiplying the "unrolled" filter matrix with their transpose: <img src="images/NST_GM.png" style="width:900px;height:300px;"> The result is a matrix of dimension $(n_C,n_C)$ where $n_C$ is the number of filters. The value $G_{ij}$ measures how similar the activations of filter $i$ are to the activations of filter $j$. One important part of the gram matrix is that the diagonal elements such as $G_{ii}$ also measures how active filter $i$ is. For example, suppose filter $i$ is detecting vertical textures in the image. Then $G_{ii}$ measures how common vertical textures are in the image as a whole: If $G_{ii}$ is large, this means that the image has a lot of vertical texture. By capturing the prevalence of different types of features ($G_{ii}$), as well as how much different features occur together ($G_{ij}$), the Style matrix $G$ measures the style of an image. **Exercise**: Using TensorFlow, implement a function that computes the Gram matrix of a matrix A. The formula is: The gram matrix of A is $G_A = AA^T$. If you are stuck, take a look at [Hint 1](https://www.tensorflow.org/api_docs/python/tf/matmul) and [Hint 2](https://www.tensorflow.org/api_docs/python/tf/transpose). ``` # GRADED FUNCTION: gram_matrix def gram_matrix(A): """ Argument: A -- matrix of shape (n_C, n_H*n_W) Returns: GA -- Gram matrix of A, of shape (n_C, n_C) """ ### START CODE HERE ### (≈1 line) GA = tf.matmul(A, tf.transpose(A)) ### END CODE HERE ### return GA tf.reset_default_graph() with tf.Session() as test: tf.set_random_seed(1) A = tf.random_normal([3, 2*1], mean=1, stddev=4) GA = gram_matrix(A) print("GA = " + str(GA.eval())) ``` **Expected Output**: <table> <tr> <td> **GA** </td> <td> [[ 6.42230511 -4.42912197 -2.09668207] <br> [ -4.42912197 19.46583748 19.56387138] <br> [ -2.09668207 19.56387138 20.6864624 ]] </td> </tr> </table> ### 3.2.2 - Style cost After generating the Style matrix (Gram matrix), your goal will be to minimize the distance between the Gram matrix of the "style" image S and that of the "generated" image G. For now, we are using only a single hidden layer $a^{[l]}$, and the corresponding style cost for this layer is defined as: $$J_{style}^{[l]}(S,G) = \frac{1}{4 \times {n_C}^2 \times (n_H \times n_W)^2} \sum _{i=1}^{n_C}\sum_{j=1}^{n_C}(G^{(S)}_{ij} - G^{(G)}_{ij})^2\tag{2} $$ where $G^{(S)}$ and $G^{(G)}$ are respectively the Gram matrices of the "style" image and the "generated" image, computed using the hidden layer activations for a particular hidden layer in the network. **Exercise**: Compute the style cost for a single layer. **Instructions**: The 3 steps to implement this function are: 1. Retrieve dimensions from the hidden layer activations a_G: - To retrieve dimensions from a tensor X, use: `X.get_shape().as_list()` 2. Unroll the hidden layer activations a_S and a_G into 2D matrices, as explained in the picture above. - You may find [Hint1](https://www.tensorflow.org/versions/r1.3/api_docs/python/tf/transpose) and [Hint2](https://www.tensorflow.org/versions/r1.2/api_docs/python/tf/reshape) useful. 3. Compute the Style matrix of the images S and G. (Use the function you had previously written.) 4. Compute the Style cost: - You may find [Hint3](https://www.tensorflow.org/api_docs/python/tf/reduce_sum), [Hint4](https://www.tensorflow.org/api_docs/python/tf/square) and [Hint5](https://www.tensorflow.org/api_docs/python/tf/subtract) useful. ``` # GRADED FUNCTION: compute_layer_style_cost def compute_layer_style_cost(a_S, a_G): """ Arguments: a_S -- tensor of dimension (1, n_H, n_W, n_C), hidden layer activations representing style of the image S a_G -- tensor of dimension (1, n_H, n_W, n_C), hidden layer activations representing style of the image G Returns: J_style_layer -- tensor representing a scalar value, style cost defined above by equation (2) """ ### START CODE HERE ### # Retrieve dimensions from a_G (≈1 line) m, n_H, n_W, n_C = a_G.get_shape().as_list() # Reshape the images to have them of shape (n_C, n_H*n_W) (≈2 lines) a_S = tf.reshape(a_S, shape=(n_H * n_W, n_C)) a_G = tf.reshape(a_G, shape=(n_H * n_W, n_C)) # Computing gram_matrices for both images S and G (≈2 lines) GS = gram_matrix(tf.transpose(a_S)) GG = gram_matrix(tf.transpose(a_G)) # Computing the loss (≈1 line) J_style_layer = tf.reduce_sum(tf.square(tf.subtract(GS,GG))) / (4*(n_C*n_C)*(n_W * n_H) * (n_W * n_H)) ### END CODE HERE ### return J_style_layer tf.reset_default_graph() with tf.Session() as test: tf.set_random_seed(1) a_S = tf.random_normal([1, 4, 4, 3], mean=1, stddev=4) a_G = tf.random_normal([1, 4, 4, 3], mean=1, stddev=4) J_style_layer = compute_layer_style_cost(a_S, a_G) print("J_style_layer = " + str(J_style_layer.eval())) ``` **Expected Output**: <table> <tr> <td> **J_style_layer** </td> <td> 9.19028 </td> </tr> </table> ### 3.2.3 Style Weights So far you have captured the style from only one layer. We'll get better results if we "merge" style costs from several different layers. After completing this exercise, feel free to come back and experiment with different weights to see how it changes the generated image $G$. But for now, this is a pretty reasonable default: ``` STYLE_LAYERS = [ ('conv1_1', 0.2), ('conv2_1', 0.2), ('conv3_1', 0.2), ('conv4_1', 0.2), ('conv5_1', 0.2)] ``` You can combine the style costs for different layers as follows: $$J_{style}(S,G) = \sum_{l} \lambda^{[l]} J^{[l]}_{style}(S,G)$$ where the values for $\lambda^{[l]}$ are given in `STYLE_LAYERS`. We've implemented a compute_style_cost(...) function. It simply calls your `compute_layer_style_cost(...)` several times, and weights their results using the values in `STYLE_LAYERS`. Read over it to make sure you understand what it's doing. <!-- 2. Loop over (layer_name, coeff) from STYLE_LAYERS: a. Select the output tensor of the current layer. As an example, to call the tensor from the "conv1_1" layer you would do: out = model["conv1_1"] b. Get the style of the style image from the current layer by running the session on the tensor "out" c. Get a tensor representing the style of the generated image from the current layer. It is just "out". d. Now that you have both styles. Use the function you've implemented above to compute the style_cost for the current layer e. Add (style_cost x coeff) of the current layer to overall style cost (J_style) 3. Return J_style, which should now be the sum of the (style_cost x coeff) for each layer. !--> ``` def compute_style_cost(model, STYLE_LAYERS): """ Computes the overall style cost from several chosen layers Arguments: model -- our tensorflow model STYLE_LAYERS -- A python list containing: - the names of the layers we would like to extract style from - a coefficient for each of them Returns: J_style -- tensor representing a scalar value, style cost defined above by equation (2) """ # initialize the overall style cost J_style = 0 for layer_name, coeff in STYLE_LAYERS: # Select the output tensor of the currently selected layer out = model[layer_name] # Set a_S to be the hidden layer activation from the layer we have selected, by running the session on out a_S = sess.run(out) # Set a_G to be the hidden layer activation from same layer. Here, a_G references model[layer_name] # and isn't evaluated yet. Later in the code, we'll assign the image G as the model input, so that # when we run the session, this will be the activations drawn from the appropriate layer, with G as input. a_G = out # Compute style_cost for the current layer J_style_layer = compute_layer_style_cost(a_S, a_G) # Add coeff * J_style_layer of this layer to overall style cost J_style += coeff * J_style_layer return J_style ``` **Note**: In the inner-loop of the for-loop above, `a_G` is a tensor and hasn't been evaluated yet. It will be evaluated and updated at each iteration when we run the TensorFlow graph in model_nn() below. <!-- How do you choose the coefficients for each layer? The deeper layers capture higher-level concepts, and the features in the deeper layers are less localized in the image relative to each other. So if you want the generated image to softly follow the style image, try choosing larger weights for deeper layers and smaller weights for the first layers. In contrast, if you want the generated image to strongly follow the style image, try choosing smaller weights for deeper layers and larger weights for the first layers !--> <font color='blue'> **What you should remember**: - The style of an image can be represented using the Gram matrix of a hidden layer's activations. However, we get even better results combining this representation from multiple different layers. This is in contrast to the content representation, where usually using just a single hidden layer is sufficient. - Minimizing the style cost will cause the image $G$ to follow the style of the image $S$. </font color='blue'> ### 3.3 - Defining the total cost to optimize Finally, let's create a cost function that minimizes both the style and the content cost. The formula is: $$J(G) = \alpha J_{content}(C,G) + \beta J_{style}(S,G)$$ **Exercise**: Implement the total cost function which includes both the content cost and the style cost. ``` # GRADED FUNCTION: total_cost def total_cost(J_content, J_style, alpha = 10, beta = 40): """ Computes the total cost function Arguments: J_content -- content cost coded above J_style -- style cost coded above alpha -- hyperparameter weighting the importance of the content cost beta -- hyperparameter weighting the importance of the style cost Returns: J -- total cost as defined by the formula above. """ ### START CODE HERE ### (≈1 line) J = alpha * J_content + beta * J_style ### END CODE HERE ### return J tf.reset_default_graph() with tf.Session() as test: np.random.seed(3) J_content = np.random.randn() J_style = np.random.randn() J = total_cost(J_content, J_style) print("J = " + str(J)) ``` **Expected Output**: <table> <tr> <td> **J** </td> <td> 35.34667875478276 </td> </tr> </table> <font color='blue'> **What you should remember**: - The total cost is a linear combination of the content cost $J_{content}(C,G)$ and the style cost $J_{style}(S,G)$ - $\alpha$ and $\beta$ are hyperparameters that control the relative weighting between content and style ## 4 - Solving the optimization problem Finally, let's put everything together to implement Neural Style Transfer! Here's what the program will have to do: <font color='purple'> 1. Create an Interactive Session 2. Load the content image 3. Load the style image 4. Randomly initialize the image to be generated 5. Load the VGG16 model 7. Build the TensorFlow graph: - Run the content image through the VGG16 model and compute the content cost - Run the style image through the VGG16 model and compute the style cost - Compute the total cost - Define the optimizer and the learning rate 8. Initialize the TensorFlow graph and run it for a large number of iterations, updating the generated image at every step. </font> Lets go through the individual steps in detail. You've previously implemented the overall cost $J(G)$. We'll now set up TensorFlow to optimize this with respect to $G$. To do so, your program has to reset the graph and use an "[Interactive Session](https://www.tensorflow.org/api_docs/python/tf/InteractiveSession)". Unlike a regular session, the "Interactive Session" installs itself as the default session to build a graph. This allows you to run variables without constantly needing to refer to the session object, which simplifies the code. Lets start the interactive session. ``` # Reset the graph tf.reset_default_graph() # Start interactive session sess = tf.InteractiveSession() ``` Let's load, reshape, and normalize our "content" image (the Louvre museum picture): ``` content_image = scipy.misc.imread("images/louvre_small.jpg") content_image = reshape_and_normalize_image(content_image) ``` Let's load, reshape and normalize our "style" image (Claude Monet's painting): ``` style_image = scipy.misc.imread("images/monet.jpg") style_image = reshape_and_normalize_image(style_image) ``` Now, we initialize the "generated" image as a noisy image created from the content_image. By initializing the pixels of the generated image to be mostly noise but still slightly correlated with the content image, this will help the content of the "generated" image more rapidly match the content of the "content" image. (Feel free to look in `nst_utils.py` to see the details of `generate_noise_image(...)`; to do so, click "File-->Open..." at the upper-left corner of this Jupyter notebook.) ``` generated_image = generate_noise_image(content_image) imshow(generated_image[0]) ``` Next, as explained in part (2), let's load the VGG16 model. ``` model = load_vgg_model("pretrained-model/imagenet-vgg-verydeep-19.mat") ``` To get the program to compute the content cost, we will now assign `a_C` and `a_G` to be the appropriate hidden layer activations. We will use layer `conv4_2` to compute the content cost. The code below does the following: 1. Assign the content image to be the input to the VGG model. 2. Set a_C to be the tensor giving the hidden layer activation for layer "conv4_2". 3. Set a_G to be the tensor giving the hidden layer activation for the same layer. 4. Compute the content cost using a_C and a_G. ``` # Assign the content image to be the input of the VGG model. sess.run(model['input'].assign(content_image)) # Select the output tensor of layer conv4_2 out = model['conv4_2'] # Set a_C to be the hidden layer activation from the layer we have selected a_C = sess.run(out) # Set a_G to be the hidden layer activation from same layer. Here, a_G references model['conv4_2'] # and isn't evaluated yet. Later in the code, we'll assign the image G as the model input, so that # when we run the session, this will be the activations drawn from the appropriate layer, with G as input. a_G = out # Compute the content cost J_content = compute_content_cost(a_C, a_G) ``` **Note**: At this point, a_G is a tensor and hasn't been evaluated. It will be evaluated and updated at each iteration when we run the Tensorflow graph in model_nn() below. ``` # Assign the input of the model to be the "style" image sess.run(model['input'].assign(style_image)) # Compute the style cost J_style = compute_style_cost(model, STYLE_LAYERS) ``` **Exercise**: Now that you have J_content and J_style, compute the total cost J by calling `total_cost()`. Use `alpha = 10` and `beta = 40`. ``` ### START CODE HERE ### (1 line) J = total_cost(J_content, J_style, alpha=10, beta=40) ### END CODE HERE ### ``` You'd previously learned how to set up the Adam optimizer in TensorFlow. Lets do that here, using a learning rate of 2.0. [See reference](https://www.tensorflow.org/api_docs/python/tf/train/AdamOptimizer) ``` # define optimizer (1 line) optimizer = tf.train.AdamOptimizer(2.0) # define train_step (1 line) train_step = optimizer.minimize(J) ``` **Exercise**: Implement the model_nn() function which initializes the variables of the tensorflow graph, assigns the input image (initial generated image) as the input of the VGG16 model and runs the train_step for a large number of steps. ``` def model_nn(sess, input_image, num_iterations = 200): # Initialize global variables (you need to run the session on the initializer) ### START CODE HERE ### (1 line) sess.run(tf.global_variables_initializer()) ### END CODE HERE ### # Run the noisy input image (initial generated image) through the model. Use assign(). ### START CODE HERE ### (1 line) generated_image=sess.run(model['input'].assign(input_image)) ### END CODE HERE ### for i in range(num_iterations): # Run the session on the train_step to minimize the total cost ### START CODE HERE ### (1 line) sess.run(train_step) ### END CODE HERE ### # Compute the generated image by running the session on the current model['input'] ### START CODE HERE ### (1 line) generated_image = sess.run(model['input']) ### END CODE HERE ### # Print every 20 iteration. if i%20 == 0: Jt, Jc, Js = sess.run([J, J_content, J_style]) print("Iteration " + str(i) + " :") print("total cost = " + str(Jt)) print("content cost = " + str(Jc)) print("style cost = " + str(Js)) # save current generated image in the "/output" directory save_image("output/" + str(i) + ".png", generated_image) # save last generated image save_image('output/generated_image.jpg', generated_image) return generated_image ``` Run the following cell to generate an artistic image. It should take about 3min on CPU for every 20 iterations but you start observing attractive results after ≈140 iterations. Neural Style Transfer is generally trained using GPUs. ``` model_nn(sess, generated_image) ``` **Expected Output**: <table> <tr> <td> **Iteration 0 : ** </td> <td> total cost = 5.05035e+09 <br> content cost = 7877.67 <br> style cost = 1.26257e+08 </td> </tr> </table> You're done! After running this, in the upper bar of the notebook click on "File" and then "Open". Go to the "/output" directory to see all the saved images. Open "generated_image" to see the generated image! :) You should see something the image presented below on the right: <img src="images/louvre_generated.png" style="width:800px;height:300px;"> We didn't want you to wait too long to see an initial result, and so had set the hyperparameters accordingly. To get the best looking results, running the optimization algorithm longer (and perhaps with a smaller learning rate) might work better. After completing and submitting this assignment, we encourage you to come back and play more with this notebook, and see if you can generate even better looking images. Here are few other examples: - The beautiful ruins of the ancient city of Persepolis (Iran) with the style of Van Gogh (The Starry Night) <img src="images/perspolis_vangogh.png" style="width:750px;height:300px;"> - The tomb of Cyrus the great in Pasargadae with the style of a Ceramic Kashi from Ispahan. <img src="images/pasargad_kashi.png" style="width:750px;height:300px;"> - A scientific study of a turbulent fluid with the style of a abstract blue fluid painting. <img src="images/circle_abstract.png" style="width:750px;height:300px;"> ## 5 - Test with your own image (Optional/Ungraded) Finally, you can also rerun the algorithm on your own images! To do so, go back to part 4 and change the content image and style image with your own pictures. In detail, here's what you should do: 1. Click on "File -> Open" in the upper tab of the notebook 2. Go to "/images" and upload your images (requirement: (WIDTH = 300, HEIGHT = 225)), rename them "my_content.png" and "my_style.png" for example. 3. Change the code in part (3.4) from : ```python content_image = scipy.misc.imread("images/louvre.jpg") style_image = scipy.misc.imread("images/claude-monet.jpg") ``` to: ```python content_image = scipy.misc.imread("images/my_content.jpg") style_image = scipy.misc.imread("images/my_style.jpg") ``` 4. Rerun the cells (you may need to restart the Kernel in the upper tab of the notebook). You can also tune your hyperparameters: - Which layers are responsible for representing the style? STYLE_LAYERS - How many iterations do you want to run the algorithm? num_iterations - What is the relative weighting between content and style? alpha/beta ## 6 - Conclusion Great job on completing this assignment! You are now able to use Neural Style Transfer to generate artistic images. This is also your first time building a model in which the optimization algorithm updates the pixel values rather than the neural network's parameters. Deep learning has many different types of models and this is only one of them! <font color='blue'> What you should remember: - Neural Style Transfer is an algorithm that given a content image C and a style image S can generate an artistic image - It uses representations (hidden layer activations) based on a pretrained ConvNet. - The content cost function is computed using one hidden layer's activations. - The style cost function for one layer is computed using the Gram matrix of that layer's activations. The overall style cost function is obtained using several hidden layers. - Optimizing the total cost function results in synthesizing new images. This was the final programming exercise of this course. Congratulations--you've finished all the programming exercises of this course on Convolutional Networks! We hope to also see you in Course 5, on Sequence models! ### References: The Neural Style Transfer algorithm was due to Gatys et al. (2015). Harish Narayanan and Github user "log0" also have highly readable write-ups from which we drew inspiration. The pre-trained network used in this implementation is a VGG network, which is due to Simonyan and Zisserman (2015). Pre-trained weights were from the work of the MathConvNet team. - Leon A. Gatys, Alexander S. Ecker, Matthias Bethge, (2015). A Neural Algorithm of Artistic Style (https://arxiv.org/abs/1508.06576) - Harish Narayanan, Convolutional neural networks for artistic style transfer. https://harishnarayanan.org/writing/artistic-style-transfer/ - Log0, TensorFlow Implementation of "A Neural Algorithm of Artistic Style". http://www.chioka.in/tensorflow-implementation-neural-algorithm-of-artistic-style - Karen Simonyan and Andrew Zisserman (2015). Very deep convolutional networks for large-scale image recognition (https://arxiv.org/pdf/1409.1556.pdf) - MatConvNet. http://www.vlfeat.org/matconvnet/pretrained/
github_jupyter
<table class="ee-notebook-buttons" align="left"> <td><a target="_blank" href="https://github.com/giswqs/earthengine-py-notebooks/tree/master/Datasets/Terrain/us_ned_physio_diversity.ipynb"><img width=32px src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" /> View source on GitHub</a></td> <td><a target="_blank" href="https://nbviewer.jupyter.org/github/giswqs/earthengine-py-notebooks/blob/master/Datasets/Terrain/us_ned_physio_diversity.ipynb"><img width=26px src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/38/Jupyter_logo.svg/883px-Jupyter_logo.svg.png" />Notebook Viewer</a></td> <td><a target="_blank" href="https://colab.research.google.com/github/giswqs/earthengine-py-notebooks/blob/master/Datasets/Terrain/us_ned_physio_diversity.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" /> Run in Google Colab</a></td> </table> ## Install Earth Engine API and geemap Install the [Earth Engine Python API](https://developers.google.com/earth-engine/python_install) and [geemap](https://geemap.org). The **geemap** Python package is built upon the [ipyleaflet](https://github.com/jupyter-widgets/ipyleaflet) and [folium](https://github.com/python-visualization/folium) packages and implements several methods for interacting with Earth Engine data layers, such as `Map.addLayer()`, `Map.setCenter()`, and `Map.centerObject()`. The following script checks if the geemap package has been installed. If not, it will install geemap, which automatically installs its [dependencies](https://github.com/giswqs/geemap#dependencies), including earthengine-api, folium, and ipyleaflet. ``` # Installs geemap package import subprocess try: import geemap except ImportError: print('Installing geemap ...') subprocess.check_call(["python", '-m', 'pip', 'install', 'geemap']) import ee import geemap ``` ## Create an interactive map The default basemap is `Google Maps`. [Additional basemaps](https://github.com/giswqs/geemap/blob/master/geemap/basemaps.py) can be added using the `Map.add_basemap()` function. ``` Map = geemap.Map(center=[40,-100], zoom=4) Map ``` ## Add Earth Engine Python script ``` # Add Earth Engine dataset dataset = ee.Image('CSP/ERGo/1_0/US/physioDiversity') physiographicDiversity = dataset.select('b1') physiographicDiversityVis = { 'min': 0.0, 'max': 1.0, } Map.setCenter(-94.625, 39.825, 7) Map.addLayer( physiographicDiversity, physiographicDiversityVis, 'Physiographic Diversity') ``` ## Display Earth Engine data layers ``` Map.addLayerControl() # This line is not needed for ipyleaflet-based Map. Map ```
github_jupyter
``` import torch import torch.nn as nn import torchvision import torchvision.transforms as transforms # Device configuration device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # Hyper-parameters input_size = 784 hidden_size = 500 num_classes = 10 num_epochs = 5 batch_size = 100 learning_rate = 0.001 torch.cuda.is_available() print('device properties:', torch.cuda.get_device_properties(0)) #can be 0~torch.cuda.device_count()-1 print('device count:', torch.cuda.device_count()) # MNIST dataset train_dataset = torchvision.datasets.MNIST(root='../../data', train=True, transform=transforms.ToTensor(), download=True) test_dataset = torchvision.datasets.MNIST(root='../../data', train=False, transform=transforms.ToTensor()) # Data loader train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True) test_loader = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=False) # Fully connected neural network with one hidden layer class NeuralNet(nn.Module): def __init__(self, input_size, hidden_size, num_classes): super(NeuralNet, self).__init__() self.fc1 = nn.Linear(input_size, hidden_size) self.relu = nn.ReLU() self.fc2 = nn.Linear(hidden_size, num_classes) def forward(self, x): out = self.fc1(x) out = self.relu(out) out = self.fc2(out) return out """ model_cpu.children(): generator list(model_cpu.children()): [Linear(in_features=784, out_features=500, bias=True), ReLU(), Linear(in_features=500, out_features=10, bias=True)] """ model_cpu = NeuralNet(input_size, hidden_size, num_classes) print(list(model_cpu.children())[0].weight) """ model_cpu.to(device, dtype or tensor) """ model = model_cpu.to(device) print(list(model.children())[0].weight) ``` ``` # Loss and optimizer criterion = nn.CrossEntropyLoss() optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate) # Train the model total_step = len(train_loader) #=len(train_dataset)/batch_size for epoch in range(num_epochs): for i, (images, labels) in enumerate(train_loader): # Move tensors to the configured device """ If we omit .to(device) after the following two variables, it will give RuntimeError: Expected object of backend CUDA but got backend CPU for argument #4 'mat1' """ images = images.reshape(-1, 28*28).to(device) labels = labels.to(device) # Forward pass outputs = model(images) loss = criterion(outputs, labels) # Backward and optimize optimizer.zero_grad() loss.backward() optimizer.step() if (i+1) % (total_step/6) == 0: print ('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}' .format(epoch+1, num_epochs, i+1, total_step, loss.item())) # Test the model # In test phase, we don't need to compute gradients (for memory efficiency) """ torch.no_grad: Context-manager that disabled gradient calculation. """ with torch.no_grad(): correct = 0 total = 0 for images, labels in test_loader: images = images.reshape(-1, 28*28).to(device) labels = labels.to(device) outputs = model(images) """ max_value, index_of_max_value = torch.max(input, dim) input: tensor dim: int """ """The results from torch.max(outputs,1) and torch.max(outputs.data, 1) are the same""" _, predicted = torch.max(outputs.data, 1) # _, predicted = torch.max(outputs, 1) """ labels.size(): torch.Size labels.size(0): int """ total += labels.size(0) """(predicted==labels) returns a dytpe=torch.uint8 tensor""" """tensor.item(): get number from a tensor""" correct += (predicted == labels).sum().item() print('Accuracy of the network on the 10000 test images: {} %'.format(100 * correct / total)) # Save the model checkpoint torch.save(model.state_dict(), 'model.ckpt') ```
github_jupyter
``` import pickle import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import numpy as np import uproot3_methods as uproot_methods import networkx as nx import glob from matplotlib.colors import LogNorm import pandas import json import sklearn import sklearn.metrics import bz2 import mpl_toolkits import mplhep as hep plt.style.use(hep.style.ROOT) !pwd class PDF(object): def __init__(self, pdf, size=(200,200)): self.pdf = pdf self.size = size def _repr_html_(self): return '<iframe src={0} width={1[0]} height={1[1]}></iframe>'.format(self.pdf, self.size) def _repr_latex_(self): return r'\includegraphics[width=1.0\textwidth]{{{0}}}'.format(self.pdf) sample_title_qcd = "QCD, 14 TeV, PU200" sample_title_ttbar = "$t\\bar{t}$, 14 TeV, PU200" def sample_string_qcd(ax, x=0.0): ax.set_title(sample_title_qcd, x=x, ha="left", va="bottom") def sample_string_ttbar(ax, x=0.0): ax.set_title(sample_title_ttbar, x=x, ha="left", va="bottom") def midpoints(x): return x[:-1] + np.diff(x)/2 def mask_empty(hist): h0 = hist[0].astype(np.float64) h0[h0<50] = 0 return (h0, hist[1]) def divide_zero(a, b): a = a.astype(np.float64) b = b.astype(np.float64) out = np.zeros_like(a) np.divide(a, b, where=b>0, out=out) return out !rm -Rf plots !mkdir -p plots # #Raw input data !wget --no-clobber https://zenodo.org/record/4559324/files/tev14_pythia8_ttbar_0_0.pkl.bz2 # #predictions file !wget --no-clobber https://jpata.web.cern.ch/jpata/2101.08578/v2/pred_qcd.npz.bz2 !wget --no-clobber https://jpata.web.cern.ch/jpata/2101.08578/v2/pred_ttbar.npz.bz2 # #timing file !wget --no-clobber https://jpata.web.cern.ch/jpata/2101.08578/v1/synthetic_timing.json !bzip2 -d pred_qcd.npz.bz2 !bzip2 -d pred_ttbar.npz.bz2 ``` ## Draw a single event ``` data = pickle.load(bz2.BZ2File("tev14_pythia8_ttbar_0_0.pkl.bz2", "rb")) #We have a set 100 of events in one file len(data["ycand"]), len(data["ygen"]), len(data["X"]) #for each event, we have a number of input elements (X) # 0-padded arrays of the target particles from generator (ygen) and from the baseline algo (ycand) data["X"][0].shape, data["ygen"][0].shape, data["ycand"][0].shape, X = data["X"][0] ycand = data["ycand"][0] ygen = data["ygen"][0] #Input element feature vector, defined in ntuplizer.py:make_tower_array,make_track_array: # tower: (type, Et, eta, sin phi, cos phi, E, Eem, Ehad) # track: (type, pt, eta, sin phi, cos phi, P, eta_outer, sin phi_outer, cos phi_outer, charge, is_gen_muon, is_gen_electron) X[0, :] #Get masks for the tracks, ECAL and HCAL elements msk_trk = X[:, 0] == 2 msk_ecal = (X[:, 0] == 1) & (X[:, 6] > 0) msk_hcal = (X[:, 0] == 1) & (X[:, 7] > 0) arr_trk = pandas.DataFrame(X[msk_trk], columns=["id", "pt", "eta", "sphi", "cphi", "p", "eta_outer", "sphi_outer", "cphi_outer", "charge", "is_gen_muon", "is_gen_ele"]) arr_ecal = pandas.DataFrame(X[msk_ecal][:, :6], columns=["id", "et", "eta", "sphi", "cphi", "e"]) arr_hcal = pandas.DataFrame(X[msk_hcal][:, :6], columns=["id", "et", "eta", "sphi", "cphi", "e"]) arr_gen = pandas.DataFrame(ygen[ygen[:, 0]!=0], columns=["id", "charge", "pt", "eta", "sphi", "cphi", "energy"]) #compute track x,y on the inner and outer surfaces points_a = arr_trk["eta"].values, np.arctan2(arr_trk["sphi"], arr_trk["cphi"]).values points_b = arr_trk["eta_outer"].values, np.arctan2(arr_trk["sphi_outer"], arr_trk["cphi_outer"]).values r1 = 0.5 r2 = 1.0 r3 = 1.2 r4 = 1.4 r5 = 1.6 points = [] for i in range(len(arr_trk)): point = [] point.append((0,0,0)) point.append((points_a[0][i], r1*np.sin(points_a[1][i]), r1*np.cos(points_a[1][i]))) point.append((points_b[0][i], r2*np.sin(points_b[1][i]), r2*np.cos(points_b[1][i]))) points.append(point) points_etaphi = [] for i in range(len(arr_trk)): point = [] point.append((points_a[0][i], points_a[1][i])) point.append((points_b[0][i], points_b[1][i])) points_etaphi.append(point) points_xyz = [] for i in range(len(arr_trk)): point = [] point.append((0,0,0)) point.append((r1*np.sinh(points_a[0][i]), r1*np.sin(points_a[1][i]), r1*np.cos(points_a[1][i]))) point.append((r2*np.sinh(points_b[0][i]), r2*np.sin(points_b[1][i]), r2*np.cos(points_b[1][i]))) points.append(point) fig = plt.figure(figsize=(14,10)) plot_tracks = True plot_ecal = True plot_hcal = True plot_gen = True ax = fig.add_subplot(111, projection='3d') if plot_tracks: lc = mpl_toolkits.mplot3d.art3d.Line3DCollection(points, linewidths=0.2, color="gray", alpha=0.5) ax.add_collection(lc) # just for better legend lc2 = mpl_toolkits.mplot3d.art3d.Line3DCollection([], linewidths=2, color="gray", alpha=0.5, label="Tracks") ax.add_collection(lc2) if plot_ecal: ax.scatter(arr_ecal["eta"], r3*arr_ecal["sphi"], r3*arr_ecal["cphi"], s=0.1*arr_ecal["e"], color=u'#1f77b4', marker="s", alpha=0.5) if plot_hcal: ax.scatter(arr_hcal["eta"], r4*arr_hcal["sphi"], r4*arr_hcal["cphi"], s=0.1*arr_hcal["e"], color=u'#ff7f0e', marker="s", alpha=0.5) if plot_gen: ax.scatter(arr_gen["eta"], r5*arr_gen["sphi"], r5*arr_gen["cphi"], alpha=0.2, marker="x", color="red") # just for better legend ax.scatter([],[], [], alpha=0.5, marker="s", s = 50, color=u'#1f77b4', label="ECAL clusters") ax.scatter([],[], [], alpha=0.5, marker="s", s = 100, color=u'#ff7f0e', label="HCAL clusters") ax.scatter([],[], [], alpha=0.5, marker="x", s = 50, color="red", label="Truth particles") ax.set_zlabel(r"$y$ [a.u.]",labelpad=15) ax.set_ylabel(r"$x$ [a.u.]",labelpad=15) ax.set_xlabel(r"$\eta$",labelpad=15) from matplotlib.ticker import MultipleLocator, AutoMinorLocator ax.xaxis.set_major_locator(MultipleLocator(2)) ax.yaxis.set_major_locator(MultipleLocator(1)) ax.zaxis.set_major_locator(MultipleLocator(1)) ax.xaxis.set_minor_locator(MultipleLocator(1)) ax.yaxis.set_minor_locator(MultipleLocator(0.5)) ax.zaxis.set_minor_locator(MultipleLocator(0.5)) ax.xaxis._axinfo["grid"].update({"linewidth":0.2, "color" : "gray", "which":"major", "linestyle":"--","alpha":0.1}) ax.yaxis._axinfo["grid"].update({"linewidth":0.2, "color" : "gray", "which":"major", "linestyle":"--","alpha":0.1}) ax.zaxis._axinfo["grid"].update({"linewidth":0.2, "color" : "gray", "which":"major", "linestyle":"--","alpha":0.1}) ax.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 1.0)) ax.w_yaxis.set_pane_color((1.0, 1.0, 1.0, 1.0)) ax.w_zaxis.set_pane_color((1.0, 1.0, 1.0, 1.0)) ax.set_xlim(-5.75, 5.75) ax.set_ylim(-1.75, 1.75) ax.set_zlim(-1.75, 1.75) legend = plt.legend(title =r"$t\overline{t}$, 14 TeV, 200 PU",frameon=False, bbox_to_anchor=(0.92, 1.0), loc='upper left',fontsize=20) plt.setp(legend.get_title(),fontsize=22) #plt.title("Simulated event with PU200") plt.savefig("plots/event.pdf", bbox_inches="tight") plt.savefig("plots/event.png", bbox_inches="tight", dpi=200) plt.show() # rotate the axes and update for angle in range(0, 360, 3): ax.view_init(30, angle+300) plt.draw() plt.savefig("plots/event_%03d.jpg"%angle) #!convert -delay 5 -loop -1 plots/event_*.jpg plots/event_rotate.gif fig = plt.figure(figsize=(14,10)) ax = fig.add_subplot(111, projection='3d') lc = mpl_toolkits.mplot3d.art3d.Line3DCollection(points_xyz, linewidths=0.2, color="gray", alpha=0.5) ax.add_collection(lc) # just for better legend lc2 = mpl_toolkits.mplot3d.art3d.Line3DCollection([], linewidths=2, color="gray", alpha=0.5, label="Tracks") ax.add_collection(lc2) ax.scatter(r3*np.sinh(arr_ecal["eta"]), r3*arr_ecal["sphi"], r3*arr_ecal["cphi"], s=0.1*arr_ecal["e"], color=u'#1f77b4', marker="s", alpha=0.5) ax.scatter(r4*np.sinh(arr_hcal["eta"]), r4*arr_hcal["sphi"], r4*arr_hcal["cphi"], s=0.1*arr_hcal["e"], color=u'#ff7f0e', marker="s", alpha=0.5) ax.scatter(r5*np.sinh(arr_gen["eta"]), r5*arr_gen["sphi"], r5*arr_gen["cphi"], alpha=0.2, marker="x", color="red") # just for better legend ax.scatter([],[], [], alpha=0.5, marker="s", s = 50, color=u'#1f77b4', label="ECAL clusters") ax.scatter([],[], [], alpha=0.5, marker="s", s = 100, color=u'#ff7f0e', label="HCAL clusters") ax.scatter([],[], [], alpha=0.5, marker="x", s = 50, color="red", label="Truth particles") ax.set_zlabel(r"$y$ [a.u.]",labelpad=15) ax.set_ylabel(r"$x$ [a.u.]",labelpad=15) ax.set_xlabel(r"$z$ [a.u.]",labelpad=15) from matplotlib.ticker import MultipleLocator, AutoMinorLocator ax.xaxis.set_major_locator(MultipleLocator(50)) ax.yaxis.set_major_locator(MultipleLocator(1)) ax.zaxis.set_major_locator(MultipleLocator(1)) ax.xaxis.set_minor_locator(MultipleLocator(50)) ax.yaxis.set_minor_locator(MultipleLocator(0.5)) ax.zaxis.set_minor_locator(MultipleLocator(0.5)) ax.xaxis._axinfo["grid"].update({"linewidth":0.2, "color" : "gray", "which":"major", "linestyle":"--","alpha":0.1}) ax.yaxis._axinfo["grid"].update({"linewidth":0.2, "color" : "gray", "which":"major", "linestyle":"--","alpha":0.1}) ax.zaxis._axinfo["grid"].update({"linewidth":0.2, "color" : "gray", "which":"major", "linestyle":"--","alpha":0.1}) ax.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 1.0)) ax.w_yaxis.set_pane_color((1.0, 1.0, 1.0, 1.0)) ax.w_zaxis.set_pane_color((1.0, 1.0, 1.0, 1.0)) ax.set_xlim(-125, 125) legend = plt.legend(title =r"$t\overline{t}$, 14 TeV, 200 PU",frameon=False, bbox_to_anchor=(0.92, 1.0), loc='upper left',fontsize=20) plt.setp(legend.get_title(),fontsize=22) #plt.title("Simulated event with PU200") plt.savefig("plots/event_xyz.pdf", bbox_inches="tight") plt.savefig("plots/event_xyz.png", bbox_inches="tight", dpi=200) plt.show() fig = plt.figure(figsize=(8,8)) ax = fig.add_subplot(111) from matplotlib.collections import LineCollection lc = LineCollection(points_etaphi, linewidths=0.2, color="gray", alpha=0.5) ax.add_collection(lc) # just for better legend lc2 = LineCollection([], linewidths=2, color="gray", alpha=0.5, label="Tracks") ax.add_collection(lc2) ax.scatter(arr_ecal["eta"], np.arctan2(arr_ecal["sphi"],arr_ecal["cphi"]), s=0.1*arr_ecal["e"], color=u'#1f77b4', marker="s", alpha=0.5) ax.scatter(arr_hcal["eta"], np.arctan2(arr_hcal["sphi"],arr_hcal["cphi"]), s=0.1*arr_hcal["e"], color=u'#ff7f0e', marker="s", alpha=0.5) ax.scatter(arr_gen["eta"], np.arctan2(arr_gen["sphi"],arr_gen["cphi"]), alpha=0.2, marker="x", color="red") # just for better legend ax.scatter([],[], alpha=0.5, marker="s", s = 50, color=u'#1f77b4', label="ECAL clusters") ax.scatter([],[], alpha=0.5, marker="s", s = 100, color=u'#ff7f0e', label="HCAL clusters") ax.scatter([],[], alpha=0.5, marker="x", s = 50, color="red", label="Truth particles") ax.set_ylabel(r"$\phi$") ax.set_xlabel(r"$\eta$") ax.set_ylim(-np.pi, np.pi) ax.set_xlim(-5, 5) ax.grid(True) legend = plt.legend(title =r"$t\overline{t}$, 14 TeV, 200 PU",frameon=False, bbox_to_anchor=(0.98, 1.0), loc='upper left',fontsize=20) plt.setp(legend.get_title(),fontsize=22) #plt.title("Simulated event with PU200") plt.savefig("plots/event_etaphi.pdf", bbox_inches="tight") plt.savefig("plots/event_etaphi.png", bbox_inches="tight", dpi=200) plt.show() ``` # Analysis of predictions Once the training is done, we can generate the pred.npz file using the following: ```bash singularity exec --nv ~/HEP-KBFI/singularity/base.simg python3 mlpf/pipeline.py evaluate -c parameters/delphes.yaml -t experiments/delphes_20210821_160504.joosep-desktop -e experiments/delphes_20210821_160504.joosep-desktop/evaluation_ttbar -v "data/pythia8_ttbar/val/tev14_pythia8_ttbar_*.pkl.bz2" singularity exec --nv ~/HEP-KBFI/singularity/base.simg python3 mlpf/pipeline.py evaluate -c parameters/delphes.yaml -t experiments/delphes_20210821_160504.joosep-desktop -e experiments/delphes_20210821_160504.joosep-desktop/evaluation_qcd -v "data/pythia8_qcd/val/tev14_pythia8_qcd_*.pkl.bz2" ``` ``` def load_many_preds(path): Xs = [] ygens = [] ycands = [] ypreds = [] for fi in glob.glob(path): dd = np.load(fi) Xs.append(dd["X"]) ygens.append(dd["ygen"]) ycands.append(dd["ycand"]) ypreds.append(dd["ypred"]) X = np.concatenate(Xs) msk_X = X[:, :, 0]!=0 ygen = np.concatenate(ygens) ycand = np.concatenate(ycands) ypred = np.concatenate(ypreds) return X, ygen, ycand, ypred # For current model # X_ttbar, ygen_ttbar, ycand_ttbar, ypred_ttbar = load_many_preds("../experiments/delphes_20210821_160504.joosep-desktop/evaluation_ttbar/*.npz") # X, ygen, ycand, ypred = load_many_preds("../experiments/delphes_20210821_160504.joosep-desktop/evaluation_qcd/*.npz") # For the model from the paper #Load the predictions file from the model (this can take a while, as the file is compressed and pretty large) fi_qcd = np.load(open("pred_qcd.npz", "rb")) fi_ttbar = np.load(open("pred_ttbar.npz", "rb")) ygen = fi_qcd["ygen"] ycand = fi_qcd["ycand"] ypred = fi_qcd["ypred"] X = fi_qcd["X"] ygen_ttbar = fi_ttbar["ygen"] ycand_ttbar = fi_ttbar["ycand"] ypred_ttbar = fi_ttbar["ypred"] X_ttbar = fi_ttbar["X"] def flatten(arr): return arr.reshape((arr.shape[0]*arr.shape[1], arr.shape[2])) #Flatten the events ygen_f = flatten(ygen) ycand_f = flatten(ycand) ypred_f = flatten(ypred) X_f = flatten(X) msk_X_f = X_f[:, 0] != 0 #Flatten the events ygen_ttbar_f = flatten(ygen_ttbar) ycand_ttbar_f = flatten(ycand_ttbar) ypred_ttbar_f = flatten(ypred_ttbar) X_ttbar_f = flatten(X_ttbar) msk_X_ttbar_f = X_ttbar_f[:, 0] != 0 print(ygen_f.shape) print(ycand_f.shape) print(ypred_f.shape) print(ygen_ttbar_f.shape) print(ycand_ttbar_f.shape) print(ypred_ttbar_f.shape) def plot_pt_eta(ygen, legend_title=""): b = np.linspace(0, 100, 41) msk_pid1 = (ygen_f[:, 0]==1) msk_pid2 = (ygen_f[:, 0]==2) msk_pid3 = (ygen_f[:, 0]==3) msk_pid4 = (ygen_f[:, 0]==4) msk_pid5 = (ygen_f[:, 0]==5) h1 = np.histogram(ygen_f[msk_pid1, 2], bins=b) h2 = np.histogram(ygen_f[msk_pid2, 2], bins=b) h3 = np.histogram(ygen_f[msk_pid3, 2], bins=b) h4 = np.histogram(ygen_f[msk_pid4, 2], bins=b) h5 = np.histogram(ygen_f[msk_pid5, 2], bins=b) fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 2*8)) xs = midpoints(h1[1]) width = np.diff(h1[1]) hep.histplot([h5[0], h4[0], h3[0], h2[0], h1[0]], bins=h1[1], ax=ax1, stack=True, histtype="fill", label=["Muons", "Electrons", "Photons", "Neutral hadrons", "Charged hadrons"]) ax1.legend(loc="best", frameon=False, title=legend_title) ax1.set_yscale("log") ax1.set_ylim(1e1, 1e9) ax1.set_xlabel(r"Truth particle $p_\mathrm{T}$ [GeV]") ax1.set_ylabel("Truth particles") b = np.linspace(-8, 8, 41) h1 = np.histogram(ygen_f[msk_pid1, 3], bins=b) h2 = np.histogram(ygen_f[msk_pid2, 3], bins=b) h3 = np.histogram(ygen_f[msk_pid3, 3], bins=b) h4 = np.histogram(ygen_f[msk_pid4, 3], bins=b) h5 = np.histogram(ygen_f[msk_pid5, 3], bins=b) xs = midpoints(h1[1]) width = np.diff(h1[1]) hep.histplot([h5[0], h4[0], h3[0], h2[0], h1[0]], bins=h1[1], ax=ax2, stack=True, histtype="fill", label=["Muons", "Electrons", "Photons", "Neutral hadrons", "Charged hadrons"]) leg = ax2.legend(loc="best", frameon=False, ncol=2, title=legend_title) leg._legend_box.align = "left" ax2.set_yscale("log") ax2.set_ylim(1e1, 1e9) ax2.set_xlabel("Truth particle $\eta$") ax2.set_ylabel("Truth particles") return ax1, ax2 ax, _ = plot_pt_eta(ygen, legend_title=sample_title_qcd) #sample_string_qcd(ax, x=0.0) plt.savefig("plots/gen_pt_eta.pdf", bbox_inches="tight") PDF("plots/gen_pt_eta.pdf",size=(300,400)) ax, _ = plot_pt_eta(ygen_ttbar, legend_title=sample_title_ttbar) #sample_string_ttbar(ax) plt.savefig("plots/gen_pt_eta_ttbar.pdf", bbox_inches="tight") PDF("plots/gen_pt_eta_ttbar.pdf",size=(300,400)) ranges = { "pt": np.linspace(0, 10, 61), "eta": np.linspace(-5, 5, 61), "sphi": np.linspace(-1, 1, 61), "cphi": np.linspace(-1, 1, 61), "energy": np.linspace(0, 100, 61) } pid_names = { 1: "Charged hadrons", 2: "Neutral hadrons", 3: "Photons", 4: "Electrons", 5: "Muons", } var_names = { "pt": r"$p_\mathrm{T}$ [GeV]", "eta": r"$\eta$", "sphi": r"$\mathrm{sin} \phi$", "cphi": r"$\mathrm{cos} \phi$", "energy": r"$E$ [GeV]" } var_names_nounit = { "pt": r"$p_\mathrm{T}$", "eta": r"$\eta$", "sphi": r"$\mathrm{sin} \phi$", "cphi": r"$\mathrm{cos} \phi$", "energy": r"$E$" } var_names_bare = { "pt": "p_\mathrm{T}", "eta": "\eta", "energy": "E", } var_indices = { "pt": 2, "eta": 3, "sphi": 4, "cphi": 5, "energy": 6 } ``` ### Number of particles ``` def plot_num_particles_pid(ygen, ycand, ypred, pid=0, ax=None, legend_title=""): if not ax: plt.figure(figsize=(4,4)) ax = plt.axes() #compute the number of particles per event if pid == 0: x1 = np.sum(ygen[:, :, 0]!=pid, axis=1) x2 = np.sum(ypred[:, :, 0]!=pid, axis=1) x3 = np.sum(ycand[:, :, 0]!=pid, axis=1) else: x1 = np.sum(ygen[:, :, 0]==pid, axis=1) x2 = np.sum(ypred[:, :, 0]==pid, axis=1) x3 = np.sum(ycand[:, :, 0]==pid, axis=1) v0 = np.min([np.min(x1), np.min(x2), np.min(x3)]) v1 = np.max([np.max(x1), np.max(x2), np.max(x3)]) #draw only a random sample of the events to avoid overcrowding inds = np.random.permutation(len(x1))[:1000] ratio_dpf = (x3[inds] - x1[inds]) / x1[inds] ratio_dpf[ratio_dpf > 10] = 10 ratio_dpf[ratio_dpf < -10] = -10 mu_dpf = np.mean(ratio_dpf) sigma_dpf = np.std(ratio_dpf) ax.scatter( x1[inds], x3[inds], marker="o", label="Rule-based PF, $r={0:.3f}$\n$\mu={1:.3f}\\ \sigma={2:.3f}$".format( np.corrcoef(x1, x3)[0,1], mu_dpf, sigma_dpf ), alpha=0.5 ) ratio_mlpf = (x2[inds] - x1[inds]) / x1[inds] ratio_mlpf[ratio_mlpf > 10] = 10 ratio_mlpf[ratio_mlpf < -10] = -10 mu_mlpf = np.mean(ratio_mlpf) sigma_mlpf = np.std(ratio_mlpf) ax.scatter( x1[inds], x2[inds], marker="^", label="MLPF, $r={0:.3f}$\n$\mu={1:.3f}\\ \sigma={2:.3f}$".format( np.corrcoef(x1, x2)[0,1], mu_mlpf, sigma_mlpf ), alpha=0.5 ) leg = ax.legend(loc="best", frameon=False, title=legend_title+pid_names[pid] if pid>0 else "all particles") for lh in leg.legendHandles: lh.set_alpha(1) ax.plot([v0, v1], [v0, v1], color="black", ls="--") #ax.set_title(pid_names[pid]) ax.set_xlabel("Truth particles / event") ax.set_ylabel("Reconstructed particles / event") #plt.title("Particle multiplicity, {}".format(pid_names[pid])) #plt.savefig("plots/num_particles_pid{}.pdf".format(pid), bbox_inches="tight") return {"sigma_dpf": sigma_dpf, "sigma_mlpf": sigma_mlpf, "ratio_mlpf": ratio_mlpf, "ratio_dpf": ratio_dpf, "x1": x1, "x2": x2, "x3": x3} fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 2*8)) ret_num_particles_ch_had = plot_num_particles_pid(ygen, ycand, ypred, 1, ax1, legend_title=sample_title_qcd+"\n") ret_num_particles_n_had = plot_num_particles_pid(ygen, ycand, ypred, 2, ax2, legend_title=sample_title_qcd+"\n") #sample_string_qcd(ax1) plt.tight_layout() plt.savefig("plots/num_particles.pdf", bbox_inches="tight") plt.savefig("plots/num_particles.png", bbox_inches="tight", dpi=200) PDF("plots/num_particles.pdf",size=(300,400)) fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 2*8)) ret_num_particles_ch_had_ttbar = plot_num_particles_pid(ygen_ttbar, ycand_ttbar, ypred_ttbar, 1, ax1) ret_num_particles_n_had_ttbar = plot_num_particles_pid(ygen_ttbar, ycand_ttbar, ypred_ttbar, 2, ax2) sample_string_ttbar(ax1) plt.tight_layout() plt.savefig("plots/num_particles_ttbar.pdf", bbox_inches="tight") PDF("plots/num_particles_ttbar.pdf",size=(300,400)) plt.scatter( ret_num_particles_n_had["x1"], ret_num_particles_n_had["x2"], color="red", alpha=0.2 ) plt.scatter( ret_num_particles_n_had_ttbar["x1"], ret_num_particles_n_had_ttbar["x2"], color="blue", alpha=0.2 ) ``` ## Fake rate plots ``` def draw_efficiency_fakerate(ygen, ypred, ycand, pid, var, bins, both=True, legend_title=""): var_idx = var_indices[var] msk_gen = ygen_f[:, 0]==pid msk_pred = ypred_f[:, 0]==pid msk_cand = ycand_f[:, 0]==pid hist_gen = np.histogram(ygen_f[msk_gen, var_idx], bins=bins); hist_cand = np.histogram(ygen_f[msk_gen & msk_cand, var_idx], bins=bins); hist_pred = np.histogram(ygen_f[msk_gen & msk_pred, var_idx], bins=bins); hist_gen = mask_empty(hist_gen) hist_cand = mask_empty(hist_cand) hist_pred = mask_empty(hist_pred) #efficiency plot if both: fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 2*8)) else: fig, ax1 = plt.subplots(1, 1, figsize=(8, 1*8)) ax2 = None #ax1.set_title("reco efficiency for {}".format(pid_names[pid])) ax1.errorbar( midpoints(hist_gen[1]), divide_zero(hist_cand[0], hist_gen[0]), divide_zero(np.sqrt(hist_gen[0]), hist_gen[0]) * divide_zero(hist_cand[0], hist_gen[0]), lw=0, label="Rule-based PF", elinewidth=2, marker=".",markersize=10) ax1.errorbar( midpoints(hist_gen[1]), divide_zero(hist_pred[0], hist_gen[0]), divide_zero(np.sqrt(hist_gen[0]), hist_gen[0]) * divide_zero(hist_pred[0], hist_gen[0]), lw=0, label="MLPF", elinewidth=2, marker=".",markersize=10) ax1.legend(frameon=False, loc=0, title=legend_title+pid_names[pid]) ax1.set_ylim(0,1.2) ax1.set_xlabel(var_names[var]) ax1.set_ylabel("Efficiency") hist_cand2 = np.histogram(ygen_f[msk_cand & (ygen_f[:, 0]!=0), var_idx], bins=bins); hist_pred2 = np.histogram(ygen_f[msk_pred & (ygen_f[:, 0]!=0), var_idx], bins=bins); hist_cand_gen2 = np.histogram(ygen_f[msk_cand & ~msk_gen & (ygen_f[:, 0]!=0), var_idx], bins=bins); hist_pred_gen2 = np.histogram(ygen_f[msk_pred & ~msk_gen & (ygen_f[:, 0]!=0), var_idx], bins=bins); hist_cand2 = mask_empty(hist_cand2) hist_cand_gen2 = mask_empty(hist_cand_gen2) hist_pred2 = mask_empty(hist_pred2) hist_pred_gen2 = mask_empty(hist_pred_gen2) if both: #fake rate plot #ax2.set_title("reco fake rate for {}".format(pid_names[pid])) ax2.errorbar( midpoints(hist_cand2[1]), divide_zero(hist_cand_gen2[0], hist_cand2[0]), divide_zero(np.sqrt(hist_cand_gen2[0]), hist_cand2[0]), lw=0, label="Rule-based PF", elinewidth=2, marker=".",markersize=10) ax2.errorbar( midpoints(hist_pred2[1]), divide_zero(hist_pred_gen2[0], hist_pred2[0]), divide_zero(np.sqrt(hist_pred_gen2[0]), hist_pred2[0]), lw=0, label="MLPF", elinewidth=2, marker=".",markersize=10) ax2.legend(frameon=False, loc=0, title=legend_title+pid_names[pid]) ax2.set_ylim(0, 1.0) #plt.yscale("log") ax2.set_xlabel(var_names[var]) ax2.set_ylabel("Fake rate") return ax1, ax2 pid = 1 var_idx = var_indices["eta"] bins = np.linspace(-5, 5, 100) def get_eff(ygen, ypred, ycand): msk_gen = (ygen[:, 0]==pid) & (ygen[:, var_indices["pt"]]>5.0) msk_pred = ypred[:, 0]==pid msk_cand = ycand[:, 0]==pid hist_gen = np.histogram(ygen[msk_gen, var_idx], bins=bins); hist_cand = np.histogram(ygen[msk_gen & msk_cand, var_idx], bins=bins); hist_pred = np.histogram(ygen[msk_gen & msk_pred, var_idx], bins=bins); hist_gen = mask_empty(hist_gen) hist_cand = mask_empty(hist_cand) hist_pred = mask_empty(hist_pred) return { "x": midpoints(hist_gen[1]), "y": divide_zero(hist_pred[0], hist_gen[0]), "yerr": divide_zero(np.sqrt(hist_gen[0]), hist_gen[0]) * divide_zero(hist_pred[0], hist_gen[0]) } def get_fake(ygen, ypred, ycand): msk_gen = ygen[:, 0]==pid msk_pred = ypred[:, 0]==pid msk_cand = ycand[:, 0]==pid hist_cand2 = np.histogram(ygen[msk_cand & (ygen[:, 0]!=0), var_idx], bins=bins); hist_pred2 = np.histogram(ygen[msk_pred & (ygen[:, 0]!=0), var_idx], bins=bins); hist_cand_gen2 = np.histogram(ygen[msk_cand & ~msk_gen & (ygen[:, 0]!=0), var_idx], bins=bins); hist_pred_gen2 = np.histogram(ygen[msk_pred & ~msk_gen & (ygen[:, 0]!=0), var_idx], bins=bins); hist_cand2 = mask_empty(hist_cand2) hist_cand_gen2 = mask_empty(hist_cand_gen2) hist_pred2 = mask_empty(hist_pred2) hist_pred_gen2 = mask_empty(hist_pred_gen2) return { "x": midpoints(hist_pred2[1]), "y": divide_zero(hist_pred_gen2[0], hist_pred2[0]), "yerr": divide_zero(np.sqrt(hist_pred_gen2[0]), hist_pred2[0]) } ax, _ = draw_efficiency_fakerate(ygen_f, ypred_f, ycand_f, 1, "pt", np.linspace(0, 3, 61), both=False, legend_title=sample_title_qcd+"\n") #sample_string_qcd(ax) plt.savefig("plots/eff_fake_pid1_pt.pdf", bbox_inches="tight") PDF("plots/eff_fake_pid1_pt.pdf", size=(300,300)) ax, _ = draw_efficiency_fakerate(ygen_f, ypred_f, ycand_f, 1, "eta", np.linspace(-3, 3, 61), both=False, legend_title=sample_title_qcd+"\n") #sample_string_qcd(ax) plt.savefig("plots/eff_fake_pid1_eta.pdf", bbox_inches="tight") PDF("plots/eff_fake_pid1_eta.pdf", size=(300,300)) ax, _ = draw_efficiency_fakerate( ygen_f, ypred_f, ycand_f, 2, "energy", np.linspace(5, 205, 61), legend_title=sample_title_qcd+"\n") #sample_string_qcd(ax) plt.savefig("plots/eff_fake_pid2_energy.pdf", bbox_inches="tight") PDF("plots/eff_fake_pid2_energy.pdf", size=(300,600)) ax, _ = draw_efficiency_fakerate( ygen_ttbar_f, ypred_ttbar_f, ycand_ttbar_f, 2, "energy", np.linspace(5, 205, 61), legend_title=sample_title_ttbar+"\n") #sample_string_ttbar(ax) plt.savefig("plots/eff_fake_pid2_energy_ttbar.pdf", bbox_inches="tight") PDF("plots/eff_fake_pid2_energy_ttbar.pdf", size=(300,600)) ax, _ = draw_efficiency_fakerate( ygen_f, ypred_f, ycand_f, 2, "eta", np.linspace(-6, 6, 61), legend_title=sample_title_qcd+"\n" ) #sample_string_qcd(ax) plt.savefig("plots/eff_fake_pid2_eta.pdf", bbox_inches="tight") PDF("plots/eff_fake_pid2_eta.pdf", size=(300,600)) ax, _ = draw_efficiency_fakerate( ygen_f, ypred_f, ycand_f, 3, "eta", np.linspace(-6, 6, 61), legend_title=sample_title_qcd+"\n" ) #sample_string_qcd(ax) plt.savefig("plots/eff_fake_pid3_eta.pdf", bbox_inches="tight") PDF("plots/eff_fake_pid3_eta.pdf", size=(300,600)) ax, _ = draw_efficiency_fakerate( ygen_f, ypred_f, ycand_f, 4, "eta", np.linspace(-6, 6, 61), legend_title=sample_title_qcd+"\n" ) #sample_string_qcd(ax) plt.savefig("plots/eff_fake_pid4_eta.pdf", bbox_inches="tight") PDF("plots/eff_fake_pid4_eta.pdf", size=(300,600)) ax, _ = draw_efficiency_fakerate( ygen_f, ypred_f, ycand_f, 5, "eta", np.linspace(-6, 6, 61), legend_title=sample_title_qcd+"\n" ) #sample_string_qcd(ax) plt.savefig("plots/eff_fake_pid5_eta.pdf", bbox_inches="tight") PDF("plots/eff_fake_pid5_eta.pdf", size=(300,600)) ``` ## Resolution plots ``` def plot_reso(ygen, ypred, ycand, pid, var, rng, ax=None, legend_title=""): var_idx = var_indices[var] msk = (ygen[:, 0]==pid) & (ypred[:, 0]==pid) & (ycand[:, 0]==pid) bins = np.linspace(-rng, rng, 100) yg = ygen[msk, var_idx] yp = ypred[msk, var_idx] yc = ycand[msk, var_idx] ratio_mlpf = (yp - yg) / yg ratio_dpf = (yc - yg) / yg #remove outliers for std value computation outlier = 10 ratio_mlpf[ratio_mlpf<-outlier] = -outlier ratio_mlpf[ratio_mlpf>outlier] = outlier ratio_dpf[ratio_dpf<-outlier] = -outlier ratio_dpf[ratio_dpf>outlier] = outlier res_dpf = np.mean(ratio_dpf), np.std(ratio_dpf) res_mlpf = np.mean(ratio_mlpf), np.std(ratio_mlpf) if ax is None: plt.figure(figsize=(4, 4)) ax = plt.axes() #plt.title("{} resolution for {}".format(var_names_nounit[var], pid_names[pid])) ax.hist(ratio_dpf, bins=bins, histtype="step", lw=2, label="Rule-based PF\n$\mu={:.2f},\\ \sigma={:.2f}$".format(*res_dpf)); ax.hist(ratio_mlpf, bins=bins, histtype="step", lw=2, label="MLPF\n$\mu={:.2f},\\ \sigma={:.2f}$".format(*res_mlpf)); ax.legend(frameon=False, title=legend_title+pid_names[pid]) ax.set_xlabel("{nounit} resolution, $({bare}^\prime - {bare})/{bare}$".format(nounit=var_names_nounit[var],bare=var_names_bare[var])) ax.set_ylabel("Particles") #plt.ylim(0, ax.get_ylim()[1]*2) ax.set_ylim(1, 1e10) ax.set_yscale("log") return {"dpf": res_dpf, "mlpf": res_mlpf} fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 2*8)) res_ch_had_pt = plot_reso(ygen_f, ypred_f, ycand_f, 1, "pt", 2, ax=ax1, legend_title=sample_title_qcd+"\n") res_ch_had_eta = plot_reso(ygen_f, ypred_f, ycand_f, 1, "eta", 0.2, ax=ax2, legend_title=sample_title_qcd+"\n") ax1.set_ylim(100, 10**11) ax2.set_ylim(100, 10**11) #sample_string_qcd(ax1) plt.tight_layout() plt.savefig("plots/res_pid1.pdf", bbox_inches="tight") PDF("plots/res_pid1.pdf", size=(300,600)) fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 2*8)) res_n_had_e = plot_reso(ygen_f, ypred_f, ycand_f, 2, "energy", 5, ax=ax1, legend_title=sample_title_qcd+"\n") res_n_had_eta = plot_reso(ygen_f, ypred_f, ycand_f, 2, "eta", 0.5, ax=ax2, legend_title=sample_title_qcd+"\n") #ax1.set_title("Neutral hadrons") #sample_string_qcd(ax1) plt.tight_layout() plt.savefig("plots/res_pid2.pdf", bbox_inches="tight") plt.savefig("plots/res_pid2.png", bbox_inches="tight", dpi=200) PDF("plots/res_pid2.pdf", size=(300,600)) fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 2*8)) plot_reso(ygen_ttbar_f, ypred_ttbar_f, ycand_ttbar_f, 2, "energy", 5, ax=ax1, legend_title=sample_title_ttbar+"\n") plot_reso(ygen_ttbar_f, ypred_ttbar_f, ycand_ttbar_f, 2, "eta", 0.5, ax=ax2, legend_title=sample_title_ttbar+"\n") #ax1.set_title("Neutral hadrons") #sample_string_ttbar(ax1) plt.tight_layout() plt.savefig("plots/res_pid2_ttbar.pdf", bbox_inches="tight") PDF("plots/res_pid2_ttbar.pdf", size=(300,600)) ``` ## Confusion matrices ``` confusion = sklearn.metrics.confusion_matrix( ygen_f[msk_X, 0], ycand_f[msk_X, 0], normalize="true" ) confusion2 = sklearn.metrics.confusion_matrix( ygen_f[msk_X, 0], ypred_f[msk_X, 0], normalize="true" ) confusion_unnorm = sklearn.metrics.confusion_matrix( ygen_f[msk_X, 0], ycand_f[msk_X, 0], ) confusion2_unnorm = sklearn.metrics.confusion_matrix( ygen_f[msk_X, 0], ypred_f[msk_X, 0], ) np.round(confusion, 2) np.round(confusion2, 2) sklearn.metrics.accuracy_score(ygen_f[msk_X, 0], ycand_f[msk_X, 0]) sklearn.metrics.accuracy_score(ygen_f[msk_X, 0], ypred_f[msk_X, 0]) def plot_confusion_matrix(cm, target_names, title='Confusion matrix', cmap=None, normalize=True, ax=None): """ Citiation --------- http://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html """ import matplotlib.pyplot as plt import numpy as np import itertools accuracy = np.trace(cm) / float(np.sum(cm)) misclass = 1 - accuracy if cmap is None: cmap = plt.get_cmap('Blues') if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] cm[np.isnan(cm)] = 0.0 if not ax: fig = plt.figure(figsize=(5, 4)) ax = plt.axes() ax.imshow(cm, interpolation='nearest', cmap=cmap) #ax.colorbar() if target_names is not None: tick_marks = np.arange(len(target_names)) ax.set_xticks(tick_marks) ax.set_xticklabels(target_names, rotation=45) ax.set_yticks(tick_marks) ax.set_yticklabels(target_names, rotation=45) thresh = cm.max() / 1.5 if normalize else cm.max() / 2 for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): if normalize: ax.text(j, i, "{:0.2f}".format(cm[i, j]), horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") else: ax.text(j, i, "{:,}".format(cm[i, j]), horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") ax.set_ylabel('True PID') ax.set_xlabel('Reconstructed PID') ax.set_xlim(-1, len(target_names)) ax.set_ylim(-1, len(target_names)) #ax.set_xlabel('Predicted label\naccuracy={:0.4f}; misclass={:0.4f}'.format(accuracy, misclass)) return fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 2*8)) plot_confusion_matrix(confusion, ["None", "Ch. had", "N. had", "$\gamma$", r"$e^\pm$", r"$\mu^\pm$"], ax=ax1) plot_confusion_matrix(confusion2, ["None", "Ch. had", "N. had", "$\gamma$", r"$e^\pm$", r"$\mu^\pm$"], ax=ax2) ax1.set_xlabel("") ax1.set_title(sample_title_qcd + "\nRule-based PF") ax2.set_title(sample_title_qcd + ", MLPF") #sample_string_qcd(ax1) #ax1.text(0.03, 0.97, "Rule-based PF", ha="left", va="top", transform=ax1.transAxes) #ax2.text(0.03, 0.97, "MLPF", ha="left", va="top", transform=ax2.transAxes) plt.tight_layout() plt.savefig("plots/confusion_normed.pdf", bbox_inches="tight") PDF("plots/confusion_normed.pdf", size=(300,600)) b = np.linspace(0, 200, 61) fig, axes = plt.subplots(2, 3, figsize=(3*8, 2*8)) axes = axes.flatten() for iax, i in enumerate([1,2,3,4,5]): axes[iax].hist(ypred_f[ypred_f[:, 0]==i, 2], bins=b, histtype="step", lw=2, color="red", label="QCD MLPF"); axes[iax].hist(ygen_f[ygen_f[:, 0]==i, 2], bins=b, histtype="step", lw=1, color="red", ls="--", label="QCD truth"); #axes[iax].hist(ycand[ycand[:, 0]==i, 2], bins=b, histtype="step", lw=1, color="pink", ls="-", label="QCD PF"); axes[iax].hist(ypred_ttbar_f[ypred_ttbar_f[:, 0]==i, 2], bins=b, histtype="step", lw=2, color="blue", label=r"$t\bar{t}$ MLPF"); axes[iax].hist(ygen_ttbar_f[ygen_ttbar_f[:, 0]==i, 2], bins=b, histtype="step", lw=1, color="blue", ls="--", label=r"$t\bar{t}$ truth"); #axes[iax].hist(ycand_ttbar[ycand_ttbar[:, 0]==i, 2], bins=b, histtype="step", lw=1, color="cyan", ls="-", label=r"$t\bar{t}$ PF"); axes[iax].set_yscale("log") axes[iax].legend(ncol=2) axes[iax].set_xlabel(var_names["pt"]) axes[iax].set_ylabel("Number of particles") axes[iax].set_title(pid_names[i]) fig.delaxes(axes[-1]) plt.tight_layout() plt.savefig("plots/qcd_vs_ttbar.pdf", bbox_inches="tight") PDF("plots/qcd_vs_ttbar.pdf", size=(1200, 600)) b = np.linspace(0, 2500, 61) fig, axes = plt.subplots(2, 3, figsize=(3*8, 2*8)) axes = axes.flatten() for iax, i in enumerate([1,2,3,4,5]): axes[iax].hist(ypred_f[ypred_f[:, 0]==i, 6], bins=b, histtype="step", lw=2, color="red", label="QCD MLPF"); axes[iax].hist(ygen_f[ygen_f[:, 0]==i, 6], bins=b, histtype="step", lw=1, color="red", ls="--", label="QCD truth"); #axes[iax].hist(ycand[ycand[:, 0]==i, 6], bins=b, histtype="step", lw=1, color="pink", ls="-", label="QCD PF"); axes[iax].hist(ypred_ttbar_f[ypred_ttbar_f[:, 0]==i, 6], bins=b, histtype="step", lw=2, color="blue", label=r"$t\bar{t}$ MLPF"); axes[iax].hist(ygen_ttbar_f[ygen_ttbar_f[:, 0]==i, 6], bins=b, histtype="step", lw=1, color="blue", ls="--", label=r"$t\bar{t}$ truth"); #axes[iax].hist(ycand_ttbar[ycand_ttbar[:, 0]==i, 6], bins=b, histtype="step", lw=1, color="cyan", ls="-", label=r"$t\bar{t}$ PF"); axes[iax].set_yscale("log") axes[iax].legend(ncol=2) axes[iax].set_xlabel("E [GeV]") axes[iax].set_ylabel("Number of particles") axes[iax].set_title(pid_names[i]) fig.delaxes(axes[-1]) plt.tight_layout() plt.savefig("plots/qcd_vs_ttbar_e.pdf", bbox_inches="tight") PDF("plots/qcd_vs_ttbar_e.pdf", size=(600,300)) ``` ### Results table ``` metrics_delphes = { "ch_had_eff": confusion_unnorm[1, 1] / np.sum(confusion_unnorm[1, :]), "n_had_eff": confusion_unnorm[2, 2] / np.sum(confusion_unnorm[2, :]), "ch_had_fake": 1.0 - confusion_unnorm[1, 1] / np.sum(confusion_unnorm[:, 1]), "n_had_fake": 1.0 - confusion_unnorm[2, 2] / np.sum(confusion_unnorm[:, 2]), "res_ch_had_eta_s": res_ch_had_eta["dpf"][1], "res_ch_had_pt_s": res_ch_had_pt["dpf"][1], "res_n_had_eta_s": res_n_had_eta["dpf"][1], "res_n_had_e_s": res_n_had_e["dpf"][1], "num_ch_had_sigma": ret_num_particles_ch_had["sigma_dpf"], "num_n_had_sigma": ret_num_particles_n_had["sigma_dpf"], } metrics_mlpf = { "ch_had_eff": confusion2_unnorm[1, 1] / np.sum(confusion2_unnorm[1, :]), "n_had_eff": confusion2_unnorm[2, 2] / np.sum(confusion2_unnorm[2, :]), "ch_had_fake": 1.0 - confusion2_unnorm[1, 1] / np.sum(confusion2_unnorm[:, 1]), "n_had_fake": 1.0 - confusion2_unnorm[2, 2] / np.sum(confusion2_unnorm[:, 2]), "res_ch_had_eta_s": res_ch_had_eta["mlpf"][1], "res_ch_had_pt_s": res_ch_had_pt["mlpf"][1], "res_n_had_eta_s": res_n_had_eta["mlpf"][1], "res_n_had_e_s": res_n_had_e["mlpf"][1], "num_ch_had_sigma": ret_num_particles_ch_had["sigma_mlpf"], "num_n_had_sigma": ret_num_particles_n_had["sigma_mlpf"], } metrics_delphes metrics_mlpf names = [ "Efficiency", "Fake rate", r"$p_\mathrm{T}$ ($E$) resolution", r"$\eta$ resolution", r"particle multiplicity resolution" ] for n, ks in zip(names, [ ("ch_had_eff", "n_had_eff"), ("ch_had_fake", "n_had_fake"), ("res_ch_had_pt_s", "res_n_had_e_s"), ("res_ch_had_eta_s", "res_n_had_eta_s"), ("num_ch_had_sigma", "num_n_had_sigma") ]): k0 = ks[0] k1 = ks[1] print("{} & {:.3f} & {:.3f} & {:.3f} & {:.3f} \\\\".format( n, metrics_delphes[k0], metrics_mlpf[k0], metrics_delphes[k1], metrics_mlpf[k1])) msk_pid_gen = ygen_f[:, 0]==1 msk_pid_cand = ycand_f[:, 0]==1 msk_pid_pred = ypred_f[:, 0]==1 np.unique(ycand_f[(msk_pid_gen) & (~msk_pid_cand) & msk_pid_pred, 0], return_counts=True) np.sum((msk_pid_gen) & (~msk_pid_cand) & msk_pid_pred) np.sum((msk_pid_gen) & (msk_pid_cand) & msk_pid_pred) np.unique(X_f[(msk_pid_gen) & (~msk_pid_cand) & msk_pid_pred, 0], return_counts=True) plt.hist(X_f[(msk_pid_gen) & (~msk_pid_cand) & msk_pid_pred, 1], bins=np.linspace(0,5,100), density=True, histtype="step", label="MLPF charged hadron, RBPF no charged hadron"); plt.hist(X_f[(msk_pid_gen) & (msk_pid_cand) & msk_pid_pred, 1], bins=np.linspace(0,5,100), density=True, histtype="step", label="MLPF & RBPF charged hadron"); plt.legend() plt.xlabel("track pT") plt.hist(X_f[(msk_pid_gen) & (~msk_pid_cand) & msk_pid_pred, 2], bins=np.linspace(-3,3,100), density=True, histtype="step"); plt.hist(X_f[(msk_pid_gen) & (msk_pid_cand) & msk_pid_pred, 2], bins=np.linspace(-3,3,100), density=True, histtype="step"); plt.xlabel("track eta") plt.hist(X_f[(msk_pid_gen) & (~msk_pid_cand) & msk_pid_pred, 5], bins=np.linspace(0, 10, 100), density=True, histtype="step"); plt.hist(X_f[(msk_pid_gen) & (msk_pid_cand) & msk_pid_pred, 5], bins=np.linspace(0, 10, 100), density=True, histtype="step"); plt.xlabel("track energy") a = X_f[(msk_pid_gen) & (msk_pid_cand) & msk_pid_pred, 2] b = ycand_f[(msk_pid_gen) & (msk_pid_cand) & msk_pid_pred, 3] plt.hist(a, bins=100); plt.hist(b, bins=100); plt.hist((a-b)/a, bins=np.linspace(-1,1,100)); ``` ## Scaling of the model inference time with synthetic data The scaling of the model timing is done using synthetic data with the following command: ```bash singularity exec --nv ~/HEP-KBFI/singularity/base.simg python3 ../mlpf/tensorflow/delphes_model.py --action timing --weights weights-300-*.hdf5 ``` ``` timing_data_d = json.load(open("synthetic_timing.json", "r")) timing_data_d = sum(timing_data_d, []) timing_data = pandas.DataFrame.from_records(timing_data_d) lines = timing_data[timing_data["batch_size"] == 1] times_b1 = lines.groupby("event_size").apply(lambda x: np.mean(x["time_per_event"])) lines = timing_data[timing_data["event_size"] == 128*50] times_ev1 = lines.groupby("batch_size").apply(lambda x: np.mean(x["time_per_event"])) lines = timing_data[timing_data["event_size"] == 128*20] times_ev2 = lines.groupby("batch_size").apply(lambda x: np.mean(x["time_per_event"])) lines = timing_data[timing_data["event_size"] == 128*10] times_ev3 = lines.groupby("batch_size").apply(lambda x: np.mean(x["time_per_event"])) fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 2*8)) bins = [128*10, 128*20, 128*30, 128*40, 128*50, 128*60, 128*70, 128*80, 128*90, 128*100] #ax1.axvline(128*50, color="black", ymin=0, ymax=0.39, lw=2,ls='--') #ax1.text(128*50*1.02, 10, r"$t\overline{t}$, 14 TeV, 200 PU") #ax1.axvline(128*50, color="black", ymin=0, ymax=0.39, lw=2,ls='--') #ax1.text(128*50*1.02, 10, r"$t\overline{t}$, 14 TeV, 200 PU") ax1.plot([128*10], [times_b1.values[0]], marker="v", alpha=0.5, lw=0, ms=20, label="40 PU") ax1.plot([128*20], [times_b1.values[1]], marker="^", alpha=0.5, lw=0, ms=20, label="80 PU") ax1.plot([128*50], [times_b1.values[4]], marker="o", alpha=0.5, lw=0, ms=20, label="200 PU") ax1.plot(times_b1.keys(), times_b1.values, marker="o", label="MLPF scaling",lw=2,markersize=10, color="black") ax1.set_ylim(0,120) ax1.set_xlim(0,15000) #plt.xlim(0,25000) ax1.set_xlabel("Average event size [elements]") ax1.set_ylabel("Average runtime / event [ms]") leg = ax1.legend(loc="best", frameon=False, title="$t\\bar{t}$, 14 TeV") leg._legend_box.align = "left" ax2.plot(times_ev3.keys(), times_ev3.values / times_ev3.values[0], marker="v", label="40 PU",lw=2,markersize=10) ax2.plot(times_ev2.keys(), times_ev2.values / times_ev2.values[0], marker="^", label="80 PU",lw=2,markersize=10) ax2.plot(times_ev1.keys(), times_ev1.values / times_ev1.values[0], marker="o", label="200 PU",lw=2,markersize=10) ax2.set_xticks([1, 2, 3, 4]) ax2.set_xlabel("Batch size [events]") ax2.set_ylabel("Relative inference time [a.u.]") ax2.legend(loc=0, frameon=False) plt.savefig("plots/inference_time.pdf", bbox_inches="tight") PDF("plots/inference_time.pdf", size=(300,600)) ```
github_jupyter
### Description This notebook loads the data csv file and plots Figures 3 (right panel) and A4. Minor post-processing was done after the fact to compile and format the figures. ``` import os import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline csv_file = "data/deep-nonlinear.csv" df = pd.read_csv(csv_file).set_index("id") metric = "validation-1/loss" names = ["single_task", "main_train_pts", "nlayers", "s_a", "train_seed"] new_index = pd.MultiIndex.from_tuples([tuple(x) for x in df[names].values], names=names) df_single = df[metric].set_axis(new_index, axis=0, inplace=False).sort_index()[True] names = ["single_task", "main_train_pts", "nlayers", "s_a", "s_b", "relatedness", "train_seed"] new_index = pd.MultiIndex.from_tuples([tuple(x) for x in df[names].values], names=names) df_multi = df[metric].set_axis(new_index, axis=0, inplace=False).sort_index()[False] def benefit_generalized(df1, df2): df = df1.sub(df2, axis="index") return pd.DataFrame(df).T.reorder_levels(df2.index.names, axis=1).sort_index(axis=1) ntrain = 800 tmp = benefit_generalized(df_single, df_multi)[ntrain] data = tmp.stack().droplevel(0) n = len(data) mean = data.mean().unstack(2).T err = data.std().unstack(2).T / n ** .5 ncolors = len(mean.columns.levels[2]) cmap = plt.cm.cividis(np.linspace(0, 1, ncolors))[:, :3] fig, axs = plt.subplots(len(mean.columns.levels[0]), len(mean.columns.levels[1])) a = len(mean.columns.levels[0]) / len(mean.columns.levels[1]) #fig.set_size_inches([5.5, 5.5 * a]) miny = np.round((mean - err).values.min(), 2) miny = -.1 if miny >= -.1 else miny maxy = np.round((mean + err).values.max(), 2) minx = mean.index.values.min() maxx = mean.index.values.max() maxx = int(maxx) if maxx > 1 else maxx for nn, nlayers in enumerate(mean.columns.levels[0]): for ii, s1 in enumerate(mean.columns.levels[1]): ax = axs[nn, ii] for jj, re in enumerate(mean.columns.levels[2]): ax.plot(mean.index.values, mean[nlayers][s1][re], color=cmap[jj], label="{:1.2f}".format(re), solid_capstyle="butt") ax.fill_between(mean.index.values, mean[nlayers][s1][re] - err[nlayers][s1][re], mean[nlayers][s1][re] + err[nlayers][s1][re], color=cmap[jj], alpha=0.5, edgecolor="none", lw=0) ax.plot(mean.index.values, np.zeros_like(mean.index.values), color='k', linestyle='--', linewidth=1) for key, sp in ax.spines.items(): if key in ("top", "right"): sp.set_visible(False) if ii > 0 and key == "left": sp.set_visible(False) ax.set_xlim([minx, maxx]) ax.set_xscale('log') ax.xaxis.set_ticks([minx, maxx]) ax.xaxis.set_ticklabels([]) ax.xaxis.set_tick_params(direction="out", labelsize=10) ax.set_ylim([miny, maxy]) #ax.set_ylabel("Multitask Benefit", fontsize=10) ax.yaxis.set_ticks([miny, maxy]) ax.yaxis.set_ticklabels([]) ax.yaxis.set_tick_params(direction="out", labelsize=10) if ii > 0: ax.yaxis.set_tick_params(size=0) if ii == 0: ax.yaxis.set_ticklabels([miny, maxy]) if nn == (len(mean.columns.levels[0]) - 1): ax.xaxis.set_ticklabels([minx, maxx]) s1 = 10 d = mean.stack((0, -1))[s1].unstack((1, 2)).iloc[[0, -1]] ncolors = len(d.columns.levels[1]) cmap = plt.cm.cividis(np.linspace(0, 1, ncolors))[:, :3] fig, ax = plt.subplots(1, 1) #fig.set_size_inches([3.5, 2]) w = .25 miny = np.round(d.values.min(), 2) maxy = np.round(d.values.max(), 2) minx = -.5 maxx = len(d.columns.levels[0]) + .5 for nn, nlayers in enumerate(d.columns.levels[0]): ax.fill_betweenx([miny, maxy], nn - .5, nn + .5, color=((1, 1, 1) if nn%2 else (.95, .95, .95))) for jj, re in enumerate(d.columns.levels[1]): ax.plot([nn - w, nn + w], [d[nlayers][re].iat[0], d[nlayers][re].iat[-1]], color=cmap[jj], linewidth=2) ax.plot([nn - w, nn + w], [0, 0], color='k', linestyle='--') for key, sp in ax.spines.items(): if key in ("top", "right", "bottom"): sp.set_visible(False) ax.set_xlim([minx, maxx]) ax.xaxis.set_ticks(range(len(d.columns.levels[0]))) ax.xaxis.set_ticklabels(d.columns.levels[0]) ax.xaxis.set_tick_params(length=0, labelsize=10) ax.set_xlabel("Depth", fontsize=10) ax.set_ylim([miny, maxy]) ax.set_ylabel("Multitask Benefit", fontsize=10) ax.yaxis.set_ticks([miny, maxy]) ax.yaxis.set_tick_params(direction="out", labelsize=10) plt.tight_layout() ```
github_jupyter
# ARD Overpass Predictor <img align="right" src="../Supplementary_data/dea_logo.jpg"> * [**Sign up to the DEA Sandbox**](https://docs.dea.ga.gov.au/setup/sandbox.html) to run this notebook interactively from a browser * **Compatibility:** Notebook currently compatible with the `DEA Sandbox` environment * **Special requirements:** This notebook loads data from an external .csv file (`overpass_input.csv`) from the `Supplementary_data` folder of this repository ## Background Knowing the time of a satellite overpass (OP) at a field site is necessary to plan field work activities. While predicting the timesteps for a single field site that receives only one overpass from a given satellite is easy, it gets more complicated when you need overpass information across multiple field sites. For most sites, they will lie in a single descending (daytime) satellite acquisition. For Landsat 8 this occurs every 16 days and for Sentinel 2A / 2B this occurs every 10 days. This notebook can be used to output a list of ordered overpasses for given field sites by providing an initial timestamp for field sites of interest. Output for multiple sites are ordered by date such that dual overpasses can be identified. See "overpass_input.csv" as an example input file - this contains a number of field sites, with some that receive multiple acquisitions. ## Description You must provide a start date + time for the overpass of the site you are interested in - go to https://nationalmap.gov.au/ and https://evdc.esa.int/orbit/ to get an overpass for your location (lat/long) and add this to the input file. Take care with sites that receive multiple acquisitions, ie those that lie in the overlap of 2 acquisitions. - Specify an output file name - Provide an input file - this can be the example included or your own field site information - Specify which field sites receive extra overpasses in an orbital period, ie those which lie in satellite imaging overlap - Specify output field sites - you can select a subset of sites of interest (if adding your site to the original example file) - Combine field site overpasses If you wish to add or alter sites to predict for, edit the input file located at: ../Supplementary_data/ARD_overpass_predictor/overpass_input.csv And modify the input file path to reflect. You will need to leave the 1st site in the input file (Mullion) as the notebook requires this to order multiple overpasses. ## Getting started To run the overpass predictor with the given input file, run all cells in the notebook starting with the "Load packages" cell. ### Load packages ``` import pandas as pd import numpy as np import datetime from datetime import timedelta ``` ### Specify output file name This is the name of the .csv the notebook will output. This .csv will contain your combined predictions. ``` # You can rename the .csv to any desired output filename here. Default is "output_overpass_pred.csv" output_path = '../Supplementary_data/ARD_overpass_predictor/output_overpass_pred.csv' ``` ### Specify input file containing initial overpass data for a given site Read in base overpass file ```overpass_input.csv``` - Input date times must be in UTC - Make sure the necessary dates for your site are imported correctly - should be YYYY-MM-DD HH:MM:SS in 24hr format ``` # Read in base file 'overpass_input.csv' # Edit this file with new field sites, or load your own file with field sites as needed. # You don't need to input Path / Row or Lat / Long. The notebook only requires start times for the relevant satellites. base_file_path = '../Supplementary_data/ARD_overpass_predictor/overpass_input.csv' overpass = pd.read_csv(base_file_path, index_col='Site', parse_dates=['landsat_8', 'sentinel_2a', 'sentinel_2b', 'landsat_8_2', 'sentinel_2a_2', 'sentinel_2b_2']) overpass #"NaT" values are expected - indicates a date was not entered in input file. # Set a list for field sites included in prediction. If adding to the field sites, please leave the 1st entry, "Mullion", # as this is used to order secondary overpasses. sites = list(overpass.index) sites[0] # outputs 1st site. Should be 'Mullion' # Set satellite timesteps for overpasses # Depending on your application, you may want to add more accurate timesteps - but note that times used as inputs are # for the beginning of the acquisition, not the actual overpass time at a specific site. l8_timestep = datetime.timedelta (days=16) s2a_timestep = datetime.timedelta (days=10) s2b_timestep = datetime.timedelta (days=10) # Specify start date l8_startdate = overpass['landsat_8'] l8_startdate_2 = overpass['landsat_8_2'] sentinel2a_startdate = overpass['sentinel_2a'] sentinel2a_2_startdate = overpass['sentinel_2a_2'] sentinel2b_startdate = overpass['sentinel_2b'] sentinel2b_2_startdate = overpass['sentinel_2b_2'] sentinel2a_startdate ``` ### Project Times The following cell calculates times for Landsat and Sentinel overpasses for field sites. This is done by multiplying a number of desired iterations by the overpass frequency. Overpass frequencies for Landsat 8 = 16 days, Sentinel = 10 days. Increasing the number X in "for i in range(X):" will increase the number of iterations to predict over per satellite. An initial value of 20 iterations is set for L8, and 32 for Sentinel to result in the same total time period (320 days) to predict over. Predictions are also calculated for secondary overpasses for each site. ``` # Landsat 8 overpass prediction for 20*(overpass frequency) - ie 20*16 = 320 days. You can change this as desired, # to get overpass predictions for n days. n = x*(OP freq). X is arbitrarily set to 20 to give 320 days as a base example landsat = list() for i in range(20): landsat.append(l8_startdate + l8_timestep*(i)) landsat = pd.DataFrame(landsat) # Sentinel 2a overpass prediction for 32 * the overpass frequency, this is to give a similar total time to the L8 prediction. # OP frequency for Sentinel = 10 days, n days = 32*10 = 320 Sentinel_2A = [] for i in range(32): Sentinel_2A.append(sentinel2a_startdate + s2a_timestep * (i)) Sentinel_2A = pd.DataFrame(Sentinel_2A) # Sentinel 2b Sentinel_2B = [] for i in range(32): Sentinel_2B.append(sentinel2b_startdate + s2b_timestep * (i)) Sentinel_2B = pd.DataFrame(Sentinel_2B) # Landasat_2 # Prediction for L8 overpasses at sites which are covered by more than 1 overpass in a 16-day period. # - only Mullion in example .csv landsat_2 = [] for i in range(20): landsat_2.append(l8_startdate_2 + l8_timestep*(i)) landsat_2 = pd.DataFrame(landsat_2) # Sentinel_2A_2 # Sentinel 2a secondary (Mullion) Sentinel_2A_2 = [] for i in range(32): Sentinel_2A_2.append(sentinel2a_2_startdate + s2a_timestep * (i)) Sentinel_2A_2 = pd.DataFrame(Sentinel_2A_2) # Sentinel_2B_2 # Sentinel 2b secondary (Lake_George, Narrabundah) Sentinel_2B_2 = [] for i in range(32): Sentinel_2B_2.append(sentinel2b_2_startdate + s2b_timestep * (i)) Sentinel_2B_2 = pd.DataFrame(Sentinel_2B_2) ``` ### Append dataframes for sites that recieve more than 1 overpass in an orbital period. - If adding sites to the input file, please leave in "Mullion" - the 1st entry, as this is used to order secondary overpasses by. ``` # Combine Landsat 8 data (base plus extra overpasses) L8_combined2 = landsat.append(landsat_2) drop_label_L8 = L8_combined2.reset_index(drop=True) L8_combined2 = drop_label_L8.sort_values(by='Mullion') L8_combined2.index.names = ['Landsat_8'] # Combine Sentinel 2A data (base plus extra overpasses) S2A_combined = Sentinel_2A.append(Sentinel_2A_2) drop_label_S2A = S2A_combined.reset_index(drop=True) S2A_combined = drop_label_S2A.sort_values(by='Mullion') S2A_combined.index.names = ['Sentinel_2A'] # Combine Sentinel 2B data (base plus extra overpasses) S2B_combined = Sentinel_2B.append(Sentinel_2B_2) drop_label_S2B = S2B_combined.reset_index(drop=True) S2B_combined = drop_label_S2B.sort_values(by='Mullion') S2B_combined.index.names = ['Sentinel_2B'] # Add satellite label to each entry in "Sat" column S2A_combined['Sat'] = 'S2A' S2B_combined['Sat'] = 'S2B' L8_combined2['Sat'] = 'L8' combined1 = S2B_combined.append(S2A_combined) combined = combined1.append(L8_combined2) df = pd.DataFrame(combined) # Use a "time dummy" to force a re-order of data by date, to standardise across dataframes. timedummy = [] t0 = datetime.date(2019, 11, 1) dummystep = datetime.timedelta(days=2) for i in range(300): timedummy.append(t0 + dummystep * (i)) timedummy = pd.DataFrame(timedummy) df['DateStep'] = timedummy ``` ### Output field sites For new field sites, comment "#" out the old, add the new in the same format. ``` # Create a new df for each field site of interest. To add a new field site, add in same format ie # "Field_Site = df[['Field_Site', 'Sat', 'DateStep']].copy()" - if you are appending to the original file simply add in "site4 = sites[3]" # and "Site4 = df[[(site4), 'Sat', 'DateStep']].copy()" in the appropriate section below. site1 = sites[0] site2 = sites[1] site3 = sites[2] #site4 = sites[3] Site1 = df[[(site1), 'Sat', 'DateStep']].copy() Site2 = df[[(site2), 'Sat', 'DateStep']].copy() Site3 = df[[(site3), 'Sat', 'DateStep']].copy() #Site4 = df[[(site4), 'Sat', 'DateStep']].copy() # Reorder by date for each site, include satellite tags for each date. # Add new lines for new sites as needed. Site1 = (Site1.sort_values(by=[(site1), 'DateStep'])).reset_index(drop=True) Site2 = (Site2.sort_values(by=[(site2), 'DateStep'])).reset_index(drop=True) Site3 = (Site3.sort_values(by=[(site3), 'DateStep'])).reset_index(drop=True) #Site4 = (Site4.sort_values(by=[(site4), 'DateStep'])).reset_index(drop=True) ``` ### Optional - output individual field site. - if you wish to output multiple field sites, skip this step. ``` # Use this cell to ouput an individual field site # Write individual site to excel: take out "#" symbol below, or add new line for new site in this format: #Site1.to_excel('Site1.csv') #Site2.to_excel('Site2.csv') ``` ### Combine dataset The overpass predictions are combined and output to the specified "output_path". Times are in the same timezone as the input file. The example file used is in UTC, but you can also run the notebook on local times. To convert UTC (or whatever your input time was) to local time, ie AEST (or any other time zone), add 10h to the times or 11 for AEDT. This part is in the below cell, commented out. Remove the #'s to run the command on your desired column, and it will add the timestep. Yay, you have a list of overpasses! ``` combined_sites = ([Site1, Site2, Site3]) ## If you have more sites, ie you have added 1 or more, add here! An example is provided below if you have a total of 5 sites. #combined_sites = ([Site1, Site2, Site3, Site4, Site5]) merged = pd.concat(combined_sites, axis=1) merged = merged.rename_axis("Overpass", axis="columns") output = merged.drop(['DateStep'], axis=1) #add timestep: (comment out / delete hash to use as applicable - must include column/site name) - ignore the error #output['Mullion']=output['Mullion']+datetime.timedelta(hours=10) #output['Lake_George']=output['Lake_George']+datetime.timedelta(hours=10) #output['Narrabundah']=output['Narrabundah']+datetime.timedelta(hours=10) output.to_csv(output_path) output.head(20) ``` *** ## Additional information **License:** The code in this notebook is licensed under the [Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0). Digital Earth Australia data is licensed under the [Creative Commons by Attribution 4.0](https://creativecommons.org/licenses/by/4.0/) license. **Contact:** If you need assistance, please post a question on the [Open Data Cube Slack channel](http://slack.opendatacube.org/) or on the [GIS Stack Exchange](https://gis.stackexchange.com/questions/ask?tags=open-data-cube) using the `open-data-cube` tag (you can view previously asked questions [here](https://gis.stackexchange.com/questions/tagged/open-data-cube)). If you would like to report an issue with this notebook, you can file one on [Github](https://github.com/GeoscienceAustralia/dea-notebooks). **Last modified:** Jan 2021 ## Tags **Tags**: :index:`sentinel 2`, :index:`landsat 8`
github_jupyter
<a href="https://colab.research.google.com/github/jacobpad/DS-Unit-2-Linear-Models/blob/master/module4-logistic-regression/%20LS_DS12_214A.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> Lambda School Data Science *Unit 2, Sprint 1, Module 4* --- # Logistic Regression --- ## Assignment 🌯 ***CLASSIFICATION - A OR B - GREAT OR NOT*** --- You'll use a [**dataset of 400+ burrito reviews**](https://srcole.github.io/100burritos/). How accurately can you predict whether a burrito is rated 'Great'? > We have developed a 10-dimensional system for rating the burritos in San Diego. ... Generate models for what makes a burrito great and investigate correlations in its dimensions. - [ ] Do train/validate/test split. Train on reviews from 2016 & earlier. Validate on 2017. Test on 2018 & later. - [ ] Begin with baselines for classification. - [ ] Use scikit-learn for logistic regression. - [ ] Get your model's validation accuracy. (Multiple times if you try multiple iterations.) - [ ] Get your model's test accuracy. (One time, at the end.) - [ ] Commit your notebook to your fork of the GitHub repo. ## Stretch Goals - [ ] Add your own stretch goal(s) ! - [ ] Make exploratory visualizations. - [ ] Do one-hot encoding. - [ ] Do [feature scaling](https://scikit-learn.org/stable/modules/preprocessing.html). - [ ] Get and plot your coefficients. - [ ] Try [scikit-learn pipelines](https://scikit-learn.org/stable/modules/compose.html). # This code was given to start with ``` %%capture import sys # If you're on Colab: if 'google.colab' in sys.modules: DATA_PATH = 'https://raw.githubusercontent.com/LambdaSchool/DS-Unit-2-Linear-Models/master/data/' !pip install category_encoders==2.* # If you're working locally: else: DATA_PATH = '../data/' # Load data downloaded from https://srcole.github.io/100burritos/ import pandas as pd df = pd.read_csv(DATA_PATH+'burritos/burritos.csv') # Derive binary classification target: # We define a 'Great' burrito as having an # overall rating of 4 or higher, on a 5 point scale. # Drop unrated burritos. df = df.dropna(subset=['overall']) df['Great'] = df['overall'] >= 4 # Clean/combine the Burrito categories df['Burrito'] = df['Burrito'].str.lower() california = df['Burrito'].str.contains('california') asada = df['Burrito'].str.contains('asada') surf = df['Burrito'].str.contains('surf') carnitas = df['Burrito'].str.contains('carnitas') df.loc[california, 'Burrito'] = 'California' df.loc[asada, 'Burrito'] = 'Asada' df.loc[surf, 'Burrito'] = 'Surf & Turf' df.loc[carnitas, 'Burrito'] = 'Carnitas' df.loc[~california & ~asada & ~surf & ~carnitas, 'Burrito'] = 'Other' # Drop some high cardinality categoricals df = df.drop(columns=['Notes', 'Location', 'Reviewer', 'Address', 'URL', 'Neighborhood']) # Drop some columns to prevent "leakage" df = df.drop(columns=['Rec', 'overall']) ``` # Start with my imports ``` # A bunch of imports, yes, it's probably overkill import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import scipy.stats as stats import math import plotly.express as px import category_encoders as ce import datetime # import and manipulate datetime from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_absolute_error, r2_score from sklearn.linear_model import Ridge from sklearn.linear_model import RidgeCV from IPython.display import display, HTML from sklearn.feature_selection import SelectKBest, f_regression %matplotlib inline ``` # Check some things out ``` df df.describe() df.describe().T df.describe(exclude='number') df.describe(exclude='number').T df.columns df.isnull().sum() ``` # Train/Validate/Test Split ``` # Do train/validate/test split. Train on reviews from 2016 & earlier. Validate on 2017. Test on 2018 & later. # Begin with baselines for classification. # Use scikit-learn for logistic regression. # Get your model's validation accuracy. (Multiple times if you try multiple iterations.) # Get your model's test accuracy. (One time, at the end.) # Commit your notebook to your fork of the GitHub repo. ``` # Fix the date ``` # Fix the date thing to the date # See what it is print(df['Date'].head(1)) # it's an object # Now make it something usable # Change the date datatype print('Before changing --',df['Date'].dtypes) df['Date'] = pd.to_datetime(df['Date']) print('Post changing --',df['Date'].dtypes) ``` # Seperate the Train, Validate & Split - Train on reviews from 2016 & earlier. Validate on 2017. Test on 2018 & later ``` # Set the Train start_date = '01-01-1900' end_date = '12-31-2016' train = df[(df['Date'] > start_date) & (df['Date'] <= end_date)] print(train['Date'].min()) print(train['Date'].max()) # Set the Validate start_date = '01-01-2017' end_date = '12-31-2017' validate = df[(df['Date'] > start_date) & (df['Date'] <= end_date)] print(validate['Date'].min()) print(validate['Date'].max()) # Set the Test start_date = '01-01-2018' test = df[(df['Date'] > start_date)] print(test['Date'].min()) print(test['Date'].max()) # Print the shapes print('Train -',train.shape) print('Validate -',validate.shape) print('Test -',test.shape) ```
github_jupyter
##### Copyright 2019 Google LLC. Licensed under the Apache License, Version 2.0 (the "License"); ``` #@title Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" } # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ``` # Introduction to TensorFlow Part 1 - Basics <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https://colab.research.google.com/github/google/tf-quant-finance/blob/master/tf_quant_finance/examples/jupyter_notebooks/Introduction_to_TensorFlow_Part_1_-_Basics.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a> </td> <td> <a target="_blank" href="https://github.com/google/tf-quant-finance/blob/master/tf_quant_finance/examples/jupyter_notebooks/Introduction_to_TensorFlow_Part_1_-_Basics.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a> </td> </table> ``` #@title Install Libraries for this colab !pip install scipy !pip install matplotlib import base64 import matplotlib.pyplot as plt import numpy as np import numpy.testing as npt import scipy as sp import seaborn as sns import tensorflow as tf import time from PIL import Image from pprint import pprint from io import StringIO %load_ext tensorboard ``` # What this notebook covers The aim of this mini course is to get you up and running with Tensorflow. It's not just a walkthrough. To get the most out of this, you should follow along by running the examples below. We cover just the basics of Tensorflow. - Underlying concepts of Tensors, shapes, Operations, graphs etc. - The functionality available in the core tensorflow API. - Not really concerned with Machine Learning. While TensorFlow is widely associated with ML, it can (and was originally designed to) be used to accelerate most traditional numerical calculations. # Tips And References - The Tensorflow API reference is indispensable while you learn the ropes. [Tensorflow Python API](https://www.tensorflow.org/api_docs/python/tf) - You will need to refer to it through this course. - This notebook uses Google Colab - allowing you to run code interactively. See [the introduction](https://colab.research.google.com/notebooks/welcome.ipynb) for more information. - In Colab you can use the autocomplete feature to see the available functions and the usage. - **To see all the names available** under some module (e.g. tf.constant under tf), type the name of the module followed by a period and hit **Ctrl+Space**. - **To see the usage instructions** for a function, type the function name followed by an open bracket and hit **Tab**. ``` #@title %%html <div style="text-align:center; font-size: 100px; opacity: 0.9; color:orange">Let's Begin</div> ``` # What is Tensorflow Tensorflow is a system designed for efficient numerical computations. - The core of Tensorflow is written in C++. - The client API is most commonly developed in Python and other languages are supported. - A tensorflow program describes the computation as a sequence of operations. - The operations (also called Ops) act on zero or more inputs. The inputs are called Tensors. - The outputs of ops are also Tensors. - You can think of tensors as the data and the ops as the functions that act on that data. - Output of one op can be sent as input to another op. - A tensorflow program is a directed **graph** whose edges are tensors and the nodes are Ops. - The tensors 'flow' along the edges, hence, Tensorflow. Let us see an example. ``` tf.reset_default_graph() # a, b, c and d below are tensors. a = tf.constant([1.0], name = "a") b = tf.constant([2.0], name = "b") # This creates an output tensor of the 'Op' tf.add. # The tensor's name is 'addition', which is what you'll see in the graph # below. And we store the tensor in a python variable called 'c' c = tf.add(a, b, name="addition") # The Op 'tf.sin' consumes the input tensor 'c' and returns another tensor 'd' d = tf.sin(c, name="sin") # implementation details to generate a graph visualisation with tf.Session() as sess: with tf.summary.FileWriter("logs", sess.graph): sess.run(d) %tensorboard --logdir logs ``` # Execution Models Tensorflow has two models of execution: deferred and (since v2) eager. ## Deferred Execution With deferred mode, you build up a graph of operations, so this tensorflow code ```python a = tf.constant([1.0]) b = tf.constant([2.0]) c = tf.add(a, b) ``` is roughly equivalent to this python code ```python a = 1 b = 2 def c(): return a + b ``` In the python code, c does not hold the value 3: it holds a function. In order to get the value 3, you need to execute the function: ```python c() # returns the value 3 ``` In the same way with tensorflow in deferred mode, c doesn't hold a tensor with the value 3, it holds an execution graph that can be executed inside a *Session* to obtain the value 3, as per below ``` tf.reset_default_graph() a = tf.constant([1.0], name = "a") b = tf.constant([2.0], name = "b") c = tf.add(a, b, name="addition") print c with tf.Session() as sess: result = sess.run(c) print result ``` Sessions are discussed in more detail [later on](#scrollTo=KGYeF4K1JLIJ) While the graph is being built, TensorFlow does little more than check that the operations have been passed the right numbers of arguments and that they're of the right type and shape. Once the graph has been built, it can be * serialized, stored, repeatedly executed * analyzed and optimised: removing duplicate operations, hoisting constants up levels etc. * split across multiple CPUs, GPUs and TPUs * etc. This allows for a lot of flexibility and performance for long calculations. However when manually experimenting this mode does get in the way of the REPL behaviour that python developers are used to. Thus in tensorflow v2, eager execution was added... ## Eager Execution Eager execution works in a more intuitive fashion. Operations are executed immediately, rather than being stored as deferred instructions. With eager mode enabled, the following ```python import tensorflow as tf tf.enable_eager_execution() a = tf.constant([1.0], name = "a") b = tf.constant([2.0], name = "b") c = tf.add(a, b, name="addition") print (c) ``` would produce the output ```python tf.Tensor([3.], shape=(1,), dtype=float32) ``` To enable eager execution, just call the tf.enable_eager_execution() function. But note that the choice of execution model is an irrevocable, global one. It must be done before any tensorflow methods are called, once your process has using tensor flow in one mode, it cannot switch to the other. # Tensors and Shapes - A tensor is just an $n$-dimensional matrix. - The *rank* of a tensor is the number of dimensions it has (alternatively, the number of indices you have to specify to get at an element). - A vector is a rank $\color{blue} 1$ tensor. - A matrix is a rank $\color{blue} 2$ tensor. - Tensor is characterized by its shape and the data type of its elements. - The shape is a specification of the number of dimensions and the length of the tensor in each of those dimensions. - Shape is described by an integer vector giving the lengths in each dimension. - For example, $\left[\begin{array}{cc} 1 & 0 \\ 0 & 1 \\ 1 & 1 \end{array}\right]$ is tensor of shape [3, 2]. - On the other hand, $\left[\begin{array}{cc} [1] & [0] \\ [0] & [1] \\ [1] & [1] \end{array}\right]$ is a tensor of shape [3, 2, 1]. - The shape is read starting from the "outside" and moving in until you reach an elementary object (e.g. number or string). - Note that Tensors are not just arbitrary arrays. For example, $[1, [2]]$ is not a Tensor and has no unambiguous shape. - Tensorflow shapes are almost the same as numpy shapes. ``` #@title Fun with shapes import numpy as np # This is equivalent to a 0-rank tensor (i.e. a scalar). x = np.array(2.0) t = tf.constant(x) print ("Shape of %s = %s\n" % (x, t.shape)) # A rank 1 tensor. Shape = [5] x = np.array([1, 2, 3, 4, 5]) t = tf.constant(x) print ("Shape of %s: %s\n" % (x, t.shape)) # A rank 2 tensor. Shape = [5, 1] x = np.array([[1], [2], [3], [4], [5]]) t = tf.constant(x) print ("Shape of %s: %s\n" % (x, t.shape)) # A rank 2 tensor. Shape = [1, 5] x = np.array([[1, 2, 3, 4, 5]]) t = tf.constant(x) print ("Shape of %s: %s\n" % (x, t.shape)) # A rank 3 tensor. Shape = [2, 1, 2] x = np.array( [ [ [0, 0] ], [ [0, 0] ] ]) t = tf.constant(x) print ("Shape of %s: %s\n" % (x, t.shape)) #@title Shape Quiz import numpy as np # to-do: Fill in an array of shape [1, 2, 1, 2] in the variable x. # The values you choose don't matter but the shape does. x = np.array([]) t = tf.constant(x, name = "t") if t.shape == [1, 2, 1, 2]: print ("Success!") else: print ("Shape was %s. Try again"%t.shape) #@title Solution: Shape Quiz. Double click to reveal import numpy as np import tensorflow.google as tf # The values you choose don't matter but the shape does. x = np.array([ [[[0, 0]], [[0, 0]]] ] ) t = tf.constant(x) if t.shape == [1, 2, 1, 2]: print ("Success!") else: print ("Shape was %s. Try again"%t.shape) ``` ## Shape And Reshape Most Tensorflow operations preserve the tensor shapes or modify it in obvious ways. However you often need to rearrange the shape to fit the problem at hand. There is a number of shape related ops in Tensorflow that you can make use of. First we have these ops to give us information about the tensor shape | Name | Description | |--- | --- | |[tf.shape](https://www.tensorflow.org/api_docs/python/tf/shape) | Returns the shape of the tensor | |[tf.size](https://www.tensorflow.org/api_docs/python/tf/size) | Returns the total number of elements in the tensor | |[tf.rank](https://www.tensorflow.org/api_docs/python/tf/rank) | Returns the tensor rank | ``` #@title Shape Information Ops import numpy as np # These examples are a little silly because we already know # the shapes. x = tf.constant(np.zeros([2, 2, 3, 12])) shape_x = tf.shape(x, name="my_shape") print("Shape of x: %s" % shape_x.eval(session=tf.Session())) rank_x = tf.rank(x) print("Rank of x: %s" % rank_x.eval(session=tf.Session())) size_x = tf.size(x) print("Size of x: %s" % size_x.eval(session=tf.Session())) ``` NB: The hawkeyed amongst us would have noticed that there seem to be two different shape methods. In the examples on the previous slide we saw tensor.shape property and above we saw tf.shape(tensor). There are subtle differences between the two which we will discuss more when we talk about placeholders. ## Reshaping Continued Coming back to the ops that you can use to modify the shape, the following table lists some of them. | Name | Description | |--- |:---| |[tf.reshape](https://www.tensorflow.org/api_docs/python/tf/reshape)| Reshapes a tensor while preserving number of elements | |[tf.squeeze](https://www.tensorflow.org/api_docs/python/tf/squeeze)| "Squeezes out" dimensions of length 1| |[tf.expand\_dims](https://www.tensorflow.org/api_docs/python/tf/expand_dims)| Inverse of squeeze. Expands the dimension by 1| |[tf.transpose](https://www.tensorflow.org/api_docs/python/tf/transpose)| Permutes the dimensions. For matrices, performs usual matrix transpose.| |[tf.meshgrid](https://www.tensorflow.org/api_docs/python/tf/meshgrid) | Effectively creates an N dimensional grid from N one dimensional arrays. | The following example demonstrates the use of the reshape op. ``` #@title Reshaping Tensors import numpy as np # Create a constant tensor of shape [12] x = tf.constant(np.arange(1, 13)) print("x = %s\n" % x.eval(session=tf.Session())) # Reshape this to [2, 6]. Note how the elements get laid out. x_2_6 = tf.reshape(x, [2, -1]) print("x_2_6 = %s\n" % x_2_6.eval(session=tf.Session())) # Further rearrange x_2_6 to [3, 4] x_3_4 = tf.reshape(x_2_6, [3, 4]) print("x_3_4 = %s\n" % x_3_4.eval(session=tf.Session())) # In fact you don't have to specify the full shape. You can leave # one component of the shape unspecified by setting it to -1. # This component will then be computed automatically by preserving the # total size. x_12_1 = tf.reshape(x_3_4, [-1, 1]) print("x_12_1 = %s\n" % x_12_1.eval(session=tf.Session())) # What happens when are too many or too few elements? # You get an error! #x_wrong = tf.reshape(x_3_4, [4, 5]) #print("x_wrong = %s" % x_12_1.eval(session=tf.Session())) ``` The next set of examples show how to use the squeeze and expand_dims ops. ``` #@title Squeezing and Expanding Tensors import numpy as np # Create a tensor where the second and fourth dimension is of length 1. x = tf.constant(np.reshape(np.arange(1, 5), [2, 1, 2, 1])) print("Shape of x = %s" % x.shape) # Now squeeze out all the dimensions of length 1 x_squeezed = tf.squeeze(x) print("\nShape of x_squeezed = %s" % x_squeezed.shape) # You can control which dimension you squeeze x_squeeze_partial = tf.squeeze(x,3) print("\nShape of x_squeeze_partial = %s" % x_squeeze_partial.shape) # Expand_dims works in reverse to add dimensions of length one. # Think of this as just adding brackets [] somewhere in the tensor. y = tf.constant([[1, 2],[3, 4]]) y_2 = tf.expand_dims(y, 2) y_3 = tf.expand_dims(y_2, 2) print("\nShape of y = %s" % y.shape) print("\nShape of y_2 = %s" % y_2.shape) print("\nShape of y_3 = %s" % y_3.shape) with tf.Session() as sess: print(sess.run(y_3)) ``` * The transpose op deserves a bit of explanation. * For matrices, it does the usual transpose operation. * For higher rank tensors, it allows you to permute the dimensions by specifying the permutation you want. Examples will (hopefully) make this clearer. ``` #@title Transposing tensors import numpy as np # Create a matrix x = tf.constant([[1, 2], [3, 4]]) x_t = tf.transpose(x) print("X:\n%s\n" % x.eval(session=tf.Session())) print("transpose(X):\n%s\n" % x_t.eval(session=tf.Session())) # Now try this for a higher rank tensor. # Create a tensor of shape [3, 2, 1] y = tf.constant([[[1],[2]], [[3],[4]], [[5],[6]]]) print("Shape of Y: %s\n" % y.shape) print("Y:\n%s\n" % y.eval(session=tf.Session())) # Flip the first two dimensions y_t12 = tf.transpose(y, [1, 0, 2]) print("Shape of Y with the first two dims flipped: %s\n" % y_t12.shape) print("transpose(Y, 1 <-> 2):\n%s\n" % y_t12.eval(session=tf.Session())) ``` ## Quiz: Create a Grid We mentioned the tf.meshgrid op above but didn't use it. In this quiz you will use it to do something we will find useful later on. Suppose we are given a set of x coordinates, say, [1, 2, 3] and another set of y coordinates e.g. [1, 2, 3]. We want to create the "grid" formed from these coordinates as shown in the following diagram. tf.meshgrid allows you to do this but it will produce the X and Y coordinates of the grid separately. Your task below is to create a tensor of complex numbers such that Z = X + j Y represents points on the grid (e.g. the lower left most point will have Z = 1 + j while the top right one has Z = 3 + 3j. You should put your code in the function **create_grid** and run the cell when you are done. If it works, you will see a plot of the grid that you produced. Hints: * Experiment with tf.meshgrid to get X and Y of the right shape needed for the grid. * Join the separate X and Y using tf.complex(x, y) ``` #@title %%html <div style="text-align:center; font-size: 40px; opacity: 0.9; color:blue"><p>Example Grid</p> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="400px" height="300px" viewBox="0 0 400 300" preserveAspectRatio="xMidYMid meet" ><rect id="svgEditorBackground" x="0" y="0" width="300" height="300" style="fill: none; stroke: none;"/> <line x1="106.26899719238736" y1="50.779850959776496" x2="107.26899719238736" y2="236.77943420410023" stroke="black" style="stroke-width: 1px; fill: none;"/> <line x1="174.26887512207486" y1="50.779850959776496" x2="174.26887512207486" y2="236.77943420410023" stroke="black" style="stroke-width: 1px; fill: none;"/> <line x1="240.26852416992642" y1="50.779850959776496" x2="240.26852416992642" y2="236.77943420410023" stroke="black" style="stroke-width: 1px; fill: none;"/> <text fill="black" x="101.269" y="271.779" style="font-family: Arial; font-size: 20px;" > <tspan x="100.271" y="256.785" dy="" dx="">1</tspan> <tspan x="169.271" dy="0" y="" dx="">2</tspan> <tspan x="234.271" dy="0" y="" dx="">3</tspan> </text> <line x1="62.26904296875455" y1="209.77961730956898" x2="320.26831054687955" y2="209.77961730956898" stroke="black" style="stroke-width: 1px; fill: none;"/> <line x1="62.26904296875455" y1="153.77967834472523" x2="320.26831054687955" y2="153.77967834472523" stroke="black" style="stroke-width: 1px; fill: none;"/> <line x1="62.26904296875455" y1="99.77981567382679" x2="320.26831054687955" y2="99.77981567382679" stroke="black" style="stroke-width: 1px; fill: none;"/> <text fill="black" x="42.269" y="215.78" id="e523_texte" style="font-family: Arial; font-size: 20px;" >1</text> <text fill="black" x="42.269" y="156.78" id="e552_texte" style="font-family: Arial; font-size: 20px;" >2</text> <text fill="black" x="41.269" y="105.78" id="e564_texte" style="font-family: Arial; font-size: 20px;" >3</text> <circle id="e616_circle" cx="105.26899719238736" cy="99.77981567382679" stroke="black" style="stroke-width: 1px;" r="3.25248" fill="khaki"/> <circle id="e628_circle" cx="173.26887512207486" cy="99.77981567382679" stroke="black" style="stroke-width: 1px;" r="3.25248" fill="khaki"/> <circle id="e640_circle" cx="240.26852416992642" cy="99.77981567382679" stroke="black" style="stroke-width: 1px;" r="3.25248" fill="khaki"/> <circle id="e652_circle" cx="240.26852416992642" cy="153.77967834472523" stroke="black" style="stroke-width: 1px;" r="3.25248" fill="khaki"/> <circle id="e664_circle" cx="241.26850891113736" cy="208.77961730956898" stroke="black" style="stroke-width: 1px;" r="3.25248" fill="khaki"/> <circle id="e676_circle" cx="174.26887512207486" cy="153.77967834472523" stroke="black" style="stroke-width: 1px;" r="3.25248" fill="khaki"/> <circle id="e688_circle" cx="106.26899719238736" cy="153.77967834472523" stroke="black" style="stroke-width: 1px;" r="3.25248" fill="khaki"/> <circle id="e700_circle" cx="107.26899719238736" cy="208.77961730956898" stroke="black" style="stroke-width: 1px;" r="3.25248" fill="khaki"/> <circle id="e712_circle" cx="174.26887512207486" cy="209.77961730956898" stroke="black" style="stroke-width: 1px;" r="3.25248" fill="khaki"/> <text fill="black" x="111.269" y="199.78" id="e749_texte" style="font-family: Arial; font-size: 16px;" dy="" dx="" >(1,1)</text> <text fill="black" x="174.269" y="201.78" id="e835_texte" style="font-family: Arial; font-size: 16px;" >(2,1)</text> <text fill="black" x="107.269" y="90.7798" id="e847_texte" style="font-family: Arial; font-size: 16px;" >(1,3)</text> <text fill="black" x="108.269" y="145.78" id="e859_texte" style="font-family: Arial; font-size: 16px;" dy="" dx="" >(1,2)</text> <text fill="black" x="174.269" y="145.78" id="e967_texte" style="font-family: Arial; font-size: 16px;" >(2,2)</text> <text fill="black" x="175.269" y="92.7798" id="e994_texte" style="font-family: Arial; font-size: 16px;" >(2,3)</text> <text fill="black" x="240.269" y="200.78" id="e1021_texte" style="font-family: Arial; font-size: 16px;" >(3,1)</text> <text fill="black" x="241.269" y="145.78" id="e1048_texte" style="font-family: Arial; font-size: 16px;" >(3,2)</text> <text fill="black" x="241.269" y="92.7798" id="e1075_texte" style="font-family: Arial; font-size: 16px;" >(3,3)</text> <text fill="black" x="176.269" y="284.779" id="e1257_texte" style="font-family: Arial; font-size: 20px;" >x</text> <text fill="black" x="11.269" y="157.78" id="e1272_texte" style="font-family: Arial; font-size: 20px;" >y</text> </svg> </div> #@title Reshaping Quiz import numpy as np import matplotlib.pyplot as plt def create_grid(x, y): """Creates a grid on the complex plane from x and y. Given a set of x and y coordinates as rank 1 tensors of sizes n and m respectively, returns a complex tensor of shape [n, m] containing points on the grid formed by intersection of horizontal and vertical lines rooted at those x and y values. Args: x: A float32 or float64 tensor of shape [n] y: A tensor of the same data type as x and shape [m]. Returns: A complex tensor with shape [n, m]. """ raise NotImplementedError() coords = tf.constant([1.0, 2.0, 3.0]) square_grid = create_grid(coords, coords) def test(): x_p = np.array([1.0, 2.0, 3.0]) y_p = np.array([5.0, 6.0, 7.0, 8.0]) tensor_grid = create_grid(tf.constant(x_p), tf.constant(y_p)) grid = tensor_grid.eval(session=tf.Session()) print grid n_p = x_p.size * y_p.size x = np.reshape(np.real(grid), [n_p]) y = np.reshape(np.imag(grid), [n_p]) plt.plot(x, y, 'ro') plt.xlim((x_p.min() - 1.0, x_p.max() + 1.0)) plt.ylim((y_p.min() - 1.0, y_p.max() + 1.0)) plt.ylabel('Imaginary') plt.xlabel('Real') plt.show() test() #@title Reshaping Quiz - Solution. Double click to reveal import numpy as np import matplotlib.pyplot as plt import tensorflow as tf def create_grid(x, y): """Creates a grid on the complex plane from x and y. Given a set of x and y coordinates as rank 1 tensors of sizes n and m respectively, returns a complex tensor of shape [n, m] containing points on the grid formed by intersection of horizontal and vertical lines rooted at those x and y values. Args: x: A float32 or float64 tensor of shape [n] y: A tensor of the same data type as x and shape [m]. Returns: A complex tensor with shape [n, m]. """ X, Y = tf.meshgrid(x, y) return tf.complex(X, Y) coords = tf.constant([1.0, 2.0, 3.0]) square_grid = create_grid(coords, coords) def test(): x_p = np.array([1.0, 2.0, 3.0]) y_p = np.array([5.0, 6.0, 7.0, 8.0]) tensor_grid = create_grid(tf.constant(x_p), tf.constant(y_p)) grid = tensor_grid.eval(session=tf.Session()) n_p = x_p.size * y_p.size x = np.reshape(np.real(grid), [n_p]) y = np.reshape(np.imag(grid), [n_p]) plt.plot(x, y, 'ro') plt.xlim((x_p.min() - 1.0, x_p.max() + 1.0)) plt.ylim((y_p.min() - 1.0, y_p.max() + 1.0)) plt.ylabel('Imaginary') plt.xlabel('Real') plt.show() test() ``` # Tensors vs. Numpy Arrays - Tensors can be created by wrapping numpy arrays (as above) or even python lists. - You can use all the Numpy methods to create arrays that can be wrapped as a tensor. - Most Tensorflow ops will accept a numpy array directly but they will convert it to a tensor implicitly. - For many Numpy methods, there are analogous Tensorflow methods which we will see later. - Example: np.zeros $\leftrightarrow$ tf.zeros - However, a tensor is *not* the same as a numpy array. - Tensors are more like "pointers" to the data. - They don't have their values until they are evaluated. Numpy arrays are eagerly evalauted. - You can't convert a Tensor back to a numpy array without evaluating the graph. The following examples clarify this. ``` # Import Tensorflow and numpy. import numpy as np # You can make a tensor out of a python list. tensor_of_ones = tf.constant([1, 1, 1], dtype=tf.int64) # You can also use numpy methods to generate the arrays. tensor_of_twos = tf.constant(np.repeat(2, [3])) # Tensorflow Ops (tf.add) accept tensors ... tensor_of_threes = tf.add(tensor_of_ones, tensor_of_twos) # ... and (sometimes) also the numpy array directly. tensor_of_threes_1 = tf.add(np.array([1, 1, 1]), tensor_of_twos) # You can check that the tensor print("Type: %s" % type(tensor_of_threes)) # This is not an array! # It is a tensor. ``` ## How does it work? - **tf.constant** creates a tensor from some constant data. - In addition to supplying python lists, you may also supply numpy arrays. - Much easier to create higher dimensional data with numpy arrays. - **tf.add** is an example of an ***Op***. It takes two tensor arguments and returns a tensor. - Tensors have a definite type, e.g. int32, float64, bool etc. - By default, TF will use the type of the supplied numpy array. - For python lists, TF will try to infer the type but you are better off supplying the type explicitly using "dtype=" arg. ## Tensor data types - Other than shape, tensors are characterized by the type of data elements it contains. - Useful to keep in mind the following commonly used types - Integer types: tf.int32, tf.int64 - Float types: tf.float32, tf.float64 - Boolean type: tf.bool - Complex type: tf.complex64, tf.complex128 - Many tensor creation ops (e.g. tf.constant, tf.Variable etc.) accept an optional *dtype* argument. - Tensorflow does not do automatic type conversions. For example, the following code causes an error. ``` #@title Strict Types in Tensorflow int32_tensor = tf.constant([1, 1], dtype=tf.int32) int64_tensor = tf.constant([2, 2], dtype=tf.int64) try_mix_types = tf.add(int32_tensor, int64_tensor) # Causes a TypeError ``` - Occasionally, we need to convert one type to another (e.g. int32 -> float32). - There are a few explicit conversion ops: - **[tf.to\_double](https://www.tensorflow.org/api_docs/python/tf/to_double)**: Convert to float64. - **[tf.to\_float](https://www.tensorflow.org/api_docs/python/tf/to_float)**: Convert to float32. - **[tf.to\_int64](https://www.tensorflow.org/api_docs/python/tf/to_int64)**: Convert to int64. - **[tf.to\_int32](https://www.tensorflow.org/api_docs/python/tf/to_int32)**: Convert to int32. - If you need conversion to something that isn't listed you can use the more general: **[tf.cast](https://www.tensorflow.org/api_docs/python/tf/cast)** ``` #@title Casting from one type to another # Make sure this is an int32 tensor by explicitly specifying type. # NB: In this particular case, even if you left out the type, TF # will infer it as an int32. int32_tensor = tf.constant([1, 1], dtype=tf.int32) int64_tensor = tf.constant([2, 2], dtype=tf.int64) casted_to_64 = tf.to_int64(int32_tensor) # This is OK. added = tf.add(casted_to_64, int64_tensor) # As an example of tf.cast, consider casting to boolean zero_one = tf.constant([1.0, 0.0, 1.0]) # Inferred as tf.float32 print("Type of zero_ones = %s" % repr(zero_one.dtype)) zero_one_bool = tf.cast(zero_one, tf.bool) print("Type of zero_ones_bool = %s" % repr(zero_one_bool.dtype)) # Another example of cast: Convert real numbers to Complex real_tensor = tf.constant([1.0, 1.0]) cplx_tensor = tf.cast(real_tensor, tf.complex64) ``` # Creating Tensors - We have already seen that tf.constant creates a tensor from supplied data. - Some other useful functions are in the table below. Use the Colab auto complete feature to see their usage instructions. ## Constant Tensors | Name | Description | |--- |:---| | [tf.zeros](https://www.tensorflow.org/api_docs/python/tf/zeros) | Creates a constant tensor of zeros of a given shape and type. | | [tf.zeros\_like](https://www.tensorflow.org/api_docs/python/tf/zeros_like) | Creates a constant tensor of zeros of the same shape as the input tensor. | | [tf.ones](https://www.tensorflow.org/api_docs/python/tf/ones) | Creates a constant tensor of ones of a given shape and type. | | [tf.ones\_like](https://www.tensorflow.org/api_docs/python/tf/ones_like) | Creates a constant tensor of ones of the same shape as the input tensor. | | [tf.linspace](https://www.tensorflow.org/api_docs/python/tf/linspace) | Creates an evenly spaced tensor of values between supplied end points. | The following example demonstrates some of these ops. ``` #@title Creating Constant Tensors without numpy # Create a bunch of zeros of a specific shape and type. x = tf.zeros([2, 2], dtype=tf.float64) # Eval evaluates the tensor so you can see what it contains. More later. print("tf.zeros example: %s" % x.eval(session=tf.Session())) # tf.zeros_like is pretty useful. It creates a zero tensors which is # shaped like some other tensor you supply. x = tf.constant([[[1], [2]]]) zeros_like_x = tf.zeros_like(x, dtype=tf.float32) print("Shape(x) = %s \nShape(zeros_like_x) = %s" % (x.shape, zeros_like_x.shape)) ``` ## Random Tensors A common need is to create tensors with specific shape but with randomly distributed entries. TF provides a few methods for these. | Name | Description | |--- |:---| | [tf.random\_normal](https://www.tensorflow.org/api_docs/python/tf/random_normal) | Generates a constant tensor with independent normal entries. | | [tf.random\_uniform](https://www.tensorflow.org/api_docs/python/tf/random_uniform) | Generates a constant tensor with uniformly distributed elements. | | [tf.random\_gamma](https://www.tensorflow.org/api_docs/python/tf/random_gamma) | Generates a constant tensor with gamma distributed elements. | | [tf.random\_shuffle](https://www.tensorflow.org/api_docs/python/tf/random_shuffle) | Takes an input tensor and randomly permutes the entries along the first dimension. | Let us see some of these in action. ``` #@title Creating Random Tensors # Create a matrix with normally distributed entries. x = tf.random_normal([1, 3], mean=1.0, stddev=4.0, dtype=tf.float64) print("A random normal tensor: %s" % x.eval(session=tf.Session())) # Randomly shuffle the first dimension of a tensor. r = tf.random_shuffle([1, 2, 3, 4]) print("Random shuffle of [1,2,3,4]: %s" % r.eval(session=tf.Session())) ``` # Sessions We have used tensor.eval(session=tf.Session()) invocation above, but what does it do? - When you write tensorflow ops or tensors, you are adding them to the "graph". - It does not immediately evaluate anything. It only performs some sanity checks on your ops. - Recall: a tensor itself is not the value. It is a container for the data that will be generated when it is evaluated. - After creating the graph you have to explicitly ask for one or more of the tensors to be evaluated. - Let's see this in action: - The argument you supply to eval is called a **Session**. - The session is an object that creates/controls/talks to the C++ runtime that will actually run your computation. - The client (i.e. your python session) transfers the graph information to the session to be evaluated. - The session evaluates **the relevant part of your graph** and returns the value to your client for you to enjoy. ``` #@title Evaluating Tensors x = tf.constant([1., 1.]) # Check that x is not actually a list. print "Type of 'x': %s" % type(x) # It is a tensor # Evaluate the tensor to actually make TF to do the computation. x_values = x.eval(session=tf.Session()) print "Value of 'x': %s\nType of x: %s" % (x_values, type(x_values)) ``` * When you eval a tensor, you are telling TF that you want it to go ahead and run the computation needed to get a value for that tensor. At that point, TF figures out what other operations and tensors it needs to evaluate to be able to give you what you want. * This extra step may seem annoying but it is (part of) what makes TF powerful. It allows TF to evaluate only those ops that are directly needed for the output. * In the usage above, it is rather inconvenient that we can only evaluate one tensor at a time. There are two way to avoid this. * Create a session variable and hold on to it for use with multiple evals. The following example demonstrates this: ``` #@title Using Sessions import numpy as np import matplotlib.pyplot as plt tf.reset_default_graph() # Create a 1-tensor with uniform entries between -pi and pi. x = tf.linspace(-np.pi, np.pi, 20) y = tf.sin(x) + tf.random_uniform([20], minval=-0.5, maxval=0.5) # Create session object which we will use multiple times. sess = tf.Session() plt.plot(x.eval(session=sess), y.eval(session=sess), 'ro') # A session is a resource (like a file) and you must close it when # you are done. sess.close() ``` * In the above method, it is still inconvenient to have to call eval on each tensor separately. * This can be avoided by using the method "run" on sessions as follows ``` # Continuation of the above example so you must run that first. sess = tf.Session() # Session.run evaluates one or more tensors supplied as a list # or a tuple. It returns their values as numpy arrays which you # may capture by assigning to a variable. x_v, y_v = sess.run((x, y)) plt.plot(x_v, y_v, 'ro') sess.close() ``` * It is pretty easy to forget to close the sessions so the best idea is to use them as context managers. This is the most common way of using sessions. ``` #@title Sessions as Context managers import matplotlib.pyplot as plt x = tf.linspace(-5.0, 5.0, 1000) y = tf.nn.sigmoid(x) with tf.Session() as sess: x_v, y_v = sess.run([x, y]) plt.plot(x_v, y_v) ``` # Example: Random Matrices Let us put together a few of the ops we have seen so far (and a few we haven't) into a longer example. A random matrix is a matrix whose entries are (usually independently) randomly distributed drawn from some chosen distribution. In this example, we will approximate the distribution of the **determinant** of a random $n \times n$ matrix. The steps we will follow are: * Generate a sample of matrices of a desired size. * Compute their determinant. * Plot the histogram. ``` import matplotlib.pyplot as plt # Dimension of matrix to generate. n = 10 # Number of samples to generate. sample_size = 100000 # We will generate matrices with elements uniformly drawn from (-1, 1). # Tensorflow provides a whole bunch of methods to generate random tensors # of a given shape and here we will use the random_uniform method. samples = tf.random_uniform(shape=[sample_size, n, n], minval=-1, maxval=1) # There is also an Op to generate matrix determinant. It requires that you pass # it a tensor of shape [...., N, N]. This ensures that the last two dimensions # can be interpreted as a matrix. # Can you guess what the shape of the resulting determinants is? dets_sample = tf.matrix_determinant(samples) print(dets_sample.shape) # While we are at it, we might as well compute some summary stats. dets_mean = tf.reduce_mean(dets_sample) dets_var = tf.reduce_mean(tf.square(dets_sample)) - tf.square(dets_mean) # Evaluate the determinants and plot a histogram. # Note this style of evaluating a tensor. This allows you to compute more than # tensor at once in a session. with tf.Session() as sess: # This runs the computation det_vals, mean, var = sess.run((dets_sample, dets_mean, dets_var)) # Plot a beautiful histogram. plt.hist(det_vals, 50, normed=1, facecolor='green', alpha=0.75) plt.xlabel('Det(Unif(%d))' % n) plt.ylabel('Probability') plt.title(r'$\mathrm{Random\ Matrix\ Determinant\ Distribution:}\ \mu = %f,\ \sigma^2=%f$' % (mean, var)) plt.grid(True) plt.show() ``` In this example, we used some ops such as tf.reduce_mean and tf.square which we will discuss more later. # Maths Ops - There is a whole suite of commonly needed math ops built in. - We have already seen binary ops such as tf.add (addition) and tf.mul (multiplication). - Five can also be accessed as inline operators on tensors. - The inline form of the op allows you to e.g. write x + y instead of tf.add(x, y). | Name | Description | Inline form | | --- | --- | --- | | [tf.add](https://www.tensorflow.org/api_docs/python/tf/math/add) | Adds two tensors element wise | + | | [tf.subtract](https://www.tensorflow.org/api_docs/python/tf/math/subtract) | Subtracts two tensors element wise | - | | [tf.multiply](https://www.tensorflow.org/api_docs/python/tf/math/multiply) | Multiplies two tensors element wise | * | | [tf.divide](https://www.tensorflow.org/api_docs/python/tf/math/divide) | Divides two tensors element wise | / | | [tf.mod](https://www.tensorflow.org/api_docs/python/tf/math/floormod) | Computes the remainder of division element wise | % | - Note that the behaviour of "/" and "//" varies depending on python version and presence of `from __future__ import division`, to match how division behaves with ordinary python scalars. - The following table lists some more commonly needed functions: | Name | Description | | --- | --- | | [tf.exp](https://www.tensorflow.org/api_docs/python/tf/math/exp) | The exponential of the argument element wise. | | [tf.log](https://www.tensorflow.org/api_docs/python/tf/math/log) | The natural log element wise | | [tf.sqrt](https://www.tensorflow.org/api_docs/python/tf/math/sqrt) | Square root element wise | | [tf.round](https://www.tensorflow.org/api_docs/python/tf/math/round) | Rounds to the nearest integer element wise | | [tf.maximum](https://www.tensorflow.org/api_docs/python/tf/math/maximum) | Maximum of two tensors element wise. | # Matrix Ops * Matrices are rank 2 tensors. There is a suite of ops for doing matrix manipulations which we briefly discuss. | Name | Description | | --- | --- | | [tf.matrix_diag](https://www.tensorflow.org/api_docs/python/tf/linalg/diag) | Creates a tensor from its diagonal | | [tf.trace](https://www.tensorflow.org/api_docs/python/tf/linalg/trace) | Computes the sum of the diagonal elements of a matrix. | | [tf.matrix\_determinant](https://www.tensorflow.org/api_docs/python/tf/linalg/det) | Computes the determinant of a matrix (square only) | | [tf.matmul](https://www.tensorflow.org/api_docs/python/tf/linalg/matmul) | Multiplies two matrices | | [tf.matrix\_inverse](https://www.tensorflow.org/api_docs/python/tf/linalg/inv) | Computes the inverse of the matrix (square only) | ## Quiz: Normal Density - In the following mini-codelab, you are asked to compute the normal density using the ops you have seen so far. - You first generate a sample of points at which you will evaluate the density. - The points are generated using a normal distribution (need not be the same one whose density you are evaluating). - This is done by the function **generate\_normal\_draws** below. - The function **normal\_density\_at** computes the density at any given set of points. - You have to complete the code of these two functions so they work as expected. - Execute the code and check that the test passes. ### Hints - Recall that the normal density is given by $f(x) = \frac{1}{\sqrt{2\pi\sigma^2}} e^{-\frac{(x-\mu)^2}{2\sigma^2}}$ - Here $\mu$ is the mean of the distribution and $\sigma > 0$ is the standard deviation. - Pay attention to the data types mentioned in the function documentations. You should ensure that your implementations respect the data types stated. ``` #@title Mini-codelab: Compute the normal density. import numpy as np import numpy.testing as npt import scipy as sp def generate_normal_draws(shape, mean=0.0, stddev=1.0): """Generates a tensor drawn from a 1D normal distribution. Creates a constant tensor of the supplied shape whose elements are drawn independently from a normal distribution with the supplied parameters. Args: shape: An int32 tensor. Specifies the shape of the return value. mean: A float32 value. The mean of the normal distribution. stddev: A positive float32 value. The standard deviation of the distribution. Returns: A constant float32 tensor whose elements are normally distributed. """ # to-do: Complete this function. pass def normal_density_at(x, mean=0.0, stddev=1.0): """Computes the normal density at the supplied points. Args: x: A float32 tensor at which the density is to be computed. mean: A float32. The mean of the distribution. stddev: A positive float32. The standard deviation of the distribution. Returns: A float32 tensor of the normal density evaluated at the supplied points. """ # to-do: Complete this function. As a reminder, the normal density is # f(x) = exp(-(x-mu)^2/(2*stddev^2)) / sqrt(2 pi stddev^2). # The value of pi can be accessed as np.pi. pass def test(): mu, sd = 1.1, 2.1 x = generate_normal_draws([2, 3, 5], mean=mu, stddev=sd) pdf = normal_density_at(x) with tf.Session() as sess: x_v, y_v = sess.run((x, pdf)) npt.assert_array_equal(x_v.shape, [2,3,5], 'Shape is incorrect') norm = sp.stats.norm() npt.assert_allclose(y_v, norm.pdf(x_v), atol=1e-6) print ("All good!") test() #@title Mini-codelab Solution: Compute the normal density. Double-click to reveal import numpy as np import numpy.testing as npt import scipy as sp def generate_normal_draws(shape, mean=0.0, stddev=1.0): """Generates a tensor drawn from a 1D normal distribution. Creates a constant tensor of the supplied shape whose elements are drawn independently from a normal distribution with the supplied parameters. Args: shape: An int32 tensor. Specifies the shape of the return value. mean: A float32 value. The mean of the normal distribution. stddev: A positive float32 value. The standard deviation of the distribution. Returns: A constant float32 tensor whose elements are normally distributed. """ return tf.random_normal(shape=shape, mean=mean, stddev=stddev) def normal_density_at(x, mean=0.0, stddev=1.0): """Computes the normal density at the supplied points. Args: x: A float32 tensor at which the density is to be computed. mean: A float32. The mean of the distribution. stddev: A positive float32. The standard deviation of the distribution. Returns: A float32 tensor of the normal density evaluated at the supplied points. """ normalization = 1.0 / np.sqrt(2.0 * np.pi * stddev * stddev) return tf.exp(-tf.square((x - mean) / stddev) / 2.0) * normalization def test(): mu, sd = 1.1, 2.1 x = generate_normal_draws([2, 3, 5], mean=mu, stddev=sd) pdf = normal_density_at(x) with tf.Session() as sess: x_v, y_v = sess.run((x, pdf)) npt.assert_array_equal(x_v.shape, [2,3,5], 'Shape is incorrect') norm = sp.stats.norm() npt.assert_allclose(y_v, norm.pdf(x_v), atol=1e-6) print ("All good!") test() ``` # Logical And Comparison Ops - Tensorflow has the full complement of logical operators you would expect. - These are also overloaded so you can use their inline version. - The ops most frequently used are as follows: | Name | Description | Inline form | | --- | --- | --- | | [tf.equal](https://www.tensorflow.org/api_docs/python/tf/math/equal) | Element wise equality | **None** | | [tf.less](https://www.tensorflow.org/api_docs/python/tf/math/less) | Element wise less than | < | | [tf.less\_equal](https://www.tensorflow.org/api_docs/python/tf/math/less_equal) | Element wise less than or equal to | <= | | [tf.greater](https://www.tensorflow.org/api_docs/python/tf/math/greater) | Element wise greater than | > | | [tf.greater\_equal](https://www.tensorflow.org/api_docs/python/tf/math/greater_equal) | Element wise greater than or equal to | >= | | [tf.logical\_and](https://www.tensorflow.org/api_docs/python/tf/math/logical_and) | Element wise And | & | | [tf.logical\_or](https://www.tensorflow.org/api_docs/python/tf/math/logical_or) | Element wise Or | &#124; | - Note that tf.equal doesn't have an inline form. Comparing two tensors with == will use the default python comparison. It will **not** call tf.equal. ## Note about Broadcasting - All the binary operators described above expect their operands to be of the same shape up to broadcasting. - Broadcasting attempts to find a larger shape that would render the two arguments compatible. - Tensorflow's broadcasting behaviour is like Numpy's. - Example: [ 1, 2, 3 ] > 0. The LHS is tensor of shape [3] while the right hand side can be promoted to [ 0, 0, 0] which makes it compatible. - More non trivial example: tf.equal([[1,2], [2, 3]], [2,3]). The LHS is shape [2,2] right is shape [2]. The RHS gets broadcasted so that it looks like [[2,3],[2,3]] and the comparison is performed element wise. - These are the most common case and we will make extensive use of this below. - The full set of rules for broadcasting are available [here](https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html). ``` #@title Comparison Ops Examples a = tf.constant([1.0, 1.0]) b = tf.constant([2.0, 2.0]) c = tf.constant([1.0, 2.0]) # Less-than op. Tests if the first argument is less than the second argument # component wise. a_less_than_b = a < b b_greater_than_c = b > c d = 3.0 # Simple broadcasting in action a_less_than_d = a < d # More complex broadcasting a2 = tf.constant([[1,2],[2,3]]) b2 = tf.constant([1,3]) c2 = tf.equal(a2, b2) # Note that there is no inline form for tf.equals. If you do b == c, you will # not get what you think you might. b_equal_to_c = tf.equal(b, c) with tf.Session() as sess: # Note we don't evaluate 'd' because it is not a tensor inputs = sess.run([a, b, c]) outputs = sess.run([a_less_than_b, b_greater_than_c, a_less_than_d, b_equal_to_c]) print "Inputs:\na: %s\nb: %s\nc: %s\nd: %s\n" % (tuple(inputs) + (d,)) print "Outputs:\na < b: %s\nb > c: %s\na < d: %s\nb == c: %s\n" % tuple(outputs) with tf.Session() as sess: print "Complex Broadcasting" print "%s == %s => %s" % sess.run((a2, b2, c2)) ``` # Aggregations and Scans Most of the ops we have seen so far, act on the input tensors in an element wise manner. Another important set of operators allow you to do aggregations on a whole tensor as well as scan the tensor. - Aggregations (or reductions) act on a tensor and produce a reduced dimension tensor. The main ops here are | Name | Description | | --- | --- | | [tf.reduce\_sum](https://www.tensorflow.org/api_docs/python/tf/math/reduce_sum) | Sum of elements along all or some dimensions. | | [tf.reduce\_mean](https://www.tensorflow.org/api_docs/python/tf/math/reduce_mean) | Average of elements along all or some dimensions. | | [tf.reduce\_min](https://www.tensorflow.org/api_docs/python/tf/math/reduce_min) | Minimum of elements along all or some dimensions. | | [tf.reduce\_max](https://www.tensorflow.org/api_docs/python/tf/math/reduce_max) | Maximum of elements along all or some dimensions. | - and for boolean tensors only | Name | Description | | --- | --- | | [tf.reduce\_any](https://www.tensorflow.org/api_docs/python/tf/math/reduce_any) | Result of logical OR along all or some dimensions. | | [tf.reduce\_all](https://www.tensorflow.org/api_docs/python/tf/math/reduce_all) | Result of logical AND along all or some dimensions. | - Scan act on a tensor and produce a tensor of the same dimension. | Name | Description | | --- | --- | | [tf.cumsum](https://www.tensorflow.org/api_docs/python/tf/math/cumsum) | Cumulative sum of elements along an axis. | | [tf.cumprod](https://www.tensorflow.org/api_docs/python/tf/math/cumprod) | Cumulative product of elements along an axis. | ## Codelab: Estimating $\pi$ In this short codelab, we will use an age old method to estimate the value of $\pi$. The idea is very simple: Throw darts at a square and check what fraction lies inside the inscribed circle (see diagram). ``` #@title %%html <svg width="210" height="210"> <rect x1="0" y1="0" width="200" height="200" stroke="blue" fill="red" fill-opacity="0.5" stroke-opacity="0.8"/> <circle cx="100" cy="100" r="99" fill="green" stroke="rgba(0,20,0,0.7)" stroke-width="2"/> <circle cx="188" cy="49" r="3" fill="blue" stroke="rgba(0,20,0,0.7)" stroke-width="2"/> <circle cx="113" cy="130" r="3" fill="blue" stroke="rgba(0,20,0,0.7)" stroke-width="2"/> <circle cx="44" cy="78" r="3" fill="blue" stroke="rgba(0,20,0,0.7)" stroke-width="2"/> <circle cx="116" cy="131" r="3" fill="blue" stroke="rgba(0,20,0,0.7)" stroke-width="2"/> <circle cx="189" cy="188" r="3" fill="blue" stroke="rgba(0,20,0,0.7)" stroke-width="2"/> <circle cx="126" cy="98" r="3" fill="blue" stroke="rgba(0,20,0,0.7)" stroke-width="2"/> <circle cx="18" cy="42" r="3" fill="blue" stroke="rgba(0,20,0,0.7)" stroke-width="2"/> <circle cx="146" cy="62" r="3" fill="blue" stroke="rgba(0,20,0,0.7)" stroke-width="2"/> <circle cx="13" cy="139" r="3" fill="blue" stroke="rgba(0,20,0,0.7)" stroke-width="2"/> <circle cx="157" cy="94" r="3" fill="blue" stroke="rgba(0,20,0,0.7)" stroke-width="2"/> <line x1="100" y1="100" x2="170" y2="170" stroke="black"/> <text x="144" y="130" text-anchor="middle"><tspan baseline-shift="sub" font-size="normal">1</tspan></text> </svg> ``` The steps to estimate it are: * Generate $n$ samples of pairs of uniform variates $(x, y)$ drawn from $[-1, 1]$. * Compute the fraction $f_n$ that lie inside the unit circle, i.e. have $x^2+y^2 \leq 1$. * Estimate $\pi \approx = 4 f_n$, because * The area of the unit circle is $\pi$ * The area of the rectangle is $4$ * $f_{\infty} = \frac{\pi}{4}$. Your task is to complete the functions **generate_sample** and **compute_fraction** below. They correspond to the first and the second steps described above. The last step is already done for you in the function estimate_pi. ``` #@title Codelab: Estimating Pi import numpy as np def generate_sample(size): """Sample a tensor from the uniform distribution. Creates a tensor of shape [size, 2] containing independent uniformly distributed numbers drawn between [-1.0, 1.0]. Args: size: A positive integer. The number of samples to generate. Returns: A tensor of data type tf.float64 and shape [size, 2]. """ raise NotImplementedError() def compute_fraction(sample): """The fraction of points inside the unit circle. Computes the fraction of points that satisfy sample[0]^2 + sample[1]^2 <= 1. Args: sample: A float tensor of shape [n, 2]. Returns: The fraction of n that lie inside the unit circle. """ raise NotImplementedError() def estimate_pi(num_samples): sample = generate_sample(num_samples) f_t = compute_fraction(sample) with tf.Session() as sess: f = sess.run(f_t) f *= 4.0 error = np.abs(np.pi - f) / np.pi print ("Estimate: %.5f, Error: %.3f%%" % (f, error * 100.)) estimate_pi(100000) #@title Codelab Solution: Estimating Pi. Double click to reveal import tensorflow as tf import numpy as np def generate_sample(size): """Sample a tensor from the uniform distribution. Creates a tensor of shape [size, 2] containing independent uniformly distributed numbers drawn between [-1.0, 1.0]. Args: size: A positive integer. The number of samples to generate. Returns: A tensor of data type tf.float64 and shape [size, 2]. """ return tf.random_uniform(shape=[size, 2], minval=-1.0, maxval=1.0, dtype=tf.float64) def compute_fraction(sample): """The fraction of points inside the unit circle. Computes the fraction of points that satisfy sample[0]^2 + sample[1]^2 <= 1. Args: sample: A float tensor of shape [n, 2]. Returns: The fraction of n that lie inside the unit circle. """ sq_distance = tf.reduce_sum(tf.square(sample), 1) in_circle = tf.to_float(sq_distance <= 1.0) return tf.reduce_mean(in_circle) def estimate_pi(num_samples): sample = generate_sample(num_samples) f_t = compute_fraction(sample) with tf.Session() as sess: f = sess.run(f_t) f *= 4.0 error = np.abs(np.pi - f) / np.pi print ("Estimate: %.5f, Error: %.3f%%" % (f, error * 100.)) estimate_pi(100000) #@title Aggregation/Scan examples from pprint import pprint # Generate a tensor of gamma-distributed values and aggregate them x = tf.random_gamma([100, 10], 0.5) # Adds all the elements x_sum = tf.reduce_sum(x) # Adds along the first axis. x_sum_0 = tf.reduce_sum(x, 0) # Maximum along the first axis x_max_0 = tf.reduce_max(x, 0) # to-do: For this y, write an op to compute the cumulative sum # and evaluate it. with tf.Session() as sess: print("Total Sum: %s\n" % sess.run(x_sum)) print("Partial Sum: %s\n" % sess.run(x_sum_0)) print("Maximum: %s\n" % sess.run(x_max_0)) ``` # Mixing and Locating Elements We often need to be able to mix two tensors based on the values in another tensor. The where_v2 op is particularly useful in this context. It has two major uses: - **tf.where_v2(Condition, T, F)**: Allows you to mix and match elements of two tensors based on a boolean tensor. - All tensors must be of the same shape (or broadcastable to same). - T and F must have the same data type. - Picks elements of T where Condition is true and F where Condition is False. - Example: tf.where_v2([True, False], [1, 2], [3, 4]) $\rightarrow$ [1, 4]. - **tf.where_v2(tensor)**: Alternatively, if T and F aren't supplied, then the op returns locations of elements which are true. - Example: tf.where_v2([1, 2, 3, 4] > 2) $\rightarrow$ [[2], [3]] ### Example: Let's see them in action. We will create tensor of integers between 1 and 50 and set all multiples of 3 to 0. ``` import numpy as np # Create a tensor with numbers between 1 and 50 nums = tf.constant(np.arange(1, 51)) # tf.mod(x, y) gives the remainder of the division x / y. # Find all multiples of 3. to_replace = tf.equal(nums % 3, 0) # First form of where_v2: if to_replace is true, tf.where_v2 picks the element # from the first tensor and otherwise, from the second tensor. result = tf.where_v2(to_replace, tf.zeros_like(nums), nums) with tf.Session() as session: print session.run(result) # Now let's confirm that we did indeed set the right numbers to zero. # This is where the second form of tf.where_v2 helps us. It will find all the # indices where its first argument is true. # Keep in mind that tensors are zero indexed (i.e. the first element has # index 0) so we will need to add a 1 to the result. zero_locations = tf.where_v2(tf.equal(result, 0)) + 1 with tf.Session() as session: print np.transpose(session.run(zero_locations)) ``` # Slicing and Joining There are a number of ops which allow you to take parts of a tensor as well join multiple tensors together. Before we discuss those ops, let's look at how we can use the usual array indexing to access parts of a tensor. ## Indexing * Even though tensors are not arrays in the usual sense, you can still index into them. * The indexing produces tensors which may be evaluated or consumed further in the usual way. * Indexing is a short cut for writing a explicit op (just like you can write x + y instead of tf.add(x, y)). * Tensorflow's indexing works similarly to Numpy's. ``` #@title Indexing x = tf.constant([[1, 2, 3], [4, 5, 6]]) # Get a tensor containing only the first component of x. x_0 = x[0] # A tensor of the first two elements of the first row. x_0_12 = x[0, 0:2] with tf.Session() as session: print("x_0: %s" % session.run(x_0)) print("x_0_12: %s" % session.run(x_0_12)) # You can also do this more generally with the tf.slice op which is useful # if the indices you want are themselves tensors. x_slice = tf.slice(x, [0, 0], [1, 2]) print("With tf.slice: %s" % session.run(x_slice)) ``` Coming back to the ops that are available for tailoring tensors, here are a few of them | Name | Description | | --- | --- | | [tf.slice](https://www.tensorflow.org/api_docs/python/tf/slice) | Take a contiguous slice out of a tensor. | | [tf.split](https://www.tensorflow.org/api_docs/python/tf/split) | Split a tensor into equal pieces along a dimension | | [tf.tile](https://www.tensorflow.org/api_docs/python/tf/tile) | Tile a tensor by copying and concatenating it | | [tf.pad](https://www.tensorflow.org/api_docs/python/tf/pad) | Pads a tensor | | [tf.concat](https://www.tensorflow.org/api_docs/python/tf/concat) | Concatenate tensors along a dimension | | [tf.stack](https://www.tensorflow.org/api_docs/python/tf/stack) | Stacks n tensors of rank R into one tensor of rank R+1 | Let's briefly look at these ops in action. ``` #@title Slicing and Joining Examples with tf.Session() as sess: x = tf.constant([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # Slice takes a starting index somewhere in the tensor and a size in each # dimension that you want to keep. It allows you to pass tensors for the start # position and the sizes. Note that the shape of the result is same as size arg. start_index = tf.constant([1, 1]) size = tf.constant([1, 2]) x_slice = tf.slice(x, start_index, size) print "tf.slice" print("x[1:2, 1:3] = %s" % sess.run(x_slice)) # Split splits the tensor along any given dimension. The return value is a list # of tensors (and not just one tensor). pieces = tf.split(x, 3, 0) print "\ntf.split" print(sess.run(pieces)) # Tile makes a bigger tensor out of your tensor by tiling copies of it in the # dimensions you specify. y = tf.constant([[1, 2], [3, 4]]) tiled = tf.tile(y, [2, 2]) print "\ntf.tile" print("Y:\n%s\n" % sess.run(y)) print("Y tiled twice in both dims:\n%s\n" % sess.run(tiled)) # Pad has a few modes of operation but the simplest one is where you pad a # tensor with zeros (the default mode). You specify the amount of padding you # want at the top and at the bottom of each dimension. In this example, we will # pad y defined above with zero asymmetrically padded = tf.pad(y, paddings=[[1, 2], [3, 4]]) print "\ntf.pad" print("Y with padding:\n%s\n" % sess.run(padded)) # Concat simply concatenates two tensors of the same rank along some axis. x = tf.constant([[1], [2]]) y = tf.constant([[3], [4]]) x_y = tf.concat([x, y], 0) print "\ntf.concat" print("Concat X and Y:\n%s\n" % sess.run(x_y)) # Pack is quite useful when you have a bunch of tensors and you want to join # them into a higher rank tensor. Let's take the same x and y as above. stacked = tf.stack([x, y], axis=0) print "\ntf.stacked" print("Stacked X and Y:\n%s\n" % sess.run(stacked)) print("Shape X: %s, Shape Y: %s, Shape of Stacked_0: %s" % (x.shape, y.shape, stacked.shape)) ``` # Codelab: Distribution of Bernoulli Random Matrices It's time to flex those tensorflow muscles. Using the ops we have seen so far, let us reconsider the distribution of the determinant. As it happens, mathematicians focus a lot more on random matrices whose entries are either -1 or 1. They worry about questions regarding the singularity of a random Bernoulli matrix. In this exercise, you are asked to generate random matrices whose entries are either +1 or -1 with probability p for +1 (and 1-p for -1). The function *bernoulli_matrix_sample* needs to return a tensor of such matrices. Once that is done, you can run the rest of the code to see the plot of the empirical distribution for the determinant. ``` #@title Imports And Setup: Run Me First! import numpy as np import matplotlib.pyplot as plt import tensorflow as tf import seaborn as sns sns.set(color_codes=True) def plot_det_distribution(sample_tensor, p=0.5): """Plots the distribution of the determinant of the supplied tensor. Computes the determinant of the supplied sample of matrices and plots its histogram. Args: sample_tensor: A tensor of shape [sample_size, n, n]. p: The probability of generating a +1. Used only for display. Returns: The mean and the variance of the determinant sample as a tuple. """ dets_sample = tf.matrix_determinant(sample_tensor) dets_uniq, _, counts = tf.unique_with_counts(dets_sample) dets_mean = tf.reduce_mean(dets_sample) dets_var = tf.reduce_mean(tf.square(dets_sample)) - tf.square(dets_mean) with tf.Session() as sess: det_vals, count_vals, mean, var = sess.run( (dets_uniq, counts, dets_mean, dets_var)) num_bins = min(len(det_vals), 50) plt.hist(det_vals, num_bins, weights=count_vals, normed=1, facecolor='green', alpha=0.75) plt.xlabel('Det(Bern(p=%.2g))' % p) plt.ylabel('Probability') plt.title(r'$\mathrm{Determinant\ Distribution:}\ \mu = %.2g,\ \sigma^2=%.2g$' % (mean, var)) plt.grid(True) plt.show() return mean, var #@title Codelab: Bernoulli Matrix Distribution # NB: Run the Setup and Imports above first. def bernoulli_matrix_sample(n, size, p=0.5): """Generate a sample of matrices with entries +1 or -1. Generates matrices whose elements are independently drawn from {-1, 1} with probability {1-p, p} respectively. Args: n: The dimension of the (square) matrix to generate. An integer. size: The number of samples to generate. p: The probability of drawing +1. Returns: A tf.Tensor object of shape [size, n, n] and data type float64. """ # Tensorflow provides a number of distributions to generate random tensors. # This includes uniform, normal and gamma. The Tensorflow API docs are an # excellent reference for this and many other topics. # https://www.tensorflow.org/api_docs/python/tf/random # # Unfortunately, however, there is no bernoulli sampler in base tensorflow. # There is one in one of the libraries but we will discuss that later. # For now, you need to use a uniform sampler to generate the desired sample. gen_shape = [size, n, n] draws = tf.random_uniform(shape=gen_shape, dtype=tf.float64) ones = tf.ones(shape=gen_shape) raise NotImplementedError() prob_1 = 0.5 sample = bernoulli_matrix_sample(5, 1000000, prob_1) plot_det_distribution(sample, prob_1) #@title Codelab Solution: Bernoulli Matrix Distribution - Double click to reveal # NB: Run the Setup and Imports above first. def bernoulli_matrix_sample(n, size, p=0.5): """Generate a sample of matrices with entries +1 or -1. Generates matrices whose elements are independently drawn from {-1, 1} with probability {1-p, p} respectively. Args: n: The dimension of the (square) matrix to generate. An integer. size: The number of samples to generate. p: The probability of drawing +1. Returns: A tf.Tensor object of shape [size, n, n] and data type float64. """ # Tensorflow provides a number of distributions to generate random tensors. # This includes uniform, normal and gamma. The Tensorflow API docs are an # excellent reference for this and many other topics. # https://www.tensorflow.org/api_docs/python/tf/random # # Unfortunately, however, there is no bernoulli sampler in base tensorflow. # There is one in one of the libraries but we will discuss that later. # For now, you need to use a uniform sampler to generate the desired sample. gen_shape = [size, n, n] ones = tf.ones(shape=gen_shape) draws = tf.random_uniform(shape=gen_shape, dtype=tf.float64) return tf.where(draws <= p, ones, -ones) prob_1 = 0.5 sample = bernoulli_matrix_sample(5, 1000000, prob_1) plot_det_distribution(sample, prob_1) ``` # Control Flow ## tf.cond In Python (like in most imperative languages), we have the *if-else* construct which allows us to do different things based on the value of some variable. The equivalent construct in Tensorflow is the **tf.cond** op. Consider the following (very contrived) example: ``` # Create a vector of 10 iid normal variates. x = tf.random_normal([10], name="x") # If the average of the absolute values of x is greater than 1, we # return a tensor of 0's otherwise a tensor of 1's # Note that the predicate must return a boolean scalar. w = tf.cond(tf.reduce_mean(tf.abs(x)) > 1.0, lambda: tf.zeros_like(x, name="Zeros"), lambda: tf.ones_like(x, name="Ones"), name="w") w.eval(session=tf.Session()) ``` Some things to note here: - The predicate must be a scalar tensor (or a value convertible to a scalar tensor). - The two branches are provided as a Python function taking no arguments and returning one or more tensors - Both branches must return the same number and type of tensors. - The evaluation model is lazy. The branch not taken is not evaluated. # Inputting Data So far we have used data that we generated on the fly. Real world problems typically come with external data sources. If the data set is of small to medium size, we can load it into the python session using the usual file APIs. If we are using a Tensorflow pipeline to process this data, we need to feed this data in somehow. Tensorflow provides a couple of mechanisms to do this. The simplest way is through the feeding mechanism which we consider first. ## Feed Mechanism We have seen that Tensorflow computation is basically graph evaluation. Tensorflow allows you to "cut" the graph at some edge and replace the tensor on that edge with some value that you can "feed". This can be done with any tensor, whether they are constants or variables. You do this by passing an override value for that tensor when doing Session.run() through an argument called "feed_dict". Let's consider an example ``` import scipy as sp tf.reset_default_graph() # Build a simple graph. x = tf.constant(4.0) # y = √x y = tf.sqrt(x) # z = x^2 z = tf.square(x) # w = √x + x^2 w = y + z with tf.Session() as sess: print("W by default: %s\n" % sess.run(w)) # By default y should evaluate to sqrt(4) = 2. # We cut that part of the graph and set y to 10. print("(W|y=10) = %s" % sess.run(w, feed_dict={y: 10.0})) # You can also replace z at the same time. print("(W|y=10, z=1) = %s" % sess.run(w, feed_dict={y: 10.0, z: 1.0})) # At this point, you can generate the values to be fed in any manner # you like, including calling functions. print("(W|y=random,z=1) = %s" % sess.run(w, feed_dict={y: sp.rand(), z: 1.0})) # What you cannot do, however, is supply a value which would be inconsistent # with the expected shape or type of the original tensor. This is true even # if you stay consistent with the relevant bit of the graph. # In this (non-)example, we attempt to replace both y and z with a vector # and Tensorflow doesn't like that. #print("(W|y=[random],z=[1])=%s" % sess.run(w,feed_dict={y: [0.0], z: [1.0]})) ``` * So we see that while we can replace the value of any tensor, we cannot change the shape or the type of the tensor. * The feed value must be concrete object and not a tensor. So, python lists, numpy arrays or scalars are OK. ## Placeholders * The feed mechanism is a convenient, if somewhat *ad hoc* way to input data. * While you can replace anything, it is not usually a good idea to replace arbitrary tensors except for debugging. * Tensorflow provides **tf.placeholder** objects whose only job is to be fed data. * They can be bound to data only at run time. * They are defined by their shape and data type. At run time they expect to be fed a concrete object of that shape and type. * It is an error to not supply a required placeholder (though there is a way to specify defaults). Let us see them in action: ``` import scipy as sp # Define a placeholder. You need to define its type and shape and these will be # enforced when you supply the data. x = tf.placeholder(tf.float32, shape=(10, 10)) # A square matrix y = tf.matrix_determinant(x) with tf.Session() as sess: value_to_feed = sp.rand(10, 10) print(sess.run(y, feed_dict={x: value_to_feed})) # You can check that if you do not feed the value of x, you get an error. #sess.run(y) ## InvalidArgumentError ``` ## Shapes Revisited ### The Problem * Placeholders are commonly used as a slot where you can enter your data for training. * Data is typically supplied in batches suitable for use with stochastic gradient descent or some variant thereof. * Pretty inconvenient to hard code the batch size. * But placeholder definition requires a shape! ### The Solution * Allow shapes which are potentially unknown at graph building time but will be known at run time. * This is done by setting one or more dimensions in a shape to None. * For example, a shape of [None, 4] indicates that we plan to have a matrix with 4 columns but some unknown number of rows. * An obvious point: constants cannot be defined with unknown shape. Let's look at some examples with partially specified shapes for placeholders. ``` import tensorflow as tf # Defines a placeholder with unknown number of rows and 2 columns. x = tf.placeholder(tf.float32, shape=[None, 2]) # You can do almost everything that you can do with a fully specified shape # tensor. Here we compute the sum of squares of elements of x. y = tf.reduce_sum(x * x) with tf.Session() as sess: # When evaluating, you can specify any value of x compatible with the shape # A 2 x 2 matrix is OK print("2x2 input: %s" % sess.run(y, feed_dict={x: [[1, 2], [3, 4]]})) # A 3 x 2 matrix is also OK print("3x2 input: %s" % sess.run(y, feed_dict={x: [[1, 2], [3, 4], [5, 6]]})) ``` * This seems absolutely awesome, so is there a downside to this? * Yes! * Unspecified shapes allow you to write ops which may fail at run time even though they seem OK at graph building time as the following example demonstrates. ``` # Continuation of the previous example. Run that first. # This seems OK because while a shape of [None, 2] is not always square, it # could be square. So Tensorflow is OK with it. z = tf.matrix_determinant(x * x) with tf.Session() as sess: # With a 2x2 matrix we have no problem evaluating z print("Det([2x2]): %s" % sess.run(z, feed_dict={x:[[1, 2], [3, 4]]})) # But with 3x2 matrix we obviously get an error #print("Det([3x2]): %s" % sess.run(z, feed_dict={x:[[1, 2], [3, 4], [1, 4]]})) ``` ### tf.shape vs tensor.get_shape Earlier we encountered two different ways to get the shape of a tensor. Now we can see the difference between these two. * **tensor.get_shape()**: Returns the statically determined shape of a tensor. It is possible that this is only partially known. * **tf.shape(tensor)**: Returns the **actual** fully specified shape of the tensor but is guaranteed to be known only at run time. Let's see the difference in action: ``` x = tf.placeholder(tf.int32, [None, None]) # This is a tensor so we have to evaluate it to get its value. x_s = tf.shape(x) with tf.Session() as sess: print("Static shape of x: %s" % x.get_shape()) print("Runtime shape of x: %s" % sess.run(x_s, feed_dict={x: [[1],[2]]})) ``` ## Reading Files * While data can be fed in through placeholders, it would be still more efficient if we could just ask Tensorflow to directly read from data files. * There is a large, well developed framework in TF to do this. * To get an idea of the steps involved, tensorflow.org has this to say about it: > A typical pipeline for reading records from files has the following stages: > 1. The list of filenames 1. Optional filename shuffling 1. Optional epoch limit 1. Filename queue 1. A Reader for the file format 1. A decoder for a record read by the reader 1. Optional preprocessing 1. Example queue * However, if you are not setting up a large scale distributed tensorflow job, you can get away with using standard python IO along with placeholders. In the following example, we read a small csv StringIO object using numpy and bind the data to a placeholder. ``` # We'll use StringIO (to avoid external file handling in colab) to fake a CSV # file containing two integer columns labeled x and y. In reality, you'd be # using something like # with open("path/to/csv_file") as csv_file: csv_file = StringIO(u"""x,y 0,1 1,2 2,4 3,8 4,16 5,32""") x = tf.placeholder(tf.int32, shape=(None)) y = tf.placeholder(tf.int32, shape=(None)) z = x + y # There are many ways to read the data in using standard python utilities. # Here we use the numpy method to directly read into a numpy array. data = np.genfromtxt(csv_file, dtype='int32', delimiter=',', skip_header=True) print("x: %s" % data[:, 0]) print("y: %s" % data[:, 1]) # Now we can evaluate the tensor z using the loaded data to replace the # placeholders x and y with tf.Session() as sess: print("z: %s" % sess.run(z, feed_dict={x: data[:,0], y: data[:, 1]})) ```
github_jupyter
# Google form analysis tests ## Table of Contents ['Google form analysis' functions checks](#funcchecks) [Google form loading](#gformload) - [Selection of a question](#selquest) - [Selection of a user's answers](#selusans) [checking answers](#checkans) [comparison of checkpoints completion and answers](#compcheckans) [answers submitted through time](#ansthrutime) [merge English and French answers](#mergelang) ``` %run "../Functions/2. Google form analysis.ipynb" # Localplayerguids of users who answered the questionnaire (see below). # French #localplayerguid = 'a4d4b030-9117-4331-ba48-90dc05a7e65a' #localplayerguid = 'd6826fd9-a6fc-4046-b974-68e50576183f' #localplayerguid = 'deb089c0-9be3-4b75-9b27-28963c77b10c' #localplayerguid = '75e264d6-af94-4975-bb18-50cac09894c4' #localplayerguid = '3d733347-0313-441a-b77c-3e4046042a53' # English localplayerguid = '8d352896-a3f1-471c-8439-0f426df901c1' #localplayerguid = '7037c5b2-c286-498e-9784-9a061c778609' #localplayerguid = '5c4939b5-425b-4d19-b5d2-0384a515539e' #localplayerguid = '7825d421-d668-4481-898a-46b51efe40f0' #localplayerguid = 'acb9c989-b4a6-4c4d-81cc-6b5783ec71d8' #localplayerguid = devPCID5 ``` ## 'Google form analysis' functions checks <a id=funcchecks /> ### copy-paste for unit tests (userIdThatDidNotAnswer) (userId1AnswerEN) (userIdAnswersEN) (userId1ScoreEN) (userIdScoresEN) (userId1AnswerFR) (userIdAnswersFR) (userId1ScoreFR) (userIdScoresFR) (userIdAnswersENFR) #### getAllResponders ``` len(getAllResponders()) ``` #### hasAnswered ``` userIdThatDidNotAnswer in gform['userId'].values, hasAnswered( userIdThatDidNotAnswer ) assert(not hasAnswered( userIdThatDidNotAnswer )), "User has NOT answered" assert(hasAnswered( userId1AnswerEN )), "User HAS answered" assert(hasAnswered( userIdAnswersEN )), "User HAS answered" assert(hasAnswered( userId1AnswerFR )), "User HAS answered" assert(hasAnswered( userIdAnswersFR )), "User HAS answered" assert(hasAnswered( userIdAnswersENFR )), "User HAS answered" ``` #### getAnswers ``` assert (len(getAnswers( userIdThatDidNotAnswer ).columns) == 0),"Too many answers" assert (len(getAnswers( userId1AnswerEN ).columns) == 1),"Too many answers" assert (len(getAnswers( userIdAnswersEN ).columns) >= 2),"Not enough answers" assert (len(getAnswers( userId1AnswerFR ).columns) == 1),"Not enough columns" assert (len(getAnswers( userIdAnswersFR ).columns) >= 2),"Not enough answers" assert (len(getAnswers( userIdAnswersENFR ).columns) >= 2),"Not enough answers" ``` #### getCorrections ``` assert (len(getCorrections( userIdThatDidNotAnswer ).columns) == 0),"Too many answers" assert (len(getCorrections( userId1AnswerEN ).columns) == 2),"Too many answers" assert (len(getCorrections( userIdAnswersEN ).columns) >= 4),"Not enough answers" assert (len(getCorrections( userId1AnswerFR ).columns) == 2),"Too many answers" assert (len(getCorrections( userIdAnswersFR ).columns) >= 4),"Not enough answers" assert (len(getCorrections( userIdAnswersENFR ).columns) >= 4),"Not enough answers" ``` #### getScore ``` assert (len(pd.DataFrame(getScore( userIdThatDidNotAnswer ).values.flatten().tolist()).values.flatten().tolist()) == 0),"Too many answers" score = getScore( userId1AnswerEN ) #print(score) assert ( (len(score.values.flatten()) == 3) and score[answerTemporalities[0]][0][0] == 0 ),"Incorrect score" ``` # code to explore scores for userId in gform['userId'].values: score = getScore( userId ) pretestScore = score[answerTemporalities[0]][0] posttestScore = score[answerTemporalities[1]][0] if len(pretestScore) == 1 and len(posttestScore) == 0 and 0 != pretestScore[0]: #gform[gform['userId']] print(userId + ': ' + str(pretestScore[0])) ``` score = getScore( userIdAnswersEN ) #print(score) assert ( (len(score.values.flatten()) == 3) and score[answerTemporalities[0]][0][0] == 5 and score[answerTemporalities[1]][0][0] == 25 ),"Incorrect score" score = getScore( userId1AnswerFR ) #print(score) assert ( (len(score.values.flatten()) == 3) and score[answerTemporalities[0]][0][0] == 23 ),"Incorrect score" score = getScore( userIdAnswersFR ) #print(score) assert ( (len(score.values.flatten()) == 3) and score[answerTemporalities[0]][0][0] == 15 and score[answerTemporalities[1]][0][0] == 26 ),"Incorrect score" score = getScore( userIdAnswersENFR ) #print(score) assert ( (len(score.values.flatten()) == 3) and score[answerTemporalities[0]][0][0] == 4 and score[answerTemporalities[1]][0][0] == 13 ),"Incorrect score" ``` #### getValidatedCheckpoints ``` objective = 0 assert (len(getValidatedCheckpoints( userIdThatDidNotAnswer )) == objective),"Incorrect number of answers" objective = 1 assert (len(getValidatedCheckpoints( userId1AnswerEN )) == objective),"Incorrect number of answers" assert (getValidatedCheckpoints( userId1AnswerEN )[0].equals(validableCheckpoints)) \ , "User has validated everything" objective = 2 assert (len(getValidatedCheckpoints( userIdAnswersEN )) == objective),"Incorrect number of answers" objective = 3 assert (len(getValidatedCheckpoints( userIdAnswersEN )[0]) == objective) \ , "User has validated " + objective + " chapters on first try" objective = 1 assert (len(getValidatedCheckpoints( userId1AnswerFR )) == objective),"Incorrect number of answers" assert (getValidatedCheckpoints( userId1AnswerFR )[0].equals(validableCheckpoints)) \ , "User has validated everything" objective = 2 assert (len(getValidatedCheckpoints( userIdAnswersFR )) == objective),"Incorrect number of answers" objective = 5 assert (len(getValidatedCheckpoints( userIdAnswersFR )[1]) == objective) \ , "User has validated " + objective + " chapters on second try" objective = 2 assert (len(getValidatedCheckpoints( userIdAnswersENFR )) == objective),"Incorrect number of answers" objective = 5 assert (len(getValidatedCheckpoints( userIdAnswersENFR )[1]) == objective) \ , "User has validated " + objective + " chapters on second try" ``` #### getNonValidated ``` getValidatedCheckpoints( userIdThatDidNotAnswer ) pd.Series(getValidatedCheckpoints( userIdThatDidNotAnswer )) type(getNonValidated(pd.Series(getValidatedCheckpoints( userIdThatDidNotAnswer )))) validableCheckpoints assert(getNonValidated(getValidatedCheckpoints( userIdThatDidNotAnswer ))).equals(validableCheckpoints), \ "incorrect validated checkpoints: should contain all checkpoints that can be validated" testSeries = pd.Series( [ '', # 7 '', # 8 '', # 9 '', # 10 'tutorial1.Checkpoint00', # 11 'tutorial1.Checkpoint00', # 12 'tutorial1.Checkpoint00', # 13 'tutorial1.Checkpoint00', # 14 'tutorial1.Checkpoint02', # 15 'tutorial1.Checkpoint01', # 16 'tutorial1.Checkpoint05' ] ) assert(getNonValidated(pd.Series([testSeries]))[0][0] == 'tutorial1.Checkpoint13'), "Incorrect non validated checkpoint" ``` #### getNonValidatedCheckpoints ``` getNonValidatedCheckpoints( userIdThatDidNotAnswer ) getNonValidatedCheckpoints( userId1AnswerEN ) getNonValidatedCheckpoints( userIdAnswersEN ) getNonValidatedCheckpoints( userId1AnswerFR ) getNonValidatedCheckpoints( userIdAnswersFR ) getNonValidatedCheckpoints( userIdAnswersENFR ) ``` #### getValidatedCheckpointsCounts ``` getValidatedCheckpointsCounts(userIdThatDidNotAnswer) getValidatedCheckpointsCounts(userId1AnswerEN) getValidatedCheckpointsCounts(userIdAnswersEN) getValidatedCheckpointsCounts(userId1ScoreEN) getValidatedCheckpointsCounts(userIdScoresEN) getValidatedCheckpointsCounts(userId1AnswerFR) getValidatedCheckpointsCounts(userIdAnswersFR) getValidatedCheckpointsCounts(userId1ScoreFR) getValidatedCheckpointsCounts(userIdScoresFR) getValidatedCheckpointsCounts(userIdAnswersENFR) ``` #### getNonValidatedCheckpointsCounts ``` getNonValidatedCheckpointsCounts(userIdThatDidNotAnswer) getNonValidatedCheckpointsCounts(userId1AnswerEN) getNonValidatedCheckpointsCounts(userIdAnswersEN) getNonValidatedCheckpointsCounts(userId1ScoreEN) getNonValidatedCheckpointsCounts(userIdScoresEN) getNonValidatedCheckpointsCounts(userId1AnswerFR) getNonValidatedCheckpointsCounts(userIdAnswersFR) getNonValidatedCheckpointsCounts(userId1ScoreFR) getNonValidatedCheckpointsCounts(userIdScoresFR) getNonValidatedCheckpointsCounts(userIdAnswersENFR) ``` #### getAllAnswerRows ``` aYes = ["Yes", "Oui"] aNo = ["No", "Non"] aNoIDK = ["No", "Non", "I don't know", "Je ne sais pas"] # How long have you studied biology? qBiologyEducationLevelIndex = 5 aBiologyEducationLevelHigh = ["Until bachelor's degree", "Jusqu'à la license"] aBiologyEducationLevelLow = ['Until the end of high school', 'Until the end of middle school', 'Not even in middle school'\ "Jusqu'au bac", "Jusqu'au brevet", 'Jamais'] # Have you ever heard about BioBricks? qHeardBioBricksIndex = 8 # Have you played the current version of Hero.Coli? qPlayedHerocoliIndex = 10 qPlayedHerocoliYes = ['Yes', 'Once', 'Multiple times', 'Oui', 'De nombreuses fois', 'Quelques fois', 'Une fois'] qPlayedHerocoliNo = ['No', 'Non',] gform[QStudiedBiology].unique() gform['Before playing Hero.Coli, had you ever heard about BioBricks?'].unique() gform['Have you played the current version of Hero.Coli?'].unique() getAllAnswerRows(qBiologyEducationLevelIndex, aBiologyEducationLevelHigh) assert(len(getAllAnswerRows(qBiologyEducationLevelIndex, aBiologyEducationLevelHigh)) != 0) assert(len(getAllAnswerRows(qBiologyEducationLevelIndex, aBiologyEducationLevelLow)) != 0) assert(len(getAllAnswerRows(qHeardBioBricksIndex, aYes)) != 0) assert(len(getAllAnswerRows(qHeardBioBricksIndex, aNoIDK)) != 0) assert(len(getAllAnswerRows(qPlayedHerocoliIndex, qPlayedHerocoliYes)) != 0) assert(len(getAllAnswerRows(qPlayedHerocoliIndex, qPlayedHerocoliNo)) != 0) ``` #### getPercentCorrectPerColumn tested through getPercentCorrectKnowingAnswer #### getPercentCorrectKnowingAnswer ``` questionIndex = 15 gform.iloc[:, questionIndex].head() (qBiologyEducationLevelIndex, aBiologyEducationLevelHigh) getAllAnswerRows(qBiologyEducationLevelIndex, aBiologyEducationLevelHigh) getPercentCorrectKnowingAnswer(qBiologyEducationLevelIndex, aBiologyEducationLevelHigh) getPercentCorrectKnowingAnswer(qBiologyEducationLevelIndex, aBiologyEducationLevelLow) getPercentCorrectKnowingAnswer(qHeardBioBricksIndex, aYes) getPercentCorrectKnowingAnswer(qHeardBioBricksIndex, aNoIDK) playedHerocoliIndexYes = getPercentCorrectKnowingAnswer(qPlayedHerocoliIndex, qPlayedHerocoliYes) playedHerocoliIndexYes playedHerocoliIndexNo = getPercentCorrectKnowingAnswer(qPlayedHerocoliIndex, qPlayedHerocoliNo) playedHerocoliIndexNo playedHerocoliIndexYes - playedHerocoliIndexNo (playedHerocoliIndexYes - playedHerocoliIndexNo) / (1 - playedHerocoliIndexNo) ``` ## Google form loading <a id=gformload /> ``` #gform = gformEN transposed = gform.T #answers = transposed[transposed[]] transposed type(gform) ``` ### Selection of a question <a id=selquest /> ``` gform.columns gform.columns.get_loc('Do not edit - pre-filled anonymous ID') localplayerguidkey # Using the whole question: gform[localplayerguidkey] # Get index from question localplayerguidindex # Using the index of the question: gform.iloc[:, localplayerguidindex] ``` ### Selection of a user's answers <a id=selusans /> userIdThatDidNotAnswer userId1AnswerEN userIdAnswersEN userId1AnswerFR userIdAnswersFR userIdAnswersENFR #### getUniqueUserCount tinkering ``` sample = gform #def getUniqueUserCount(sample): sample[localplayerguidkey].nunique() ``` #### getAllRespondersGFormGUID tinkering ``` userIds = gform[localplayerguidkey].unique() len(userIds) ``` #### getRandomGFormGUID tinkering ``` allResponders = getAllResponders() uniqueUsers = np.unique(allResponders) print(len(allResponders)) print(len(uniqueUsers)) for guid in uniqueUsers: if(not isGUIDFormat(guid)): print('incorrect guid: ' + str(guid)) uniqueUsers = getAllResponders() userCount = len(uniqueUsers) guid = '0' while (not isGUIDFormat(guid)): userIndex = randint(0,userCount-1) guid = uniqueUsers[userIndex] guid ``` #### getAnswers tinkering ``` #userId = userIdThatDidNotAnswer #userId = userId1AnswerEN userId = userIdAnswersEN _form = gform #def getAnswers( userId, _form = gform ): answers = _form[_form[localplayerguidkey]==userId] _columnAnswers = answers.T if 0 != len(answers): _newColumns = [] for column in _columnAnswers.columns: _newColumns.append(answersColumnNameStem + str(column)) _columnAnswers.columns = _newColumns else: # user has never answered print("user " + str(userId) + " has never answered") _columnAnswers ``` #### answer selection ``` answers # Selection of a specific answer answers.iloc[:,localplayerguidindex] answers.iloc[:,localplayerguidindex].iloc[0] type(answers.iloc[0,:]) answers.iloc[0,:].values ``` ## checking answers <a id=checkans /> ``` #### Question that has a correct answer: questionIndex = 15 answers.iloc[:,questionIndex].iloc[0] correctAnswers.iloc[questionIndex][0] answers.iloc[:,questionIndex].iloc[0].startswith(correctAnswers.iloc[questionIndex][0]) #### Question that has no correct answer: questionIndex = 0 #answers.iloc[:,questionIndex].iloc[0].startswith(correctAnswers.iloc[questionIndex].iloc[0]) #### Batch check: columnAnswers = getAnswers( userId ) columnAnswers.values[2,0] columnAnswers[columnAnswers.columns[0]][2] correctAnswers type(columnAnswers) indexOfFirstEvaluationQuestion = 13 columnAnswers.index[indexOfFirstEvaluationQuestion] ``` #### getTemporality tinkering ``` gform.tail(50) gform[gform[localplayerguidkey] == 'ba202bbc-af77-42e8-85ff-e25b871717d5'] gformRealBefore = gform.loc[88, QTimestamp] gformRealBefore gformRealAfter = gform.loc[107, QTimestamp] gformRealAfter RMRealFirstEvent = getFirstEventDate(gform.loc[88,localplayerguidkey]) RMRealFirstEvent ``` #### getTemporality tinkering ``` tzAnswerDate = gformRealBefore gameEventDate = RMRealFirstEvent #def getTemporality( answerDate, gameEventDate ): result = answerTemporalities[2] if(gameEventDate != pd.Timestamp.max.tz_localize('utc')): if(answerDate <= gameEventDate): result = answerTemporalities[0] elif (answerDate > gameEventDate): result = answerTemporalities[1] result, tzAnswerDate, gameEventDate firstEventDate = getFirstEventDate(gform.loc[userIndex,localplayerguidkey]) firstEventDate gformTestBefore = pd.Timestamp('2018-01-16 14:28:20.998000+0000', tz='UTC') getTemporality(gformTestBefore,firstEventDate) gformTestWhile = pd.Timestamp('2018-01-16 14:28:23.998000+0000', tz='UTC') getTemporality(gformTestWhile,firstEventDate) gformTestAfter = pd.Timestamp('2018-01-16 14:28:24.998000+0000', tz='UTC') getTemporality(gformTestAfter,firstEventDate) ``` #### getTestAnswers tinkering ``` _form = gform _rmDF = rmdf1522 _rmTestDF = normalizedRMDFTest includeAndroid = True #def getTestAnswers( _form = gform, _rmDF = rmdf1522, _rmTestDF = normalizedRMDFTest, includeAndroid = True): _form[_form[localplayerguidkey].isin(testUsers)] _form[localplayerguidkey] testUsers len(getTestAnswers()[localplayerguidkey]) rmdf1522['customData.platform'].unique() rmdf1522[rmdf1522['customData.platform'].apply(lambda s: str(s).endswith('editor'))] rmdf1522[rmdf1522['userId'].isin(getTestAnswers()[localplayerguidkey])][['userTime','customData.platform','userId']].dropna() ``` #### getCorrections tinkering ``` columnAnswers #testUserId = userId1AnswerEN testUserId = '8d352896-a3f1-471c-8439-0f426df901c1' getCorrections(testUserId) testUserId = '8d352896-a3f1-471c-8439-0f426df901c1' source = correctAnswers #def getCorrections( _userId, _source = correctAnswers, _form = gform ): columnAnswers = getAnswers( testUserId ) if 0 != len(columnAnswers.columns): questionsCount = len(columnAnswers.values) for columnName in columnAnswers.columns: if answersColumnNameStem in columnName: answerNumber = columnName.replace(answersColumnNameStem,"") newCorrectionsColumnName = correctionsColumnNameStem + answerNumber columnAnswers[newCorrectionsColumnName] = columnAnswers[columnName] columnAnswers[newCorrectionsColumnName] = pd.Series(np.full(questionsCount, np.nan)) for question in columnAnswers[columnName].index: #print() #print(question) __correctAnswers = source.loc[question] if(len(__correctAnswers) > 0): columnAnswers.loc[question,newCorrectionsColumnName] = False for correctAnswer in __correctAnswers: #print("-> " + correctAnswer) if str(columnAnswers.loc[question,columnName])\ .startswith(str(correctAnswer)): columnAnswers.loc[question,newCorrectionsColumnName] = True break else: # user has never answered print("can't give correct answers") columnAnswers question = QAge columnName = '' for column in columnAnswers.columns: if str.startswith(column, 'answers'): columnName = column break type(columnAnswers.loc[question,columnName]) getCorrections(localplayerguid) gform.columns[20] columnAnswers.loc[gform.columns[20],columnAnswers.columns[1]] columnAnswers[columnAnswers.columns[1]][gform.columns[13]] columnAnswers.loc[gform.columns[13],columnAnswers.columns[1]] columnAnswers.iloc[20,1] questionsCount np.full(3, np.nan) pd.Series(np.full(questionsCount, np.nan)) columnAnswers.loc[question,newCorrectionsColumnName] question correctAnswers[question] getCorrections('8d352896-a3f1-471c-8439-0f426df901c1') ``` #### getCorrections extensions tinkering ``` correctAnswersEN #demographicAnswersEN type([]) mergedCorrectAnswersEN = correctAnswersEN.copy() for index in mergedCorrectAnswersEN.index: #print(str(mergedCorrectAnswersEN.loc[index,column])) mergedCorrectAnswersEN.loc[index] =\ demographicAnswersEN.loc[index] + mergedCorrectAnswersEN.loc[index] mergedCorrectAnswersEN correctAnswersEN + demographicAnswersEN correctAnswers + demographicAnswers ``` #### getBinarizedCorrections tinkering ``` corrections = getCorrections(userIdAnswersENFR) #corrections for columnName in corrections.columns: if correctionsColumnNameStem in columnName: for index in corrections[columnName].index: if(True==corrections.loc[index,columnName]): corrections.loc[index,columnName] = 1 elif (False==corrections.loc[index,columnName]): corrections.loc[index,columnName] = 0 corrections binarized = getBinarizedCorrections(corrections) binarized slicedBinarized = binarized[13:40] slicedBinarized slicedBinarized =\ binarized[13:40][binarized.columns[\ binarized.columns.to_series().str.contains(correctionsColumnNameStem)\ ]] slicedBinarized ``` #### getBinarized tinkering ``` _source = correctAnswers _userId = getRandomGFormGUID() getCorrections(_userId, _source=_source, _form = gform) _userId = '5e978fb3-316a-42ba-bb58-00856353838d' gform[gform[localplayerguidkey] == _userId].iloc[0].index _gformLine = gform[gform[localplayerguidkey] == _userId].iloc[0] _gformLine.loc['Before playing Hero.Coli, had you ever heard about synthetic biology?'] _gformLine = gform[gform[localplayerguidkey] == _userId].iloc[0] # only for one user # def getBinarized(_gformLine, _source = correctAnswers): _notEmptyIndexes = [] for _index in _source.index: if(len(_source.loc[_index]) > 0): _notEmptyIndexes.append(_index) _binarized = pd.Series(np.full(len(_gformLine.index), np.nan), index = _gformLine.index) for question in _gformLine.index: _correctAnswers = _source.loc[question] if(len(_correctAnswers) > 0): _binarized[question] = 0 for _correctAnswer in _correctAnswers: if str(_gformLine.loc[question])\ .startswith(str(_correctAnswer)): _binarized.loc[question] = 1 break _slicedBinarized = _binarized.loc[_notEmptyIndexes] _slicedBinarized _slicedBinarized.loc['What are BioBricks and devices?'] ``` #### getAllBinarized tinkering ``` allBinarized = getAllBinarized() plotCorrelationMatrix(allBinarized) source source = correctAnswers + demographicAnswers notEmptyIndexes = [] for eltIndex in source.index: #print(eltIndex) if(len(source.loc[eltIndex]) > 0): notEmptyIndexes.append(eltIndex) len(source)-len(notEmptyIndexes) emptyForm = gform[gform[localplayerguidkey] == 'incorrectGUID'] emptyForm _source = correctAnswers + demographicAnswers _form = gform #emptyForm #def getAllBinarized(_source = correctAnswers, _form = gform ): _notEmptyIndexes = [] for _index in _source.index: if(len(_source.loc[_index]) > 0): _notEmptyIndexes.append(_index) _result = pd.DataFrame(index = _notEmptyIndexes) for _userId in getAllResponders( _form = _form ): _corrections = getCorrections(_userId, _source=_source, _form = _form) _binarized = getBinarizedCorrections(_corrections) _slicedBinarized =\ _binarized.loc[_notEmptyIndexes][_binarized.columns[\ _binarized.columns.to_series().str.contains(correctionsColumnNameStem)\ ]] _result = pd.concat([_result, _slicedBinarized], axis=1) _result = _result.T #_result if(_result.shape[0] > 0 and _result.shape[1] > 0): correlation = _result.astype(float).corr() #plt.matshow(correlation) sns.clustermap(correlation,cmap=plt.cm.jet,square=True,figsize=(10,10)) #ax = sns.clustermap(correlation,cmap=plt.cm.jet,square=True,figsize=(10,10),cbar_kws={\ #"orientation":"vertical"}) correlation_pearson = _result.T.astype(float).corr(methods[0]) correlation_kendall = _result.T.astype(float).corr(methods[1]) correlation_spearman = _result.T.astype(float).corr(methods[2]) print(correlation_pearson.equals(correlation_kendall)) print(correlation_kendall.equals(correlation_spearman)) diff = (correlation_pearson - correlation_kendall) flattened = diff[diff > 0.1].values.flatten() flattened[~np.isnan(flattened)] correlation ``` #### plotCorrelationMatrix tinkering ``` scientificQuestionsLabels = gform.columns[13:40] scientificQuestionsLabels = [ 'In order to modify the abilities of the bacterium, you have to... #1', 'What are BioBricks and devices? #2', 'What is the name of this BioBrick? #3', 'What is the name of this BioBrick?.1 #4', 'What is the name of this BioBrick?.2 #5', 'What is the name of this BioBrick?.3 #6', 'What does this BioBrick do? #7', 'What does this BioBrick do?.1 #8', 'What does this BioBrick do?.2 #9', 'What does this BioBrick do?.3 #10', 'Pick the case where the BioBricks are well-ordered: #11', 'When does green fluorescence happen? #12', 'What happens when you unequip the movement device? #13', 'What is this? #14', 'What does this device do? #15', 'What does this device do?.1 #16', 'What does this device do?.2 #17', 'What does this device do?.3 #18', 'What does this device do?.4 #19', 'What does this device do?.5 #20', 'What does this device do?.6 #21', 'What does this device do?.7 #22', 'Guess: what would a device producing l-arabinose do, if it started with a l-arabinose-induced promoter? #23', 'Guess: the bacterium would glow yellow... #24', 'What is the species of the bacterium of the game? #25', 'What is the scientific name of the tails of the bacterium? #26', 'Find the antibiotic: #27', ] scientificQuestionsLabelsX = [ '#1 In order to modify the abilities of the bacterium, you have to...', '#2 What are BioBricks and devices?', '#3 What is the name of this BioBrick?', '#4 What is the name of this BioBrick?.1', '#5 What is the name of this BioBrick?.2', '#6 What is the name of this BioBrick?.3', '#7 What does this BioBrick do?', '#8 What does this BioBrick do?.1', '#9 What does this BioBrick do?.2', '#10 What does this BioBrick do?.3', '#11 Pick the case where the BioBricks are well-ordered:', '#12 When does green fluorescence happen?', '#13 What happens when you unequip the movement device?', '#14 What is this?', '#15 What does this device do?', '#16 What does this device do?.1', '#17 What does this device do?.2', '#18 What does this device do?.3', '#19 What does this device do?.4', '#20 What does this device do?.5', '#21 What does this device do?.6', '#22 What does this device do?.7', 'Guess: what would a device producing l-arabinose do, if it started with a l-arabinose-induced p#23 romoter?', '#24 Guess: the bacterium would glow yellow...', '#25 What is the species of the bacterium of the game?', '#26 What is the scientific name of the tails of the bacterium?', '#27 Find the antibiotic:', ] questionsLabels = scientificQuestionsLabels questionsLabelsX = scientificQuestionsLabelsX fig = plt.figure(figsize=(10,10)) ax = fig.add_subplot(111) ax.set_yticklabels(['']+questionsLabels) ax.set_xticklabels(['']+questionsLabelsX, rotation='vertical') ax.matshow(correlation) ax.set_xticks(np.arange(-1,len(questionsLabels),1.)); ax.set_yticks(np.arange(-1,len(questionsLabels),1.)); questionsLabels = correlation.columns.copy() newLabels = [] for index in range(0, len(questionsLabels)): newLabels.append(questionsLabels[index] + ' #' + str(index + 1)) correlationRenamed = correlation.copy() correlationRenamed.columns = newLabels correlationRenamed.index = newLabels correlationRenamed correlationRenamed = correlation.copy() correlationRenamed.columns = pd.Series(correlation.columns).apply(lambda x: x + ' #' + str(correlation.columns.get_loc(x) + 1)) correlationRenamed.index = correlationRenamed.columns correlationRenamed correlation.shape fig = plt.figure(figsize=(10,10)) ax12 = plt.subplot(111) ax12.set_title('Heatmap') sns.heatmap(correlation,ax=ax12,cmap=plt.cm.jet,square=True) ax = sns.clustermap(correlation,cmap=plt.cm.jet,square=True,figsize=(10,10),cbar_kws={\ "orientation":"vertical"}) questionsLabels = pd.Series(correlation.columns).apply(lambda x: x + ' #' + str(correlation.columns.get_loc(x) + 1)) fig = plt.figure(figsize=(10,10)) ax = plt.subplot(111) cmap=plt.cm.jet #cmap=plt.cm.ocean cax = ax.imshow(correlation, interpolation='nearest', cmap=cmap, # extent=(0.5,np.shape(correlation)[0]+0.5,0.5,np.shape(correlation)[1]+0.5) ) #ax.grid(True) plt.title('Questions\' Correlations') ax.set_yticklabels(questionsLabels) ax.set_xticklabels(questionsLabels, rotation='vertical') ax.set_xticks(np.arange(len(questionsLabels))); ax.set_yticks(np.arange(len(questionsLabels))); #ax.set_xticks(np.arange(-1,len(questionsLabels),1.)); #ax.set_yticks(np.arange(-1,len(questionsLabels),1.)); fig.colorbar(cax) plt.show() ax.get_xticks() transposed = _result.T.astype(float) transposed.head() transposed.corr() transposed.columns = range(0,len(transposed.columns)) transposed.index = range(0,len(transposed.index)) transposed.head() transposed = transposed.iloc[0:10,0:3] transposed transposed = transposed.astype(float) type(transposed[0][0]) transposed.columns = list('ABC') transposed transposed.loc[0, 'A'] = 0 transposed transposed.corr() ``` data = transposed[[0,1]] data.corr(method = 'spearman') ``` round(7.64684) df = pd.DataFrame(10*np.random.randint(2, size=[20,2]),index=range(0,20),columns=list('AB')) #df.columns = range(0,len(df.columns)) df.head() #type(df[0][0]) type(df.columns) df.corr() #corr = pd.Series({}, index = methods) for meth in methods: #corr[meth] = result.corr(method = meth) print(meth + ":\n" + str(transposed.corr(method = meth)) + "\n\n") ``` #### getCrossCorrectAnswers tinkering ##### Before ``` befores = gform.copy() befores = befores[befores[QTemporality] == answerTemporalities[0]] print(len(befores)) allBeforesBinarized = getAllBinarized( _source = correctAnswers + demographicAnswers, _form = befores) np.unique(allBeforesBinarized.values.flatten()) allBeforesBinarized.columns[20] allBeforesBinarized.T.dot(allBeforesBinarized) np.unique(allBeforesBinarized.iloc[:,20].values) plotCorrelationMatrix( allBeforesBinarized, _abs=False,\ _clustered=False, _questionNumbers=True ) _correlation = allBeforesBinarized.astype(float).corr() overlay = allBeforesBinarized.T.dot(allBeforesBinarized).astype(int) _correlation.columns = pd.Series(_correlation.columns).apply(\ lambda x: x + ' #' + str(_correlation.columns.get_loc(x) + 1)) _correlation.index = _correlation.columns _correlation = _correlation.abs() _fig = plt.figure(figsize=(20,20)) _ax = plt.subplot(111) #sns.heatmap(_correlation,ax=_ax,cmap=plt.cm.jet,square=True,annot=overlay,fmt='d') sns.heatmap(_correlation,ax=_ax,cmap=plt.cm.jet,square=True,annot=True) ``` ##### after ``` afters = gform.copy() afters = afters[afters[QTemporality] == answerTemporalities[1]] print(len(afters)) allAftersBinarized = getAllBinarized( _source = correctAnswers + demographicAnswers, _form = afters) np.unique(allAftersBinarized.values.flatten()) plotCorrelationMatrix( allAftersBinarized, _abs=False,\ _clustered=False, _questionNumbers=True ) #for answerIndex in range(0,len(allAftersBinarized)): # print(str(answerIndex) + " " + str(allAftersBinarized.iloc[answerIndex,0])) allAftersBinarized.iloc[28,0] len(allAftersBinarized) len(allAftersBinarized.index) _correlation = allAftersBinarized.astype(float).corr() overlay = allAftersBinarized.T.dot(allAftersBinarized).astype(int) _correlation.columns = pd.Series(_correlation.columns).apply(\ lambda x: x + ' #' + str(_correlation.columns.get_loc(x) + 1)) _correlation.index = _correlation.columns _fig = plt.figure(figsize=(10,10)) _ax = plt.subplot(111) #sns.heatmap(_correlation,ax=_ax,cmap=plt.cm.jet,square=True,annot=overlay,fmt='d') sns.heatmap(_correlation,ax=_ax,cmap=plt.cm.jet,square=True) crossCorrect = getCrossCorrectAnswers(allAftersBinarized) pd.Series((overlay == crossCorrect).values.flatten()).unique() allAftersBinarized.shape cross = allAftersBinarized.T.dot(allAftersBinarized) cross.shape equal = (cross == crossCorrect) type(equal) pd.Series(equal.values.flatten()).unique() ``` #### getScore tinkering ``` testUser = userIdAnswersFR gform[gform[localplayerguidkey] == testUser].T getScore(testUser) print("draft test") testUserId = "3ef14300-4987-4b54-a56c-5b6d1f8a24a1" testUserId = userIdAnswersEN #def getScore( _userId, _form = gform ): score = pd.DataFrame({}, columns = answerTemporalities) score.loc['score',:] = np.nan for column in score.columns: score.loc['score', column] = [] if hasAnswered( testUserId ): columnAnswers = getCorrections(testUserId) for columnName in columnAnswers.columns: # only work on corrected columns if correctionsColumnNameStem in columnName: answerColumnName = columnName.replace(correctionsColumnNameStem,\ answersColumnNameStem) temporality = columnAnswers.loc[QTemporality,answerColumnName] counts = (columnAnswers[columnName]).value_counts() thisScore = 0 if(True in counts): thisScore = counts[True] score.loc['score',temporality].append(thisScore) else: print("user " + str(testUserId) + " has never answered") #expectedScore = 18 #if (expectedScore != score[0]): # print("ERROR incorrect score: expected "+ str(expectedScore) +", got "+ str(score)) score score = pd.DataFrame({}, columns = answerTemporalities) score.loc['score',:] = np.nan for column in score.columns: score.loc['score', column] = [] score #score.loc['user0',:] = [1,2,3] #score #type(score) #type(score[0]) #for i,v in score[0].iteritems(): # print(v) #score[0][answerTemporalities[2]] #columnAnswers.loc[QTemporality,'answers0'] False in (columnAnswers[columnName]).value_counts() getScore("3ef14300-4987-4b54-a56c-5b6d1f8a24a1") #gform[gform[localplayerguidkey]=="3ef14300-4987-4b54-a56c-5b6d1f8a24a1"].T correctAnswers ``` ## comparison of checkpoints completion and answers <a id=compcheckans /> Theoretically, they should match. Whoever understood an item should beat the matching challenge. The discrepancies are due to game design or level design. #### getValidatedCheckpoints tinkering ``` #questionnaireValidatedCheckpointsPerQuestion = pd.Series(np.nan, index=range(35)) questionnaireValidatedCheckpointsPerQuestion = pd.Series(np.nan, index=range(len(checkpointQuestionMatching))) questionnaireValidatedCheckpointsPerQuestion.head() checkpointQuestionMatching['checkpoint'][19] userId = localplayerguid _form = gform #function that returns the list of checkpoints from user id #def getValidatedCheckpoints( userId, _form = gform ): _validatedCheckpoints = [] if hasAnswered( userId, _form = _form ): _columnAnswers = getCorrections( userId, _form = _form) for _columnName in _columnAnswers.columns: # only work on corrected columns if correctionsColumnNameStem in _columnName: _questionnaireValidatedCheckpointsPerQuestion = pd.Series(np.nan, index=range(len(checkpointQuestionMatching))) for _index in range(0, len(_questionnaireValidatedCheckpointsPerQuestion)): if _columnAnswers[_columnName][_index]==True: _questionnaireValidatedCheckpointsPerQuestion[_index] = checkpointQuestionMatching['checkpoint'][_index] else: _questionnaireValidatedCheckpointsPerQuestion[_index] = '' _questionnaireValidatedCheckpoints = _questionnaireValidatedCheckpointsPerQuestion.unique() _questionnaireValidatedCheckpoints = _questionnaireValidatedCheckpoints[_questionnaireValidatedCheckpoints!=''] _questionnaireValidatedCheckpoints = pd.Series(_questionnaireValidatedCheckpoints) _questionnaireValidatedCheckpoints = _questionnaireValidatedCheckpoints.sort_values() _questionnaireValidatedCheckpoints.index = range(0, len(_questionnaireValidatedCheckpoints)) _validatedCheckpoints.append(_questionnaireValidatedCheckpoints) else: print("user " + str(userId) + " has never answered") result = pd.Series(data=_validatedCheckpoints) result type(result[0]) ``` #### getNonValidated tinkering ``` testSeries1 = pd.Series( [ 'tutorial1.Checkpoint00', 'tutorial1.Checkpoint01', 'tutorial1.Checkpoint02', 'tutorial1.Checkpoint05' ] ) testSeries2 = pd.Series( [ 'tutorial1.Checkpoint01', 'tutorial1.Checkpoint05' ] ) np.setdiff1d(testSeries1, testSeries2) np.setdiff1d(testSeries1.values, testSeries2.values) getAnswers(localplayerguid).head(2) getCorrections(localplayerguid).head(2) getScore(localplayerguid) getValidatedCheckpoints(localplayerguid) getNonValidatedCheckpoints(localplayerguid) ``` #### getAllAnswerRows tinkering ``` qPlayedHerocoliIndex = 10 qPlayedHerocoliYes = ['Yes', 'Once', 'Multiple times', 'Oui', 'De nombreuses fois', 'Quelques fois', 'Une fois'] questionIndex = qPlayedHerocoliIndex choice = qPlayedHerocoliYes _form = gform # returns all rows of Google form's answers that contain an element # of the array 'choice' for question number 'questionIndex' #def getAllAnswerRows(questionIndex, choice, _form = gform ): _form[_form.iloc[:, questionIndex].isin(choice)] ``` #### getPercentCorrectPerColumn tinkering ``` _df = getAllAnswerRows(qPlayedHerocoliIndex, qPlayedHerocoliYes, _form = gform ) #def getPercentCorrectPerColumn(_df): _count = len(_df) _percents = pd.Series(np.full(len(_df.columns), np.nan), index=_df.columns) for _rowIndex in _df.index: for _columnName in _df.columns: _columnIndex = _df.columns.get_loc(_columnName) if ((_columnIndex >= firstEvaluationQuestionIndex) \ and (_columnIndex < len(_df.columns)-3)): if(str(_df[_columnName][_rowIndex]).startswith(str(correctAnswers[_columnIndex]))): if (np.isnan(_percents[_columnName])): _percents[_columnName] = 1; else: _percents[_columnName] = _percents[_columnName]+1 else: if (np.isnan(_percents[_columnName])): _percents[_columnName] = 0; _percents = _percents/_count _percents['Count'] = _count _percents print('\n\n\npercents=\n' + str(_percents)) ``` #### getPercentCorrectKnowingAnswer tinkering ``` questionIndex = qPlayedHerocoliIndex choice = qPlayedHerocoliYes _form = gform #def getPercentCorrectKnowingAnswer(questionIndex, choice, _form = gform): _answerRows = getAllAnswerRows(questionIndex, choice, _form = _form); getPercentCorrectPerColumn(_answerRows) ``` ## tests on all user Ids, including those who answered more than once ``` #localplayerguid = '8d352896-a3f1-471c-8439-0f426df901c1' #localplayerguid = '7037c5b2-c286-498e-9784-9a061c778609' #localplayerguid = '5c4939b5-425b-4d19-b5d2-0384a515539e' #localplayerguid = '7825d421-d668-4481-898a-46b51efe40f0' #localplayerguid = 'acb9c989-b4a6-4c4d-81cc-6b5783ec71d8' for id in getAllResponders(): print("===========================================") print("id=" + str(id)) print("-------------------------------------------") print(getAnswers(id).head(2)) print("-------------------------------------------") print(getCorrections(id).head(2)) print("-------------------------------------------") print("scores=" + str(getScore(id))) print("#ValidatedCheckpoints=" + str(getValidatedCheckpointsCounts(id))) print("#NonValidatedCheckpoints=" + str(getNonValidatedCheckpointsCounts(id))) print("===========================================") gform[localplayerguidkey] hasAnswered( '8d352896-a3f1-471c-8439-0f426df901c1' ) '8d352896-a3f1-471c-8439-0f426df901c1' in gform[localplayerguidkey].values apostropheTestString = 'it\'s a test' apostropheTestString ``` ## answers submitted through time <a id=ansthrutime /> ## merging answers in English and French <a id=mergelang /> ### tests ``` #gformEN.head(2) #gformFR.head(2) ``` ### add language column Scores will be evaluated per language ``` #gformEN[QLanguage] = pd.Series(enLanguageID, index=gformEN.index) #gformFR[QLanguage] = pd.Series(frLanguageID, index=gformFR.index) #gformFR.head(2) ``` ### concatenate ``` # rename columns #gformFR.columns = gformEN.columns #gformFR.head(2) #gformTestMerge = pd.concat([gformEN, gformFR]) #gformTestMerge.head(2) #gformTestMerge.tail(2) gform localplayerguid someAnswers = getAnswers( '8ca16c7a-70a6-4723-bd72-65b8485a2e86' ) someAnswers testQuestionIndex = 24 thisUsersFirstEvaluationQuestion = str(someAnswers[someAnswers.columns[0]][testQuestionIndex]) thisUsersFirstEvaluationQuestion someAnswers[someAnswers.columns[0]][QLanguage] firstEvaluationQuestionCorrectAnswer = str(correctAnswers[testQuestionIndex]) firstEvaluationQuestionCorrectAnswer thisUsersFirstEvaluationQuestion.startswith(firstEvaluationQuestionCorrectAnswer) ``` #### getEventCountRatios tinkering ``` answerDate = gform[gform['userId'] == '51f1ef77-ec48-4976-be1f-89b7cbd1afab'][QTimestamp][0] answerDate allEvents = rmdf1522[rmdf1522['userId']=='51f1ef77-ec48-4976-be1f-89b7cbd1afab'] allEventsCount = len(allEvents) eventsBeforeRatio = len(allEvents[allEvents['userTime'] > answerDate])/allEventsCount eventsAfterRatio = len(allEvents[allEvents['userTime'] < answerDate])/allEventsCount result = [eventsBeforeRatio, eventsAfterRatio] result ``` #### setAnswerTemporalities2 tinkering / Temporalities analysis ``` len(gform) len(gform[gform[QTemporality] == answerTemporalities[2]]) len(gform[gform[QTemporality] == answerTemporalities[0]]) len(gform[gform[QTemporality] == answerTemporalities[1]]) gform.loc[:, [QPlayed, 'userId', QTemporality, QTimestamp]].sort_values(by = ['userId', QTimestamp]) gform.loc[:, [QPlayed, 'userId', QTemporality, QTimestamp]].sort_values(by = ['userId', QTimestamp]) sortedGFs = gform.loc[:, [QPlayed, 'userId', QTemporality, QTimestamp]].sort_values(by = ['userId', QTimestamp]) sortedGFs[sortedGFs[QTemporality] == answerTemporalities[2]] result = pd.DataFrame() maxuserIdIndex = len(sortedGFs['userId']) userIdIndex = 0 userIdIntProgress = IntProgress( value=0, min=0, max=maxuserIdIndex, description='userIdIndex:' ) display(userIdIntProgress) userIdText = Text('') display(userIdText) for userid in sortedGFs['userId']: userIdIndex += 1 userIdIntProgress.value = userIdIndex userIdText.value = userid if (len(sortedGFs[sortedGFs['userId'] == userid]) >= 2) and (answerTemporalities[2] in sortedGFs[sortedGFs['userId'] == userid][QTemporality].values): if len(result) == 0: result = sortedGFs[sortedGFs['userId'] == userid] else: result = pd.concat([result, sortedGFs[sortedGFs['userId'] == userid]]) #print(sortedGFs[sortedGFs['userId'] == userid]) result len(gform) - len(result) len(gform[gform[QTemporality] == answerTemporalities[2]]) len(gform[gform[QTemporality] == answerTemporalities[0]]) len(gform[gform[QTemporality] == answerTemporalities[1]]) gform.loc[:, [QPlayed, 'userId', QTemporality, QTimestamp]].sort_values(by = ['userId', QTimestamp]) rmdf1522['userTime'].min(),gform[QTimestamp].min(),rmdf1522['userTime'].min().floor('d') == gform[QTimestamp].min().floor('d') # code to find special userIds enSpeakers = gform[gform[QLanguage]==enLanguageID] frSpeakers = gform[gform[QLanguage]==frLanguageID] sortedGFs = gform.loc[:, ['userId', QTemporality, QTimestamp, QLanguage]].sort_values(by = ['userId', QTimestamp]) foundUserIDThatDidNotAnswer = False foundUserID1AnswerEN = False foundUserIDAnswersEN = False foundUserID1ScoreEN = False foundUserIDScoresEN = False foundUserID1AnswerFR = False foundUserIDAnswersFR = False foundUserID1ScoreFR = False foundUserIDScoresFR = False foundUserIDAnswersENFR = False maxuserIdIndex = len(sortedGFs['userId']) userIdIndex = 0 userIdIntProgress = IntProgress( value=0, min=0, max=maxuserIdIndex, description='userIdIndex:' ) display(userIdIntProgress) userIdText = Text('') display(userIdText) # survey1522startDate = Timestamp('2018-03-24 12:00:00.000000+0000', tz='UTC') survey1522startDate = gform[QTimestamp].min().floor('d') if (rmdf1522['userTime'].min().floor('d') != gform[QTimestamp].min().floor('d')): print("rmdf and gform first date don't match") for userId in rmdf1522[rmdf1522['userTime'] >= survey1522startDate]['userId']: if userId not in sortedGFs['userId'].values: print("userIdThatDidNotAnswer = '" + userId + "'") foundUserIDThatDidNotAnswer = True break for userId in sortedGFs['userId']: userIdIndex += 1 userIdIntProgress.value = userIdIndex userIdText.value = userId answers = sortedGFs[sortedGFs['userId'] == userId] if not foundUserID1AnswerEN and (len(answers) == 1) and (answers[QLanguage].unique() == [enLanguageID]): print("userId1AnswerEN = '" + userId + "'") print("userId1ScoreEN = '" + userId + "'") foundUserID1AnswerEN = True foundUserID1ScoreEN = True if not foundUserIDAnswersEN and (len(answers) >= 2) and (answers[QLanguage].unique() == [enLanguageID]): print("userIdAnswersEN = '" + userId + "'") print("userIdScoresEN = '" + userId + "'") foundUserIDAnswersEN = True foundUserIDScoresEN = True # if not foundUserID1ScoreEN and : # print("userId1ScoreEN = '" + userId + "'") # foundUserID1ScoreEN = True # if not foundUserIDScoresEN and : # print("userIdScoresEN = '" + userId + "'") # foundUserIDScoresEN = True if not foundUserID1AnswerFR and (len(answers) == 1) and (answers[QLanguage].unique() == [frLanguageID]): print("userId1AnswerFR = '" + userId + "'") print("userId1ScoreFR = '" + userId + "'") foundUserID1AnswerFR = True foundUserID1ScoreFR = True if not foundUserIDAnswersFR and (len(answers) >= 2) and (answers[QLanguage].unique() == [frLanguageID]): print("userIdAnswersFR = '" + userId + "'") print("userIdScoresFR = '" + userId + "'") foundUserIDAnswersFR = True foundUserIDScoresFR = True # if not foundUserID1ScoreFR and : # print("userId1ScoreFR = '" + userId + "'") # foundUserID1ScoreFR = True # if not foundUserIDScoresFR and : # print("userIdScoresFR = '" + userId + "'") # foundUserIDScoresFR = True if not foundUserIDAnswersENFR and (len(answers) >= 2) and (enLanguageID in answers[QLanguage].unique()) and (frLanguageID in answers[QLanguage].unique()): print("userIdAnswersENFR = '" + userId + "'") foundUserIDAnswersENFR = True answers answerDate = gform[gform['userId'] == '51f1ef77-ec48-4976-be1f-89b7cbd1afab'][QTimestamp][0] answerDate getEventCountRatios(answerDate, '51f1ef77-ec48-4976-be1f-89b7cbd1afab') allEvents = rmdf1522[rmdf1522['userId']=='51f1ef77-ec48-4976-be1f-89b7cbd1afab'] allEventsCount = len(allEvents) eventsBeforeRatio = len(allEvents[allEvents['userTime'] < answerDate])/allEventsCount eventsAfterRatio = len(allEvents[allEvents['userTime'] > answerDate])/allEventsCount result = [eventsBeforeRatio, eventsAfterRatio] result [answerDate, allEvents.loc[:, ['userTime']].iloc[0], allEvents.loc[:, ['userTime']].iloc[-1]] gform[gform['userId'] == '51f1ef77-ec48-4976-be1f-89b7cbd1afab'][QTemporality].iloc[0] userId = '51f1ef77-ec48-4976-be1f-89b7cbd1afab' answerDate = gform[gform['userId'] == userId][QTimestamp][0] [eventsBeforeRatio, eventsAfterRatio] = getEventCountRatios(answerDate, userId) [eventsBeforeRatio, eventsAfterRatio] ``` #### question types ``` # code to find currently-sorted-as-posttest answers that have nan answers to content questions QQ = QBioBricksDevicesComposition for answerIndex in gform.index: if gform.loc[answerIndex, QTemporality] == answerTemporalities[1]: if pd.isnull(gform.loc[answerIndex,QQ]): print(answerIndex) # code to find which answers have both already played but also filled in profile questions answersPlayedButProfile = [] for answerIndex in gform.index: if gform.loc[answerIndex, QTemporality] == answerTemporalities[1]: if ~pd.isnull(gform.iloc[answerIndex, QAge]): answersPlayedButProfile.append(answerIndex) gform.loc[answersPlayedButProfile, QPlayed] userId = gform.loc[54, 'userId'] thisUserIdsAnswers = gform[gform['userId'] == userId] thisUserIdsAnswers[thisUserIdsAnswers[QTemporality] == answerTemporalities[0]][QAge].values[0] gform[gform[QTemporality] == answerTemporalities[0]][QAge].unique() # pretest ages ages = gform[(gform[QTemporality] == answerTemporalities[0])][QAge].unique() ages.sort() ages # the answers that are a problem for the analysis AUnclassifiable = 'I played recently on an other computer' #_gformDF[(_gformDF[QTemporality] == answerTemporalities[1]) & (_gformDF[QAge].apply(type) == str)] gform[gform[QPlayed] == AUnclassifiable] # various tests around setPosttestsProfileInfo len(_gformDF[pd.isnull(_gformDF[QAge])])/len(_gformDF) _gformDF[pd.isnull(_gformDF[QAge])][QTemporality].unique() _gformDF[_gformDF[QTemporality] == answerTemporalities[1]][QAge].unique() nullAge = _gformDF[pd.isnull(_gformDF[QAge])]['userId'] nullAge = _gformDF[_gformDF['userId'].isin(nullAge)] len(nullAge) nullAge.sort_values(QPlayed) dates = np.unique(nullAge[QTimestamp].apply(pd.Timestamp.date).values) dates.sort() dates nullAge[QTimestamp].apply(pd.Timestamp.date).value_counts().sort_index() len(nullAge['userId'].unique())/len(gform['userId'].unique()) pretestIds = _gformDF[_gformDF[QTemporality] == answerTemporalities[0]]['userId'] posttestIds = _gformDF[_gformDF[QTemporality] == answerTemporalities[1]]['userId'] posttestsWithoutPretests = posttestIds[~posttestIds.isin(pretestIds)] pretestsWithoutPosttests = pretestIds[~pretestIds.isin(posttestIds)] len(posttestsWithoutPretests), len(posttestIds), len(pretestsWithoutPosttests), len(pretestIds) intersectionIds1 = pretestIds[pretestIds.isin(posttestIds)] intersectionIds2 = posttestIds[posttestIds.isin(pretestIds)] _gformDF.loc[intersectionIds2.index] len(gform) - len(getWithoutIncompleteAnswers()) _gformDF2.iloc[_gformDF2.index[pd.isnull(_gformDF2[_gformDF2.columns[survey1522DF[profileColumn]]].T).any()]] withoutIncompleteAnswers = getWithoutIncompleteAnswers() len(gform) - len(withoutIncompleteAnswers) len(getWithoutIncompleteAnswers()) # tests for getPerfectPretestPostestPairs '29b739fc-4f9f-4f5e-bfee-8ba12de4b7fa' in testUsers _gformDF3 = getWithoutIncompleteAnswers(gform) sortedPosttests = _gformDF3[_gformDF3[QTemporality] == answerTemporalities[1]]['userId'].value_counts() posttestDuplicatesUserIds = sortedPosttests[sortedPosttests > 1].index _gformDF4 = _gformDF3[_gformDF3['userId'].isin(posttestDuplicatesUserIds)].drop_duplicates(subset=['userId', QTemporality], keep='first') _gformDF5 = _gformDF3.sort_values(['userId', QTimestamp]).drop_duplicates(subset=['userId', QTemporality], keep='first') len(gform),len(_gformDF3),len(_gformDF4),len(_gformDF5) gform[gform['userId'].isin(posttestDuplicatesUserIds)][[QTimestamp, 'userId', QTemporality]].sort_values(['userId', QTimestamp]) gform.iloc[getPosttestsWithoutPretests(gform)][[QTimestamp, 'userId', QTemporality]].sort_values(['userId', QTimestamp]) # tests for getPerfectPretestPostestPairs _gformDF = gform _gformDF2 = getWithoutIncompleteAnswers(_gformDF) vc = _gformDF2['userId'].value_counts() vc[vc == 1] # remove ulterior pretests and posttests _gformDF3 = _gformDF2.sort_values(['userId', QTimestamp]).drop_duplicates(subset=['userId', QTemporality], keep='first') vc = _gformDF3['userId'].value_counts() vc[vc == 1] # only keep pretests that have matching posttests posttestIds = _gformDF3[_gformDF3[QTemporality] == answerTemporalities[1]]['userId'] _gformDF4 = _gformDF3.drop(_gformDF3.index[~_gformDF3['userId'].isin(posttestIds)]) vc = _gformDF4['userId'].value_counts() vc[vc == 1] vc ```
github_jupyter
# 1.2 Creating variables and assigning values Python is a Dynamically typed language. It means based on the value we assign to a variable, it sets the datatype to it. Now the question is "How do we assign a value to a variable?🤔". It's pretty easy. ```Python <variable_name> = <value> ``` We have a big list of data types that come as builtins in Python. * None * bytes * int * bool * float * complex * string * tuple * list * set * dict Apart from the above prominent data types, we have a few other data types like namedtuple, frozensets, etc.. Let's create examples for the above data types, will be little bored in just seeing the examples. We would be covering in depth about these data types in upcoming chapters :) Few things to know before getting into the examples:😉 1. `print` function is used to print the data on to the console. We used `f` inside the print function which is used to format the strings as `{}`, these are known as f-strings. 2. `type` function is used to find the type of the object or datatype. ``` # None none_datatype = None print(f"The type of none_datatype is {type(none_datatype)}") # int int_datatype = 13 print(f"The type of int_datatype is {type(int_datatype)}") # bytes bytes_datatype = b"Hello Python!" print(f"The type of bytes_datatype is {type(bytes_datatype)}") # bool # bool datatype can only have either True or False. Integer value of True is 1 and False is 0. bool_datatype = True print(f"The type of bool_datatype is {type(bool_datatype)}") # float float_datatype = 3.14 print(f"The type of float_datatype is {type(float_datatype)}") # complex complex_datatype = 13 + 5j print(f"The type of complex_datatype is {type(complex_datatype)}") # str str_datatype = "Hey! Welcome to Python." print(f"The type of str_datatype is {type(str_datatype)}") # tuple tuple_datatype = (None, 13, True, 3.14, "Hey! Welcome to Python.") print(f"The type of tuple_datatype is {type(tuple_datatype)}") # list list_datatype = [None, 13, True, 3.14, "Hey! Welcome to Python."] print(f"The type of list_datatype is {type(list_datatype)}") # set set_datatype = {None, 13, True, 3.14, "Hey! Welcome to Python."} print(f"The type of set_datatype is {type(set_datatype)}") # dict dict_datatype = { "language": "Python", "Inventor": "Guido Van Rossum", "release_year": 1991, } print(f"The type of dict_datatype is {type(dict_datatype)}") ``` ## Tidbits The thing which I Love the most about Python is the dynamic typing, Due to this we might not know what are the types of parameters we might pass to a function or method. If you pass any other type of object as a parameter, **boom** you might see Exceptions raised during the runtime👻. Let's remember that **With great power comes great responsibility** 🕷 To help the developers with this, from Python 3.6 we have [Type Hints(PEP-484)](https://www.python.org/dev/peps/pep-0484/). We will get through these in the coming chapters. Stay tuned 😇
github_jupyter
### Bayes' theorem In probability theory and statistics, Bayes’ theorem (alternatively Bayes’ law or Bayes' rule, also written as Bayes’s theorem) describes the probability of an event, based on prior knowledge of conditions that might be related to the event. <br/> Bayes' theorem is stated mathematically as the following equation: $$ P(A\mid B)={\frac {P(B\mid A)\,P(A)}{P(B)}},$$ where,<br/> * P(A|B) is a conditional probability: the likelihood of event A occurring given that B is true. * P(B|A) is also a conditional probability: the likelihood of event B occurring given that A is true. * P(A) and P(B) are the probabilities of observing A and B independently of each other; this is known as the marginal probability. $$P(A|B) \propto P(B|A)P(A)$$ * 正向概率:假设袋子里有N个白球,M个黑球,伸手摸球,摸到黑球的概率有多大 * 逆向概率:事先不知道袋子里的黑白球比例。观察取出的球(结果)的颜色,对袋子里的黑白比率做出推测 ``` # Spelling Correction # P(A): the probability that the result A occuring # P(B|A): the probability that the result A can affect input B import re, collections def words(text): return re.findall('[a-z]+', text.lower()) def train(features): model = collections.defaultdict(lambda: 1) for f in features: model[f] += 1 return model NWORDS = train(words(open('big.txt').read())) alphabet = 'abcdefghijklmnopqrstuvwxyz' def edits1(word): n = len(word) return set( [word[0:i] + word[i + 1:] for i in range(n)] + # deletion [word[0:i] + word[i + 1] + word[i] + word[i + 2:] for i in range(n - 1)] + # transposition [word[0:i] + c + word[i + 1:] for i in range(n) for c in alphabet] + # alteration [word[0:i] + c + word[i:] for i in range(n + 1) for c in alphabet]) # insertion def known_edits2(word): return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in NWORDS) def known(words): return set(w for w in words if w in NWORDS) def correct(word): candidates = known([word]) or known( edits1(word)) or known_edits2(word) or [word] return max(candidates, key=lambda w: NWORDS[w]) correct('knon') ``` ### 求解:argmaxc P(c|w) -> argmaxc P(w|c) P(c) / P(w) ### * P(c), 文章中出现一个正确拼写词 c 的概率, 也就是说, 在英语文章中, c 出现的概率有多大 * P(w|c), 在用户想键入 c 的情况下敲成 w 的概率. 因为这个是代表用户会以多大的概率把 c 敲错成 w * argmaxc, 用来枚举所有可能的 c 并且选取概率最大的 ``` # 把语料中的单词全部抽取出来, 转成小写, 并且去除单词中间的特殊符号 def words(text): return re.findall('[a-z]+', text.lower()) def train(features): model = collections.defaultdict(lambda: 1) for f in features: model[f] += 1 return model NWORDS = train(words(open('big.txt').read())) ``` 要是遇到我们从来没有过见过的新词怎么办. 假如说一个词拼写完全正确, 但是语料库中没有包含这个词, 从而这个词也永远不会出现在训练集中. 于是, 我们就要返回出现这个词的概率是0. 这个情况不太妙, 因为概率为0这个代表了这个事件绝对不可能发生, 而在我们的概率模型中, 我们期望用一个很小的概率来代表这种情况. lambda: 1 ``` NWORDS ``` ### 编辑距离: ### 两个词之间的编辑距离定义为使用了几次插入(在词中插入一个单字母), 删除(删除一个单字母), 交换(交换相邻两个字母), 替换(把一个字母换成另一个)的操作从一个词变到另一个词. ``` #返回所有与单词 w 编辑距离为 1 的集合 def edits1(word): n = len(word) return set([word[0:i]+word[i+1:] for i in range(n)] + # deletion [word[0:i]+word[i+1]+word[i]+word[i+2:] for i in range(n-1)] + # transposition [word[0:i]+c+word[i+1:] for i in range(n) for c in alphabet] + # alteration [word[0:i]+c+word[i:] for i in range(n+1) for c in alphabet]) # insertion # 与 something 编辑距离为2的单词居然达到了 114,324 个 # 优化:在这些编辑距离小于2的词中间, 只把那些正确的词作为候选词,只能返回 3 个单词: ‘smoothing’, ‘something’ 和 ‘soothing’ #返回所有与单词 w 编辑距离为 2 的集合 #在这些编辑距离小于2的词中间, 只把那些正确的词作为候选词 def edits2(word): return set(e2 for e1 in edits1(word) for e2 in edits1(e1)) ``` 正常来说把一个元音拼成另一个的概率要大于辅音 (因为人常常把 hello 打成 hallo 这样); 把单词的第一个字母拼错的概率会相对小, 等等.但是为了简单起见, 选择了一个简单的方法: 编辑距离为1的正确单词比编辑距离为2的优先级高, 而编辑距离为0的正确单词优先级比编辑距离为1的高. ``` def known(words): return set(w for w in words if w in NWORDS) #如果known(set)非空, candidate 就会选取这个集合, 而不继续计算后面的 def correct(word): candidates = known([word]) or known(edits1(word)) or known_edits2(word) or [word] return max(candidates, key=lambda w: NWORDS[w]) ```
github_jupyter
# **YOLOv2** --- <font size = 4> YOLOv2 is a deep-learning method designed to perform object detection and classification of objects in images, published by [Redmon and Farhadi](https://ieeexplore.ieee.org/document/8100173). This is based on the original [YOLO](https://arxiv.org/abs/1506.02640) implementation published by the same authors. YOLOv2 is trained on images with class annotations in the form of bounding boxes drawn around the objects of interest. The images are downsampled by a convolutional neural network (CNN) and objects are classified in two final fully connected layers in the network. YOLOv2 learns classification and object detection simultaneously by taking the whole input image into account, predicting many possible bounding box solutions, and then using regression to find the best bounding boxes and classifications for each object. <font size = 4>**This particular notebook enables object detection and classification on 2D images given ground truth bounding boxes. If you are interested in image segmentation, you should use our U-net or Stardist notebooks instead.** --- <font size = 4>*Disclaimer*: <font size = 4>This notebook is part of the Zero-Cost Deep-Learning to Enhance Microscopy project (https://github.com/HenriquesLab/DeepLearning_Collab/wiki). Jointly developed by the Jacquemet (link to https://cellmig.org/) and Henriques (https://henriqueslab.github.io/) laboratories. <font size = 4>This notebook is based on the following papers: **YOLO9000: Better, Faster, Stronger** from Joseph Redmon and Ali Farhadi in Proceedings of the IEEE conference on computer vision and pattern recognition, 2017, (https://ieeexplore.ieee.org/document/8100173) **You Only Look Once: Unified, Real-Time Object Detection** from Joseph Redmon, Santosh Divvala, Ross Girshick, Ali Farhadi in IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2016, (https://ieeexplore.ieee.org/document/7780460) <font size = 4>**Note: The source code for this notebook is adapted for keras and can be found in: (https://github.com/experiencor/keras-yolo2)** <font size = 4>**Please also cite these original papers when using or developing this notebook.** # **How to use this notebook?** --- <font size = 4>Video describing how to use our notebooks are available on youtube: - [**Video 1**](https://www.youtube.com/watch?v=GzD2gamVNHI&feature=youtu.be): Full run through of the workflow to obtain the notebooks and the provided test datasets as well as a common use of the notebook - [**Video 2**](https://www.youtube.com/watch?v=PUuQfP5SsqM&feature=youtu.be): Detailed description of the different sections of the notebook --- ###**Structure of a notebook** <font size = 4>The notebook contains two types of cell: <font size = 4>**Text cells** provide information and can be modified by douple-clicking the cell. You are currently reading the text cell. You can create a new text by clicking `+ Text`. <font size = 4>**Code cells** contain code and the code can be modfied by selecting the cell. To execute the cell, move your cursor on the `[ ]`-mark on the left side of the cell (play button appears). Click to execute the cell. After execution is done the animation of play button stops. You can create a new coding cell by clicking `+ Code`. --- ###**Table of contents, Code snippets** and **Files** <font size = 4>On the top left side of the notebook you find three tabs which contain from top to bottom: <font size = 4>*Table of contents* = contains structure of the notebook. Click the content to move quickly between sections. <font size = 4>*Code snippets* = contain examples how to code certain tasks. You can ignore this when using this notebook. <font size = 4>*Files* = contain all available files. After mounting your google drive (see section 1.) you will find your files and folders here. <font size = 4>**Remember that all uploaded files are purged after changing the runtime.** All files saved in Google Drive will remain. You do not need to use the Mount Drive-button; your Google Drive is connected in section 1.2. <font size = 4>**Note:** The "sample data" in "Files" contains default files. Do not upload anything in here! --- ###**Making changes to the notebook** <font size = 4>**You can make a copy** of the notebook and save it to your Google Drive. To do this click file -> save a copy in drive. <font size = 4>To **edit a cell**, double click on the text. This will show you either the source code (in code cells) or the source text (in text cells). You can use the `#`-mark in code cells to comment out parts of the code. This allows you to keep the original code piece in the cell as a comment. #**0. Before getting started** --- <font size = 4> Preparing the dataset carefully is essential to make this YOLOv2 notebook work. This model requires as input a set of images (currently .jpg) and as target a list of annotation files in Pascal VOC format. The annotation files should have the exact same name as the input files, except with an .xml instead of the .jpg extension. The annotation files contain the class labels and all bounding boxes for the objects for each image in your dataset. Most datasets will give the option of saving the annotations in this format or using software for hand-annotations will automatically save the annotations in this format. <font size=4> If you want to assemble your own dataset we recommend using the open source https://www.makesense.ai/ resource. You can follow our instructions on how to label your dataset with this tool on our [wiki](https://github.com/HenriquesLab/ZeroCostDL4Mic/wiki/Object-Detection-(YOLOv2)). <font size = 4>**We strongly recommend that you generate extra paired images. These images can be used to assess the quality of your trained model (Quality control dataset)**. The quality control assessment can be done directly in this notebook. <font size = 4> **Additionally, the corresponding input and output files need to have the same name**. <font size = 4> Please note that you currently can **only use .png or .jpg files!** <font size = 4>Here's a common data structure that can work: * Experiment A - **Training dataset** - Input images (Training_source) - img_1.png, img_2.png, ... - High SNR images (Training_source_annotations) - img_1.xml, img_2.xml, ... - **Quality control dataset** - Input images - img_1.png, img_2.png - High SNR images - img_1.xml, img_2.xml - **Data to be predicted** - **Results** --- <font size = 4>**Important note** <font size = 4>- If you wish to **Train a network from scratch** using your own dataset (and we encourage everyone to do that), you will need to run **sections 1 - 4**, then use **section 5** to assess the quality of your model and **section 6** to run predictions using the model that you trained. <font size = 4>- If you wish to **Evaluate your model** using a model previously generated and saved on your Google Drive, you will only need to run **sections 1 and 2** to set up the notebook, then use **section 5** to assess the quality of your model. <font size = 4>- If you only wish to **run predictions** using a model previously generated and saved on your Google Drive, you will only need to run **sections 1 and 2** to set up the notebook, then use **section 6** to run the predictions on the desired model. --- # **1. Initialise the Colab session** --- ## **1.1. Check for GPU access** --- By default, the session should be using Python 3 and GPU acceleration, but it is possible to ensure that these are set properly by doing the following: <font size = 4>Go to **Runtime -> Change the Runtime type** <font size = 4>**Runtime type: Python 3** *(Python 3 is programming language in which this program is written)* <font size = 4>**Accelerator: GPU** *(Graphics processing unit)* ``` #@markdown ##Run this cell to check if you have GPU access %tensorflow_version 1.x import tensorflow as tf if tf.test.gpu_device_name()=='': print('You do not have GPU access.') print('Did you change your runtime ?') print('If the runtime setting is correct then Google did not allocate a GPU for your session') print('Expect slow performance. To access GPU try reconnecting later') else: print('You have GPU access') !nvidia-smi ``` ## **1.2. Mount your Google Drive** --- <font size = 4> To use this notebook on the data present in your Google Drive, you need to mount your Google Drive to this notebook. <font size = 4> Play the cell below to mount your Google Drive and follow the link. In the new browser window, select your drive and select 'Allow', copy the code, paste into the cell and press enter. This will give Colab access to the data on the drive. <font size = 4> Once this is done, your data are available in the **Files** tab on the top left of notebook. ``` #@markdown ##Play the cell to connect your Google Drive to Colab #@markdown * Click on the URL. #@markdown * Sign in your Google Account. #@markdown * Copy the authorization code. #@markdown * Enter the authorization code. #@markdown * Click on "Files" site on the right. Refresh the site. Your Google Drive folder should now be available here as "drive". # mount user's Google Drive to Google Colab. from google.colab import drive drive.mount('/content/gdrive') ``` # **2. Install YOLOv2 and Dependencies** --- ``` Notebook_version = ['1.12'] #@markdown ##Install Network and Dependencies %tensorflow_version 1.x !pip install pascal-voc-writer !pip install fpdf !pip install PTable import sys before = [str(m) for m in sys.modules] from pascal_voc_writer import Writer from __future__ import division from __future__ import print_function from __future__ import absolute_import import csv import random import pprint import sys import time import numpy as np from optparse import OptionParser import pickle import math import cv2 import copy import math from matplotlib import pyplot as plt import matplotlib.patches as patches import tensorflow as tf import pandas as pd import os import shutil from skimage import io from sklearn.metrics import average_precision_score from keras.models import Model from keras.layers import Flatten, Dense, Input, Conv2D, MaxPooling2D, Dropout, Reshape, Activation, Conv2D, MaxPooling2D, BatchNormalization, Lambda from keras.layers.advanced_activations import LeakyReLU from keras.layers.merge import concatenate from keras.applications.mobilenet import MobileNet from keras.applications import InceptionV3 from keras.applications.vgg16 import VGG16 from keras.applications.resnet50 import ResNet50 from keras import backend as K from keras.optimizers import Adam, SGD, RMSprop from keras.layers import GlobalAveragePooling2D, GlobalMaxPooling2D, TimeDistributed from keras.engine.topology import get_source_inputs from keras.utils import layer_utils from keras.utils.data_utils import get_file from keras.objectives import categorical_crossentropy from keras.models import Model from keras.utils import generic_utils from keras.engine import Layer, InputSpec from keras import initializers, regularizers from keras.utils import Sequence import xml.etree.ElementTree as ET from collections import OrderedDict, Counter import json import imageio import imgaug as ia from imgaug import augmenters as iaa import copy import cv2 from tqdm import tqdm from tempfile import mkstemp from shutil import move, copymode from os import fdopen, remove from fpdf import FPDF, HTMLMixin from datetime import datetime from pip._internal.operations.freeze import freeze import subprocess as sp from prettytable import from_csv # from matplotlib.pyplot import imread ia.seed(1) # imgaug uses matplotlib backend for displaying images from imgaug.augmentables.bbs import BoundingBox, BoundingBoxesOnImage import re import glob #Here, we import a different github repo which includes the map_evaluation.py !git clone https://github.com/rodrigo2019/keras_yolo2.git if os.path.exists('/content/gdrive/My Drive/keras-yolo2'): shutil.rmtree('/content/gdrive/My Drive/keras-yolo2') #Here, we import the main github repo for this notebook and move it to the gdrive !git clone https://github.com/experiencor/keras-yolo2.git shutil.move('/content/keras-yolo2','/content/gdrive/My Drive/keras-yolo2') #Now, we move the map_evaluation.py file to the main repo for this notebook. #The source repo of the map_evaluation.py can then be ignored and is not further relevant for this notebook. shutil.move('/content/keras_yolo2/keras_yolov2/map_evaluation.py','/content/gdrive/My Drive/keras-yolo2/map_evaluation.py') os.chdir('/content/gdrive/My Drive/keras-yolo2') from backend import BaseFeatureExtractor, FullYoloFeature from preprocessing import parse_annotation, BatchGenerator def plt_rectangle(plt,label,x1,y1,x2,y2,fontsize=10): ''' == Input == plt : matplotlib.pyplot object label : string containing the object class name x1 : top left corner x coordinate y1 : top left corner y coordinate x2 : bottom right corner x coordinate y2 : bottom right corner y coordinate ''' linewidth = 1 color = "yellow" plt.text(x1,y1,label,fontsize=fontsize,backgroundcolor="magenta") plt.plot([x1,x1],[y1,y2], linewidth=linewidth,color=color) plt.plot([x2,x2],[y1,y2], linewidth=linewidth,color=color) plt.plot([x1,x2],[y1,y1], linewidth=linewidth,color=color) plt.plot([x1,x2],[y2,y2], linewidth=linewidth,color=color) def extract_single_xml_file(tree,object_count=True): Nobj = 0 row = OrderedDict() for elems in tree.iter(): if elems.tag == "size": for elem in elems: row[elem.tag] = int(elem.text) if elems.tag == "object": for elem in elems: if elem.tag == "name": row["bbx_{}_{}".format(Nobj,elem.tag)] = str(elem.text) if elem.tag == "bndbox": for k in elem: row["bbx_{}_{}".format(Nobj,k.tag)] = float(k.text) Nobj += 1 if object_count == True: row["Nobj"] = Nobj return(row) def count_objects(tree): Nobj=0 for elems in tree.iter(): if elems.tag == "object": for elem in elems: if elem.tag == "bndbox": Nobj += 1 return(Nobj) def compute_overlap(a, b): """ Code originally from https://github.com/rbgirshick/py-faster-rcnn. Parameters ---------- a: (N, 4) ndarray of float b: (K, 4) ndarray of float Returns ------- overlaps: (N, K) ndarray of overlap between boxes and query_boxes """ area = (b[:, 2] - b[:, 0]) * (b[:, 3] - b[:, 1]) iw = np.minimum(np.expand_dims(a[:, 2], axis=1), b[:, 2]) - np.maximum(np.expand_dims(a[:, 0], 1), b[:, 0]) ih = np.minimum(np.expand_dims(a[:, 3], axis=1), b[:, 3]) - np.maximum(np.expand_dims(a[:, 1], 1), b[:, 1]) iw = np.maximum(iw, 0) ih = np.maximum(ih, 0) ua = np.expand_dims((a[:, 2] - a[:, 0]) * (a[:, 3] - a[:, 1]), axis=1) + area - iw * ih ua = np.maximum(ua, np.finfo(float).eps) intersection = iw * ih return intersection / ua def compute_ap(recall, precision): """ Compute the average precision, given the recall and precision curves. Code originally from https://github.com/rbgirshick/py-faster-rcnn. # Arguments recall: The recall curve (list). precision: The precision curve (list). # Returns The average precision as computed in py-faster-rcnn. """ # correct AP calculation # first append sentinel values at the end mrec = np.concatenate(([0.], recall, [1.])) mpre = np.concatenate(([0.], precision, [0.])) # compute the precision envelope for i in range(mpre.size - 1, 0, -1): mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i]) # to calculate area under PR curve, look for points # where X axis (recall) changes value i = np.where(mrec[1:] != mrec[:-1])[0] # and sum (\Delta recall) * prec ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) return ap def load_annotation(image_folder,annotations_folder, i, config): annots = [] imgs, anns = parse_annotation(annotations_folder,image_folder,config['model']['labels']) for obj in imgs[i]['object']: annot = [obj['xmin'], obj['ymin'], obj['xmax'], obj['ymax'], config['model']['labels'].index(obj['name'])] annots += [annot] if len(annots) == 0: annots = [[]] return np.array(annots) def _calc_avg_precisions(config,image_folder,annotations_folder,weights_path,iou_threshold,score_threshold): # gather all detections and annotations all_detections = [[None for _ in range(len(config['model']['labels']))] for _ in range(len(os.listdir(image_folder)))] all_annotations = [[None for _ in range(len(config['model']['labels']))] for _ in range(len(os.listdir(annotations_folder)))] for i in range(len(os.listdir(image_folder))): raw_image = cv2.imread(os.path.join(image_folder,sorted(os.listdir(image_folder))[i])) raw_height, raw_width, _ = raw_image.shape #print(raw_height) # make the boxes and the labels yolo = YOLO(backend = config['model']['backend'], input_size = config['model']['input_size'], labels = config['model']['labels'], max_box_per_image = config['model']['max_box_per_image'], anchors = config['model']['anchors']) yolo.load_weights(weights_path) pred_boxes = yolo.predict(raw_image,iou_threshold=iou_threshold,score_threshold=score_threshold) score = np.array([box.score for box in pred_boxes]) #print(score) pred_labels = np.array([box.label for box in pred_boxes]) #print(len(pred_boxes)) if len(pred_boxes) > 0: pred_boxes = np.array([[box.xmin * raw_width, box.ymin * raw_height, box.xmax * raw_width, box.ymax * raw_height, box.score] for box in pred_boxes]) else: pred_boxes = np.array([[]]) # sort the boxes and the labels according to scores score_sort = np.argsort(-score) pred_labels = pred_labels[score_sort] pred_boxes = pred_boxes[score_sort] # copy detections to all_detections for label in range(len(config['model']['labels'])): all_detections[i][label] = pred_boxes[pred_labels == label, :] annotations = load_annotation(image_folder,annotations_folder,i,config) # copy ground truth to all_annotations for label in range(len(config['model']['labels'])): all_annotations[i][label] = annotations[annotations[:, 4] == label, :4].copy() # compute mAP by comparing all detections and all annotations average_precisions = {} F1_scores = {} total_recall = [] total_precision = [] with open(QC_model_folder+"/Quality Control/QC_results.csv", "w", newline='') as file: writer = csv.writer(file) writer.writerow(["class", "false positive", "true positive", "false negative", "recall", "precision", "accuracy", "f1 score", "average_precision"]) for label in range(len(config['model']['labels'])): false_positives = np.zeros((0,)) true_positives = np.zeros((0,)) scores = np.zeros((0,)) num_annotations = 0.0 for i in range(len(os.listdir(image_folder))): detections = all_detections[i][label] annotations = all_annotations[i][label] num_annotations += annotations.shape[0] detected_annotations = [] for d in detections: scores = np.append(scores, d[4]) if annotations.shape[0] == 0: false_positives = np.append(false_positives, 1) true_positives = np.append(true_positives, 0) continue overlaps = compute_overlap(np.expand_dims(d, axis=0), annotations) assigned_annotation = np.argmax(overlaps, axis=1) max_overlap = overlaps[0, assigned_annotation] if max_overlap >= iou_threshold and assigned_annotation not in detected_annotations: false_positives = np.append(false_positives, 0) true_positives = np.append(true_positives, 1) detected_annotations.append(assigned_annotation) else: false_positives = np.append(false_positives, 1) true_positives = np.append(true_positives, 0) # no annotations -> AP for this class is 0 (is this correct?) if num_annotations == 0: average_precisions[label] = 0 continue # sort by score indices = np.argsort(-scores) false_positives = false_positives[indices] true_positives = true_positives[indices] # compute false positives and true positives false_positives = np.cumsum(false_positives) true_positives = np.cumsum(true_positives) # compute recall and precision recall = true_positives / num_annotations precision = true_positives / np.maximum(true_positives + false_positives, np.finfo(np.float64).eps) total_recall.append(recall) total_precision.append(precision) #print(precision) # compute average precision average_precision = compute_ap(recall, precision) average_precisions[label] = average_precision if len(precision) != 0: F1_score = 2*(precision[-1]*recall[-1]/(precision[-1]+recall[-1])) F1_scores[label] = F1_score writer.writerow([config['model']['labels'][label], str(int(false_positives[-1])), str(int(true_positives[-1])), str(int(num_annotations-true_positives[-1])), str(recall[-1]), str(precision[-1]), str(true_positives[-1]/num_annotations), str(F1_scores[label]), str(average_precisions[label])]) else: F1_score = 0 F1_scores[label] = F1_score writer.writerow([config['model']['labels'][label], str(0), str(0), str(0), str(0), str(0), str(0), str(F1_score), str(average_precisions[label])]) return F1_scores, average_precisions, total_recall, total_precision def show_frame(pred_bb, pred_classes, pred_conf, gt_bb, gt_classes, class_dict, background=np.zeros((512, 512, 3)), show_confidence=True): """ Here, we are adapting classes and functions from https://github.com/MathGaron/mean_average_precision """ """ Plot the boundingboxes :param pred_bb: (np.array) Predicted Bounding Boxes [x1, y1, x2, y2] : Shape [n_pred, 4] :param pred_classes: (np.array) Predicted Classes : Shape [n_pred] :param pred_conf: (np.array) Predicted Confidences [0.-1.] : Shape [n_pred] :param gt_bb: (np.array) Ground Truth Bounding Boxes [x1, y1, x2, y2] : Shape [n_gt, 4] :param gt_classes: (np.array) Ground Truth Classes : Shape [n_gt] :param class_dict: (dictionary) Key value pairs of classes, e.g. {0:'dog',1:'cat',2:'horse'} :return: """ n_pred = pred_bb.shape[0] n_gt = gt_bb.shape[0] n_class = int(np.max(np.append(pred_classes, gt_classes)) + 1) #print(n_class) if len(background.shape) < 3: h, w = background.shape else: h, w, c = background.shape ax = plt.subplot("111") ax.imshow(background) cmap = plt.cm.get_cmap('hsv') confidence_alpha = pred_conf.copy() if not show_confidence: confidence_alpha.fill(1) for i in range(n_pred): x1 = pred_bb[i, 0]# * w y1 = pred_bb[i, 1]# * h x2 = pred_bb[i, 2]# * w y2 = pred_bb[i, 3]# * h rect_w = x2 - x1 rect_h = y2 - y1 #print(x1, y1) ax.add_patch(patches.Rectangle((x1, y1), rect_w, rect_h, fill=False, edgecolor=cmap(float(pred_classes[i]) / n_class), linestyle='dashdot', alpha=confidence_alpha[i])) for i in range(n_gt): x1 = gt_bb[i, 0]# * w y1 = gt_bb[i, 1]# * h x2 = gt_bb[i, 2]# * w y2 = gt_bb[i, 3]# * h rect_w = x2 - x1 rect_h = y2 - y1 ax.add_patch(patches.Rectangle((x1, y1), rect_w, rect_h, fill=False, edgecolor=cmap(float(gt_classes[i]) / n_class))) legend_handles = [] for i in range(n_class): legend_handles.append(patches.Patch(color=cmap(float(i) / n_class), label=class_dict[i])) ax.legend(handles=legend_handles) plt.show() class BoundBox: """ Here, we are adapting classes and functions from https://github.com/MathGaron/mean_average_precision """ def __init__(self, xmin, ymin, xmax, ymax, c = None, classes = None): self.xmin = xmin self.ymin = ymin self.xmax = xmax self.ymax = ymax self.c = c self.classes = classes self.label = -1 self.score = -1 def get_label(self): if self.label == -1: self.label = np.argmax(self.classes) return self.label def get_score(self): if self.score == -1: self.score = self.classes[self.get_label()] return self.score class WeightReader: def __init__(self, weight_file): self.offset = 4 self.all_weights = np.fromfile(weight_file, dtype='float32') def read_bytes(self, size): self.offset = self.offset + size return self.all_weights[self.offset-size:self.offset] def reset(self): self.offset = 4 def bbox_iou(box1, box2): intersect_w = _interval_overlap([box1.xmin, box1.xmax], [box2.xmin, box2.xmax]) intersect_h = _interval_overlap([box1.ymin, box1.ymax], [box2.ymin, box2.ymax]) intersect = intersect_w * intersect_h w1, h1 = box1.xmax-box1.xmin, box1.ymax-box1.ymin w2, h2 = box2.xmax-box2.xmin, box2.ymax-box2.ymin union = w1*h1 + w2*h2 - intersect return float(intersect) / union def draw_boxes(image, boxes, labels): image_h, image_w, _ = image.shape #Changes in box color added by LvC # class_colours = [] # for c in range(len(labels)): # colour = np.random.randint(low=0,high=255,size=3).tolist() # class_colours.append(tuple(colour)) for box in boxes: xmin = int(box.xmin*image_w) ymin = int(box.ymin*image_h) xmax = int(box.xmax*image_w) ymax = int(box.ymax*image_h) if box.get_label() == 0: cv2.rectangle(image, (xmin,ymin), (xmax,ymax), (255,0,0), 3) elif box.get_label() == 1: cv2.rectangle(image, (xmin,ymin), (xmax,ymax), (0,255,0), 3) else: cv2.rectangle(image, (xmin,ymin), (xmax,ymax), (0,0,255), 3) #cv2.rectangle(image, (xmin,ymin), (xmax,ymax), class_colours[box.get_label()], 3) cv2.putText(image, labels[box.get_label()] + ' ' + str(round(box.get_score(),3)), (xmin, ymin - 13), cv2.FONT_HERSHEY_SIMPLEX, 1e-3 * image_h, (0,0,0), 2) #print(box.get_label()) return image #Function added by LvC def save_boxes(image_path, boxes, labels):#, save_path): image = cv2.imread(image_path) image_h, image_w, _ = image.shape save_boxes =[] save_boxes_names = [] save_boxes.append(os.path.basename(image_path)) save_boxes_names.append(os.path.basename(image_path)) for box in boxes: # xmin = box.xmin save_boxes.append(int(box.xmin*image_w)) save_boxes_names.append(int(box.xmin*image_w)) # ymin = box.ymin save_boxes.append(int(box.ymin*image_h)) save_boxes_names.append(int(box.ymin*image_h)) # xmax = box.xmax save_boxes.append(int(box.xmax*image_w)) save_boxes_names.append(int(box.xmax*image_w)) # ymax = box.ymax save_boxes.append(int(box.ymax*image_h)) save_boxes_names.append(int(box.ymax*image_h)) score = box.get_score() save_boxes.append(score) save_boxes_names.append(score) label = box.get_label() save_boxes.append(label) save_boxes_names.append(labels[label]) #This file will be for later analysis of the bounding boxes in imagej if not os.path.exists('/content/predicted_bounding_boxes.csv'): with open('/content/predicted_bounding_boxes.csv', 'w', newline='') as csvfile: csvwriter = csv.writer(csvfile, delimiter=',') specs_list = ['filename']+['xmin', 'ymin', 'xmax', 'ymax', 'confidence', 'class']*len(boxes) csvwriter.writerow(specs_list) csvwriter.writerow(save_boxes) else: with open('/content/predicted_bounding_boxes.csv', 'a+', newline='') as csvfile: csvwriter = csv.writer(csvfile) csvwriter.writerow(save_boxes) if not os.path.exists('/content/predicted_bounding_boxes_names.csv'): with open('/content/predicted_bounding_boxes_names.csv', 'w', newline='') as csvfile_names: csvwriter = csv.writer(csvfile_names, delimiter=',') specs_list = ['filename']+['xmin', 'ymin', 'xmax', 'ymax', 'confidence', 'class']*len(boxes) csvwriter.writerow(specs_list) csvwriter.writerow(save_boxes_names) else: with open('/content/predicted_bounding_boxes_names.csv', 'a+', newline='') as csvfile_names: csvwriter = csv.writer(csvfile_names) csvwriter.writerow(save_boxes_names) # #This file is to create a nicer display for the output images # if not os.path.exists('/content/predicted_bounding_boxes_display.csv'): # with open('/content/predicted_bounding_boxes_display.csv', 'w', newline='') as csvfile_new: # csvwriter2 = csv.writer(csvfile_new, delimiter=',') # specs_list = ['filename','width','height','class','xmin','ymin','xmax','ymax'] # csvwriter2.writerow(specs_list) # else: # with open('/content/predicted_bounding_boxes_display.csv','a+',newline='') as csvfile_new: # csvwriter2 = csv.writer(csvfile_new) # for box in boxes: # row = [os.path.basename(image_path),image_w,image_h,box.get_label(),int(box.xmin*image_w),int(box.ymin*image_h),int(box.xmax*image_w),int(box.ymax*image_h)] # csvwriter2.writerow(row) def add_header(inFilePath,outFilePath): header = ['filename']+['xmin', 'ymin', 'xmax', 'ymax', 'confidence', 'class']*max(n_objects) with open(inFilePath, newline='') as inFile, open(outFilePath, 'w', newline='') as outfile: r = csv.reader(inFile) w = csv.writer(outfile) next(r, None) # skip the first row from the reader, the old header # write new header w.writerow(header) # copy the rest for row in r: w.writerow(row) def decode_netout(netout, anchors, nb_class, obj_threshold=0.3, nms_threshold=0.5): grid_h, grid_w, nb_box = netout.shape[:3] boxes = [] # decode the output by the network netout[..., 4] = _sigmoid(netout[..., 4]) netout[..., 5:] = netout[..., 4][..., np.newaxis] * _softmax(netout[..., 5:]) netout[..., 5:] *= netout[..., 5:] > obj_threshold for row in range(grid_h): for col in range(grid_w): for b in range(nb_box): # from 4th element onwards are confidence and class classes classes = netout[row,col,b,5:] if np.sum(classes) > 0: # first 4 elements are x, y, w, and h x, y, w, h = netout[row,col,b,:4] x = (col + _sigmoid(x)) / grid_w # center position, unit: image width y = (row + _sigmoid(y)) / grid_h # center position, unit: image height w = anchors[2 * b + 0] * np.exp(w) / grid_w # unit: image width h = anchors[2 * b + 1] * np.exp(h) / grid_h # unit: image height confidence = netout[row,col,b,4] box = BoundBox(x-w/2, y-h/2, x+w/2, y+h/2, confidence, classes) boxes.append(box) # suppress non-maximal boxes for c in range(nb_class): sorted_indices = list(reversed(np.argsort([box.classes[c] for box in boxes]))) for i in range(len(sorted_indices)): index_i = sorted_indices[i] if boxes[index_i].classes[c] == 0: continue else: for j in range(i+1, len(sorted_indices)): index_j = sorted_indices[j] if bbox_iou(boxes[index_i], boxes[index_j]) >= nms_threshold: boxes[index_j].classes[c] = 0 # remove the boxes which are less likely than a obj_threshold boxes = [box for box in boxes if box.get_score() > obj_threshold] return boxes def replace(file_path, pattern, subst): #Create temp file fh, abs_path = mkstemp() with fdopen(fh,'w') as new_file: with open(file_path) as old_file: for line in old_file: new_file.write(line.replace(pattern, subst)) #Copy the file permissions from the old file to the new file copymode(file_path, abs_path) #Remove original file remove(file_path) #Move new file move(abs_path, file_path) with open("/content/gdrive/My Drive/keras-yolo2/frontend.py", "r") as check: lineReader = check.readlines() reduce_lr = False for line in lineReader: if "reduce_lr" in line: reduce_lr = True break if reduce_lr == False: #replace("/content/gdrive/My Drive/keras-yolo2/frontend.py","period=1)","period=1)\n csv_logger=CSVLogger('/content/training_evaluation.csv')") replace("/content/gdrive/My Drive/keras-yolo2/frontend.py","period=1)","period=1)\n reduce_lr=ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=5, verbose=1)") replace("/content/gdrive/My Drive/keras-yolo2/frontend.py","import EarlyStopping","import ReduceLROnPlateau, EarlyStopping") with open("/content/gdrive/My Drive/keras-yolo2/frontend.py", "r") as check: lineReader = check.readlines() map_eval = False for line in lineReader: if "map_evaluation" in line: map_eval = True break if map_eval == False: replace("/content/gdrive/My Drive/keras-yolo2/frontend.py", "import cv2","import cv2\nfrom map_evaluation import MapEvaluation") new_callback = ' map_evaluator = MapEvaluation(self, valid_generator,save_best=True,save_name="/content/gdrive/My Drive/keras-yolo2/best_map_weights.h5",iou_threshold=0.3,score_threshold=0.3)' replace("/content/gdrive/My Drive/keras-yolo2/frontend.py","write_images=False)","write_images=False)\n"+new_callback) replace("/content/gdrive/My Drive/keras-yolo2/map_evaluation.py","import keras","import keras\nimport csv") replace("/content/gdrive/My Drive/keras-yolo2/map_evaluation.py","from .utils","from utils") replace("/content/gdrive/My Drive/keras-yolo2/map_evaluation.py",".format(_map))",".format(_map))\n with open('/content/gdrive/My Drive/mAP.csv','a+', newline='') as mAP_csv:\n csv_writer=csv.writer(mAP_csv)\n csv_writer.writerow(['mAP:','{:.4f}'.format(_map)])") replace("/content/gdrive/My Drive/keras-yolo2/map_evaluation.py","iou_threshold=0.5","iou_threshold=0.3") replace("/content/gdrive/My Drive/keras-yolo2/map_evaluation.py","score_threshold=0.5","score_threshold=0.3") replace("/content/gdrive/My Drive/keras-yolo2/frontend.py", "[early_stop, checkpoint, tensorboard]","[checkpoint, reduce_lr, map_evaluator]") replace("/content/gdrive/My Drive/keras-yolo2/frontend.py", "predict(self, image)","predict(self,image,iou_threshold=0.3,score_threshold=0.3)") replace("/content/gdrive/My Drive/keras-yolo2/frontend.py", "self.model.summary()","#self.model.summary()") from frontend import YOLO def train(config_path, model_path, percentage_validation): #config_path = args.conf with open(config_path) as config_buffer: config = json.loads(config_buffer.read()) ############################### # Parse the annotations ############################### # parse annotations of the training set train_imgs, train_labels = parse_annotation(config['train']['train_annot_folder'], config['train']['train_image_folder'], config['model']['labels']) # parse annotations of the validation set, if any, otherwise split the training set if os.path.exists(config['valid']['valid_annot_folder']): valid_imgs, valid_labels = parse_annotation(config['valid']['valid_annot_folder'], config['valid']['valid_image_folder'], config['model']['labels']) else: train_valid_split = int((1-percentage_validation/100.)*len(train_imgs)) np.random.shuffle(train_imgs) valid_imgs = train_imgs[train_valid_split:] train_imgs = train_imgs[:train_valid_split] if len(config['model']['labels']) > 0: overlap_labels = set(config['model']['labels']).intersection(set(train_labels.keys())) print('Seen labels:\t', train_labels) print('Given labels:\t', config['model']['labels']) print('Overlap labels:\t', overlap_labels) if len(overlap_labels) < len(config['model']['labels']): print('Some labels have no annotations! Please revise the list of labels in the config.json file!') return else: print('No labels are provided. Train on all seen labels.') config['model']['labels'] = train_labels.keys() ############################### # Construct the model ############################### yolo = YOLO(backend = config['model']['backend'], input_size = config['model']['input_size'], labels = config['model']['labels'], max_box_per_image = config['model']['max_box_per_image'], anchors = config['model']['anchors']) ############################### # Load the pretrained weights (if any) ############################### if os.path.exists(config['train']['pretrained_weights']): print("Loading pre-trained weights in", config['train']['pretrained_weights']) yolo.load_weights(config['train']['pretrained_weights']) if os.path.exists('/content/gdrive/My Drive/mAP.csv'): os.remove('/content/gdrive/My Drive/mAP.csv') ############################### # Start the training process ############################### yolo.train(train_imgs = train_imgs, valid_imgs = valid_imgs, train_times = config['train']['train_times'], valid_times = config['valid']['valid_times'], nb_epochs = config['train']['nb_epochs'], learning_rate = config['train']['learning_rate'], batch_size = config['train']['batch_size'], warmup_epochs = config['train']['warmup_epochs'], object_scale = config['train']['object_scale'], no_object_scale = config['train']['no_object_scale'], coord_scale = config['train']['coord_scale'], class_scale = config['train']['class_scale'], saved_weights_name = config['train']['saved_weights_name'], debug = config['train']['debug']) # The training evaluation.csv is saved (overwrites the Files if needed). lossDataCSVpath = os.path.join(model_path,'Quality Control/training_evaluation.csv') with open(lossDataCSVpath, 'w') as f1: writer = csv.writer(f1) mAP_df = pd.read_csv('/content/gdrive/My Drive/mAP.csv',header=None) writer.writerow(['loss','val_loss','mAP','learning rate']) for i in range(len(yolo.model.history.history['loss'])): writer.writerow([yolo.model.history.history['loss'][i], yolo.model.history.history['val_loss'][i], float(mAP_df[1][i]), yolo.model.history.history['lr'][i]]) yolo.model.save(model_path+'/last_weights.h5') def predict(config, weights_path, image_path):#, model_path): with open(config) as config_buffer: config = json.load(config_buffer) ############################### # Make the model ############################### yolo = YOLO(backend = config['model']['backend'], input_size = config['model']['input_size'], labels = config['model']['labels'], max_box_per_image = config['model']['max_box_per_image'], anchors = config['model']['anchors']) ############################### # Load trained weights ############################### yolo.load_weights(weights_path) ############################### # Predict bounding boxes ############################### if image_path[-4:] == '.mp4': video_out = image_path[:-4] + '_detected' + image_path[-4:] video_reader = cv2.VideoCapture(image_path) nb_frames = int(video_reader.get(cv2.CAP_PROP_FRAME_COUNT)) frame_h = int(video_reader.get(cv2.CAP_PROP_FRAME_HEIGHT)) frame_w = int(video_reader.get(cv2.CAP_PROP_FRAME_WIDTH)) video_writer = cv2.VideoWriter(video_out, cv2.VideoWriter_fourcc(*'MPEG'), 50.0, (frame_w, frame_h)) for i in tqdm(range(nb_frames)): _, image = video_reader.read() boxes = yolo.predict(image) image = draw_boxes(image, boxes, config['model']['labels']) video_writer.write(np.uint8(image)) video_reader.release() video_writer.release() else: image = cv2.imread(image_path) boxes = yolo.predict(image) image = draw_boxes(image, boxes, config['model']['labels']) save_boxes(image_path,boxes,config['model']['labels'])#,model_path)#added by LvC print(len(boxes), 'boxes are found') #print(image) cv2.imwrite(image_path[:-4] + '_detected' + image_path[-4:], image) return len(boxes) # function to convert BoundingBoxesOnImage object into DataFrame def bbs_obj_to_df(bbs_object): # convert BoundingBoxesOnImage object into array bbs_array = bbs_object.to_xyxy_array() # convert array into a DataFrame ['xmin', 'ymin', 'xmax', 'ymax'] columns df_bbs = pd.DataFrame(bbs_array, columns=['xmin', 'ymin', 'xmax', 'ymax']) return df_bbs # Function that will extract column data for our CSV file def xml_to_csv(path): xml_list = [] for xml_file in glob.glob(path + '/*.xml'): tree = ET.parse(xml_file) root = tree.getroot() for member in root.findall('object'): value = (root.find('filename').text, int(root.find('size')[0].text), int(root.find('size')[1].text), member[0].text, int(member[4][0].text), int(member[4][1].text), int(member[4][2].text), int(member[4][3].text) ) xml_list.append(value) column_name = ['filename', 'width', 'height', 'class', 'xmin', 'ymin', 'xmax', 'ymax'] xml_df = pd.DataFrame(xml_list, columns=column_name) return xml_df def image_aug(df, images_path, aug_images_path, image_prefix, augmentor): # create data frame which we're going to populate with augmented image info aug_bbs_xy = pd.DataFrame(columns= ['filename','width','height','class', 'xmin', 'ymin', 'xmax', 'ymax'] ) grouped = df.groupby('filename') for filename in df['filename'].unique(): # get separate data frame grouped by file name group_df = grouped.get_group(filename) group_df = group_df.reset_index() group_df = group_df.drop(['index'], axis=1) # read the image image = imageio.imread(images_path+filename) # get bounding boxes coordinates and write into array bb_array = group_df.drop(['filename', 'width', 'height', 'class'], axis=1).values # pass the array of bounding boxes coordinates to the imgaug library bbs = BoundingBoxesOnImage.from_xyxy_array(bb_array, shape=image.shape) # apply augmentation on image and on the bounding boxes image_aug, bbs_aug = augmentor(image=image, bounding_boxes=bbs) # disregard bounding boxes which have fallen out of image pane bbs_aug = bbs_aug.remove_out_of_image() # clip bounding boxes which are partially outside of image pane bbs_aug = bbs_aug.clip_out_of_image() # don't perform any actions with the image if there are no bounding boxes left in it if re.findall('Image...', str(bbs_aug)) == ['Image([]']: pass # otherwise continue else: # write augmented image to a file imageio.imwrite(aug_images_path+image_prefix+filename, image_aug) # create a data frame with augmented values of image width and height info_df = group_df.drop(['xmin', 'ymin', 'xmax', 'ymax'], axis=1) for index, _ in info_df.iterrows(): info_df.at[index, 'width'] = image_aug.shape[1] info_df.at[index, 'height'] = image_aug.shape[0] # rename filenames by adding the predifined prefix info_df['filename'] = info_df['filename'].apply(lambda x: image_prefix+x) # create a data frame with augmented bounding boxes coordinates using the function we created earlier bbs_df = bbs_obj_to_df(bbs_aug) # concat all new augmented info into new data frame aug_df = pd.concat([info_df, bbs_df], axis=1) # append rows to aug_bbs_xy data frame aug_bbs_xy = pd.concat([aug_bbs_xy, aug_df]) # return dataframe with updated images and bounding boxes annotations aug_bbs_xy = aug_bbs_xy.reset_index() aug_bbs_xy = aug_bbs_xy.drop(['index'], axis=1) return aug_bbs_xy print('-------------------------------------------') print("Depencies installed and imported.") # Colors for the warning messages class bcolors: WARNING = '\033[31m' NORMAL = '\033[0m' # Check if this is the latest version of the notebook Latest_notebook_version = pd.read_csv("https://raw.githubusercontent.com/HenriquesLab/ZeroCostDL4Mic/master/Colab_notebooks/Latest_ZeroCostDL4Mic_Release.csv") if Notebook_version == list(Latest_notebook_version.columns): print("This notebook is up-to-date.") if not Notebook_version == list(Latest_notebook_version.columns): print(bcolors.WARNING +"A new version of this notebook has been released. We recommend that you download it at https://github.com/HenriquesLab/ZeroCostDL4Mic/wiki"+bcolors.NORMAL) #Create a pdf document with training summary # save FPDF() class into a # variable pdf def pdf_export(trained = False, augmentation = False, pretrained_model = False): class MyFPDF(FPDF, HTMLMixin): pass pdf = MyFPDF() pdf.add_page() pdf.set_right_margin(-1) pdf.set_font("Arial", size = 11, style='B') Network = 'YOLOv2' day = datetime.now() datetime_str = str(day)[0:10] Header = 'Training report for '+Network+' model ('+model_name+'):\nDate: '+datetime_str pdf.multi_cell(180, 5, txt = Header, align = 'L') # add another cell if trained: training_time = "Training time: "+str(hour)+ "hour(s) "+str(mins)+"min(s) "+str(round(sec))+"sec(s)" pdf.cell(190, 5, txt = training_time, ln = 1, align='L') pdf.ln(1) Header_2 = 'Information for your materials and methods:' pdf.cell(190, 5, txt=Header_2, ln=1, align='L') all_packages = '' for requirement in freeze(local_only=True): all_packages = all_packages+requirement+', ' #print(all_packages) #Main Packages main_packages = '' version_numbers = [] for name in ['tensorflow','numpy','Keras']: find_name=all_packages.find(name) main_packages = main_packages+all_packages[find_name:all_packages.find(',',find_name)]+', ' #Version numbers only here: version_numbers.append(all_packages[find_name+len(name)+2:all_packages.find(',',find_name)]) cuda_version = sp.run('nvcc --version',stdout=sp.PIPE, shell=True) cuda_version = cuda_version.stdout.decode('utf-8') cuda_version = cuda_version[cuda_version.find(', V')+3:-1] gpu_name = sp.run('nvidia-smi',stdout=sp.PIPE, shell=True) gpu_name = gpu_name.stdout.decode('utf-8') gpu_name = gpu_name[gpu_name.find('Tesla'):gpu_name.find('Tesla')+10] #print(cuda_version[cuda_version.find(', V')+3:-1]) #print(gpu_name) shape = io.imread(Training_Source+'/'+os.listdir(Training_Source)[1]).shape dataset_size = len(os.listdir(Training_Source)) text = 'The '+Network+' model was trained from scratch for '+str(number_of_epochs)+' epochs on '+str(dataset_size)+' labelled images (image dimensions: '+str(shape)+') with a batch size of '+str(batch_size)+' and a custom loss function combining MSE and crossentropy losses, using the '+Network+' ZeroCostDL4Mic notebook (v '+Notebook_version[0]+') (von Chamier & Laine et al., 2020). Key python packages used include tensorflow (v '+version_numbers[0]+'), Keras (v '+version_numbers[2]+'), numpy (v '+version_numbers[1]+'), cuda (v '+cuda_version+'). The training was accelerated using a '+gpu_name+'GPU.' if pretrained_model: text = 'The '+Network+' model was trained for '+str(number_of_epochs)+' epochs on '+str(dataset_size)+' labelled images (image dimensions: '+str(shape)+') with a batch size of '+str(batch_size)+' and a custom loss function combining MSE and crossentropy losses, using the '+Network+' ZeroCostDL4Mic notebook (v '+Notebook_version[0]+') (von Chamier & Laine et al., 2020). The model was retrained from a pretrained model. Key python packages used include tensorflow (v '+version_numbers[0]+'), Keras (v '+version_numbers[2]+'), numpy (v '+version_numbers[1]+'), cuda (v '+cuda_version+'). The training was accelerated using a '+gpu_name+'GPU.' pdf.set_font('') pdf.set_font_size(10.) pdf.multi_cell(190, 5, txt = text, align='L') pdf.set_font('') pdf.set_font('Arial', size = 10, style = 'B') pdf.ln(1) pdf.cell(28, 5, txt='Augmentation: ', ln=0) pdf.set_font('') if augmentation: aug_text = 'The dataset was augmented by a factor of '+str(multiply_dataset_by)+' by' if multiply_dataset_by >= 2: aug_text = aug_text+'\n- flipping' if multiply_dataset_by > 2: aug_text = aug_text+'\n- rotation' else: aug_text = 'No augmentation was used for training.' pdf.multi_cell(190, 5, txt=aug_text, align='L') pdf.set_font('Arial', size = 11, style = 'B') pdf.ln(1) pdf.cell(180, 5, txt = 'Parameters', align='L', ln=1) pdf.set_font('') pdf.set_font_size(10.) if Use_Default_Advanced_Parameters: pdf.cell(200, 5, txt='Default Advanced Parameters were enabled') pdf.cell(200, 5, txt='The following parameters were used for training:') pdf.ln(1) html = """ <table width=40% style="margin-left:0px;"> <tr> <th width = 50% align="left">Parameter</th> <th width = 50% align="left">Value</th> </tr> <tr> <td width = 50%>number_of_epochs</td> <td width = 50%>{0}</td> </tr> <tr> <td width = 50%>train_times</td> <td width = 50%>{1}</td> </tr> <tr> <td width = 50%>batch_size</td> <td width = 50%>{2}</td> </tr> <tr> <td width = 50%>learning_rate</td> <td width = 50%>{3}</td> </tr> <tr> <td width = 50%>false_negative_penalty</td> <td width = 50%>{4}</td> </tr> <tr> <td width = 50%>false_positive_penalty</td> <td width = 50%>{5}</td> </tr> <tr> <td width = 50%>position_size_penalty</td> <td width = 50%>{6}</td> </tr> <tr> <td width = 50%>false_class_penalty</td> <td width = 50%>{7}</td> </tr> <tr> <td width = 50%>percentage_validation</td> <td width = 50%>{8}</td> </tr> </table> """.format(number_of_epochs, train_times, batch_size, learning_rate, false_negative_penalty, false_positive_penalty, position_size_penalty, false_class_penalty, percentage_validation) pdf.write_html(html) #pdf.multi_cell(190, 5, txt = text_2, align='L') pdf.set_font("Arial", size = 11, style='B') pdf.ln(1) pdf.cell(190, 5, txt = 'Training Dataset', align='L', ln=1) pdf.set_font('') pdf.set_font('Arial', size = 10, style = 'B') pdf.cell(30, 5, txt= 'Training_source:', align = 'L', ln=0) pdf.set_font('') pdf.multi_cell(170, 5, txt = Training_Source, align = 'L') pdf.set_font('') pdf.set_font('Arial', size = 10, style = 'B') pdf.cell(29, 5, txt= 'Training_target:', align = 'L', ln=0) pdf.set_font('') pdf.multi_cell(170, 5, txt = Training_Source_annotations, align = 'L') #pdf.cell(190, 5, txt=aug_text, align='L', ln=1) pdf.ln(1) pdf.set_font('') pdf.set_font('Arial', size = 10, style = 'B') pdf.cell(22, 5, txt= 'Model Path:', align = 'L', ln=0) pdf.set_font('') pdf.multi_cell(170, 5, txt = model_path+'/'+model_name, align = 'L') pdf.ln(1) if visualise_example == True: pdf.cell(60, 5, txt = 'Example ground-truth annotation', ln=1) pdf.ln(1) exp_size = io.imread('/content/TrainingDataExample_YOLOv2.png').shape pdf.image('/content/TrainingDataExample_YOLOv2.png', x = 11, y = None, w = round(exp_size[1]/8), h = round(exp_size[0]/8)) pdf.ln(1) ref_1 = 'References:\n - ZeroCostDL4Mic: von Chamier, Lucas & Laine, Romain, et al. "ZeroCostDL4Mic: an open platform to simplify access and use of Deep-Learning in Microscopy." bioRxiv (2020).' pdf.multi_cell(190, 5, txt = ref_1, align='L') ref_2 = '- YOLOv2: Redmon, Joseph, and Ali Farhadi. "YOLO9000: better, faster, stronger." Proceedings of the IEEE conference on computer vision and pattern recognition. 2017.' pdf.multi_cell(190, 5, txt = ref_2, align='L') ref_3 = '- YOLOv2 keras: https://github.com/experiencor/keras-yolo2, (2018)' pdf.multi_cell(190, 5, txt = ref_3, align='L') if augmentation: ref_4 = '- imgaug: Jung, Alexander et al., https://github.com/aleju/imgaug, (2020)' pdf.multi_cell(190, 5, txt = ref_4, align='L') pdf.ln(3) reminder = 'Important:\nRemember to perform the quality control step on all newly trained models\nPlease consider depositing your training dataset on Zenodo' pdf.set_font('Arial', size = 11, style='B') pdf.multi_cell(190, 5, txt=reminder, align='C') pdf.output(model_path+'/'+model_name+'/'+model_name+'_training_report.pdf') print('------------------------------') print('PDF report exported in '+model_path+'/'+model_name+'/') def qc_pdf_export(): class MyFPDF(FPDF, HTMLMixin): pass pdf = MyFPDF() pdf.add_page() pdf.set_right_margin(-1) pdf.set_font("Arial", size = 11, style='B') Network = 'YOLOv2' day = datetime.now() datetime_str = str(day)[0:16] Header = 'Quality Control report for '+Network+' model ('+QC_model_name+')\nDate and Time: '+datetime_str pdf.multi_cell(180, 5, txt = Header, align = 'L') all_packages = '' for requirement in freeze(local_only=True): all_packages = all_packages+requirement+', ' pdf.set_font('') pdf.set_font('Arial', size = 11, style = 'B') pdf.ln(2) pdf.cell(190, 5, txt = 'Development of Training Losses', ln=1, align='L') pdf.ln(1) if os.path.exists(QC_model_folder+'/Quality Control/lossCurveAndmAPPlots.png'): exp_size = io.imread(QC_model_folder+'/Quality Control/lossCurveAndmAPPlots.png').shape pdf.image(QC_model_folder+'/Quality Control/lossCurveAndmAPPlots.png', x = 11, y = None, w = round(exp_size[1]/8), h = round(exp_size[0]/8)) else: pdf.set_font('') pdf.set_font('Arial', size=10) pdf.multi_cell(190, 5, txt='If you would like to see the evolution of the loss function during training please play the first cell of the QC section in the notebook.') pdf.set_font('') pdf.set_font('Arial', size = 10, style = 'B') pdf.cell(80, 5, txt = 'P-R curves for test dataset', ln=1, align='L') pdf.ln(2) for i in range(len(AP)): if os.path.exists(QC_model_folder+'/Quality Control/P-R_curve_'+config['model']['labels'][i]+'.png'): exp_size = io.imread(QC_model_folder+'/Quality Control/P-R_curve_'+config['model']['labels'][i]+'.png').shape pdf.ln(1) pdf.image(QC_model_folder+'/Quality Control/P-R_curve_'+config['model']['labels'][i]+'.png', x=16, y=None, w=round(exp_size[1]/4), h=round(exp_size[0]/4)) else: pdf.cell(100, 5, txt='For the class '+config['model']['labels'][i]+' the model did not predict any objects.', ln=1, align='L') pdf.ln(3) pdf.set_font('') pdf.set_font('Arial', size = 11, style = 'B') pdf.ln(1) pdf.cell(180, 5, txt = 'Quality Control Metrics', align='L', ln=1) pdf.set_font('') pdf.set_font_size(10.) pdf.ln(1) html = """ <body> <font size="10" face="Courier New" > <table width=95% style="margin-left:0px;">""" with open(QC_model_folder+'/Quality Control/QC_results.csv', 'r') as csvfile: metrics = csv.reader(csvfile) header = next(metrics) class_name = header[0] fp = header[1] tp = header[2] fn = header[3] recall = header[4] precision = header[5] acc = header[6] f1 = header[7] AP_score = header[8] header = """ <tr> <th width = 11% align="left">{0}</th> <th width = 13% align="left">{1}</th> <th width = 13% align="left">{2}</th> <th width = 13% align="left">{3}</th> <th width = 8% align="left">{4}</th> <th width = 9% align="left">{5}</th> <th width = 9% align="left">{6}</th> <th width = 9% align="left">{7}</th> <th width = 14% align="left">{8}</th> </tr>""".format(class_name,fp,tp,fn,recall,precision,acc,f1,AP_score) html = html+header i=0 for row in metrics: i+=1 class_name = row[0] fp = row[1] tp = row[2] fn = row[3] recall = row[4] precision = row[5] acc = row[6] f1 = row[7] AP_score = row[8] cells = """ <tr> <td width = 11% align="left">{0}</td> <td width = 13% align="left">{1}</td> <td width = 13% align="left">{2}</td> <td width = 13% align="left">{3}</td> <td width = 8% align="left">{4}</td> <td width = 9% align="left">{5}</td> <td width = 9% align="left">{6}</td> <td width = 9% align="left">{7}</td> <td width = 14% align="left">{8}</td> </tr>""".format(class_name,fp,tp,fn,str(round(float(recall),3)),str(round(float(precision),3)),str(round(float(acc),3)),str(round(float(f1),3)),str(round(float(AP_score),3))) html = html+cells html = html+"""</body></table>""" pdf.write_html(html) pdf.cell(180, 5, txt='Mean average precision (mAP) over the all classes is: '+str(round(mAP_score,3)), ln=1, align='L') pdf.set_font('') pdf.set_font('Arial', size = 11, style = 'B') pdf.ln(3) pdf.cell(80, 5, txt = 'Example Quality Control Visualisation', ln=1) pdf.ln(3) exp_size = io.imread(QC_model_folder+'/Quality Control/QC_example_data.png').shape pdf.image(QC_model_folder+'/Quality Control/QC_example_data.png', x = 16, y = None, w = round(exp_size[1]/10), h = round(exp_size[0]/10)) pdf.set_font('') pdf.set_font_size(10.) pdf.ln(3) ref_1 = 'References:\n - ZeroCostDL4Mic: von Chamier, Lucas & Laine, Romain, et al. "ZeroCostDL4Mic: an open platform to simplify access and use of Deep-Learning in Microscopy." bioRxiv (2020).' pdf.multi_cell(190, 5, txt = ref_1, align='L') ref_2 = '- YOLOv2: Redmon, Joseph, and Ali Farhadi. "YOLO9000: better, faster, stronger." Proceedings of the IEEE conference on computer vision and pattern recognition. 2017.' pdf.multi_cell(190, 5, txt = ref_2, align='L') ref_3 = '- YOLOv2 keras: https://github.com/experiencor/keras-yolo2, (2018)' pdf.multi_cell(190, 5, txt = ref_3, align='L') pdf.ln(3) reminder = 'To find the parameters and other information about how this model was trained, go to the training_report.pdf of this model which should be in the folder of the same name.' pdf.set_font('Arial', size = 11, style='B') pdf.multi_cell(190, 5, txt=reminder, align='C') pdf.output(QC_model_folder+'/Quality Control/'+QC_model_name+'_QC_report.pdf') print('------------------------------') print('PDF report exported in '+QC_model_folder+'/Quality Control/') # Exporting requirements.txt for local run !pip freeze > ../../../requirements.txt after = [str(m) for m in sys.modules] # Get minimum requirements file #Add the following lines before all imports: # import sys # before = [str(m) for m in sys.modules] #Add the following line after the imports: # after = [str(m) for m in sys.modules] from builtins import any as b_any def filter_files(file_list, filter_list): filtered_list = [] for fname in file_list: if b_any(fname.split('==')[0] in s for s in filter_list): filtered_list.append(fname) return filtered_list df = pd.read_csv('../../../requirements.txt', delimiter = "\n") mod_list = [m.split('.')[0] for m in after if not m in before] req_list_temp = df.values.tolist() req_list = [x[0] for x in req_list_temp] # Replace with package name mod_name_list = [['sklearn', 'scikit-learn'], ['skimage', 'scikit-image']] mod_replace_list = [[x[1] for x in mod_name_list] if s in [x[0] for x in mod_name_list] else s for s in mod_list] filtered_list = filter_files(req_list, mod_replace_list) file=open('../../../YOLO_v2_requirements_simple.txt','w') for item in filtered_list: file.writelines(item + '\n') file.close() ``` # **3. Select your paths and parameters** --- <font size = 4>The code below allows the user to enter the paths to where the training data is and to define the training parameters. <font size = 4>After playing the cell will display some quantitative metrics of your dataset, including a count of objects per image and the number of instances per class. ## **3.1. Setting main training parameters** --- <font size = 4> <font size = 5> **Paths for training, predictions and results** <font size = 4>**`Training_source:`, `Training_source_annotations`:** These are the paths to your folders containing the Training_source and the annotation data respectively. To find the paths of the folders containing the respective datasets, go to your Files on the left of the notebook, navigate to the folder containing your files and copy the path by right-clicking on the folder, **Copy path** and pasting it into the right box below. <font size = 4>**`model_name`:** Use only my_model -style, not my-model (Use "_" not "-"). Do not use spaces in the name. Avoid using the name of an existing model (saved in the same folder) as it will be overwritten. <font size = 4>**`model_path`**: Enter the path where your model will be saved once trained (for instance your result folder). <font size = 5>**Training Parameters** <font size = 4>**`number_of_epochs`:**Give estimates for training performance given a number of epochs and provide a default value. **Default value: 27** <font size = 4>**Note that YOLOv2 uses 3 Warm-up epochs which improves the model's performance. This means the network will train for number_of_epochs + 3 epochs.** <font size = 4>**`backend`:** There are different backends which are available to be trained for YOLO. These are usually slightly different model architectures, with pretrained weights. Take a look at the available backends and research which one will be best suited for your dataset. <font size = 5>**Advanced Parameters - experienced users only** <font size = 4>**`train_times:`**Input how many times to cycle through the dataset per epoch. This is more useful for smaller datasets (but risks overfitting). **Default value: 4** <font size = 4>**`batch_size:`** This parameter defines the number of patches seen in each training step. Reducing or increasing the **batch size** may slow or speed up your training, respectively, and can influence network performance. **Default value: 16** <font size = 4>**`learning_rate:`** Input the initial value to be used as learning rate. **Default value: 0.0004** <font size=4>**`false_negative_penalty:`** Penalize wrong detection of 'no-object'. **Default: 5.0** <font size=4>**`false_positive_penalty:`** Penalize wrong detection of 'object'. **Default: 1.0** <font size=4>**`position_size_penalty:`** Penalize inaccurate positioning or size of bounding boxes. **Default:1.0** <font size=4>**`false_class_penalty:`** Penalize misclassification of object in bounding box. **Default: 1.0** <font size = 4>**`percentage_validation:`** Input the percentage of your training dataset you want to use to validate the network during training. **Default value: 10** ``` #@markdown ###Path to training images: Training_Source = "" #@param {type:"string"} # Ground truth images Training_Source_annotations = "" #@param {type:"string"} # model name and path #@markdown ###Name of the model and path to model folder: model_name = "" #@param {type:"string"} model_path = "" #@param {type:"string"} # backend #@markdown ###Choose a backend backend = "Full Yolo" #@param ["Select Model","Full Yolo","Inception3","SqueezeNet","MobileNet","Tiny Yolo"] full_model_path = os.path.join(model_path,model_name) if os.path.exists(full_model_path): print(bcolors.WARNING+'Model folder already exists and will be overwritten.'+bcolors.NORMAL) # other parameters for training. # @markdown ###Training Parameters # @markdown Number of epochs: number_of_epochs = 27#@param {type:"number"} # !sed -i 's@\"nb_epochs\":.*,@\"nb_epochs\": $number_of_epochs,@g' config.json # #@markdown ###Advanced Parameters Use_Default_Advanced_Parameters = True #@param {type:"boolean"} #@markdown ###If not, please input: train_times = 4 #@param {type:"integer"} batch_size = 16#@param {type:"number"} learning_rate = 1e-4 #@param{type:"number"} false_negative_penalty = 5.0 #@param{type:"number"} false_positive_penalty = 1.0 #@param{type:"number"} position_size_penalty = 1.0 #@param{type:"number"} false_class_penalty = 1.0 #@param{type:"number"} percentage_validation = 10#@param{type:"number"} if (Use_Default_Advanced_Parameters): print("Default advanced parameters enabled") train_times = 4 batch_size = 8 learning_rate = 1e-4 false_negative_penalty = 5.0 false_positive_penalty = 1.0 position_size_penalty = 1.0 false_class_penalty = 1.0 percentage_validation = 10 df_anno = [] dir_anno = Training_Source_annotations for fnm in os.listdir(dir_anno): if not fnm.startswith('.'): ## do not include hidden folders/files tree = ET.parse(os.path.join(dir_anno,fnm)) row = extract_single_xml_file(tree) row["fileID"] = os.path.splitext(fnm)[0] df_anno.append(row) df_anno = pd.DataFrame(df_anno) maxNobj = np.max(df_anno["Nobj"]) totalNobj = np.sum(df_anno["Nobj"]) class_obj = [] for ibbx in range(maxNobj): class_obj.extend(df_anno["bbx_{}_name".format(ibbx)].values) class_obj = np.array(class_obj) count = Counter(class_obj[class_obj != 'nan']) print(count) class_nm = list(count.keys()) class_labels = json.dumps(class_nm) class_count = list(count.values()) asort_class_count = np.argsort(class_count) class_nm = np.array(class_nm)[asort_class_count] class_count = np.array(class_count)[asort_class_count] xs = range(len(class_count)) #Show how many objects there are in the images plt.figure(figsize=(15,8)) plt.subplot(1,2,1) plt.hist(df_anno["Nobj"].values,bins=50) plt.title("Total number of objects in the dataset: {}".format(totalNobj)) plt.xlabel('Number of objects per image') plt.ylabel('Occurences') plt.subplot(1,2,2) plt.barh(xs,class_count) plt.yticks(xs,class_nm) plt.title("The number of objects per class: {} classes in total".format(len(count))) plt.show() visualise_example = False Use_pretrained_model = False Use_Data_augmentation = False full_model_path = os.path.join(model_path,model_name) if os.path.exists(full_model_path): print(bcolors.WARNING+'Model folder already exists and has been overwritten.'+bcolors.NORMAL) shutil.rmtree(full_model_path) # Create a new directory os.mkdir(full_model_path) pdf_export() #@markdown ###Play this cell to visualise an example image from your dataset to make sure annotations and images are properly matched. import imageio visualise_example = True size = 1 ind_random = np.random.randint(0,df_anno.shape[0],size=size) img_dir=Training_Source file_suffix = os.path.splitext(os.listdir(Training_Source)[0])[1] for irow in ind_random: row = df_anno.iloc[irow,:] path = os.path.join(img_dir, row["fileID"] + file_suffix) # read in image img = imageio.imread(path) plt.figure(figsize=(12,12)) plt.imshow(img, cmap='gray') # plot image plt.title("Nobj={}, height={}, width={}".format(row["Nobj"],row["height"],row["width"])) # for each object in the image, plot the bounding box for iplot in range(row["Nobj"]): plt_rectangle(plt, label = row["bbx_{}_name".format(iplot)], x1=row["bbx_{}_xmin".format(iplot)], y1=row["bbx_{}_ymin".format(iplot)], x2=row["bbx_{}_xmax".format(iplot)], y2=row["bbx_{}_ymax".format(iplot)]) plt.axis('off') plt.savefig('/content/TrainingDataExample_YOLOv2.png',bbox_inches='tight',pad_inches=0) plt.show() ## show the plot pdf_export() ``` ##**3.2. Data augmentation** --- <font size = 4> Data augmentation can improve training progress by amplifying differences in the dataset. This can be useful if the available dataset is small since, in this case, it is possible that a network could quickly learn every example in the dataset (overfitting), without augmentation. Augmentation is not necessary for training and if the dataset the `Use_Data_Augmentation` box can be unticked. <font size = 4>Here, the images and bounding boxes are augmented by flipping and rotation. When doubling the dataset the images are only flipped. With each higher factor of augmentation the images added to the dataset represent one further rotation to the right by 90 degrees. 8x augmentation will give a dataset that is fully rotated and flipped once. ``` #@markdown ##**Augmentation Options** Use_Data_augmentation = True #@param {type:"boolean"} multiply_dataset_by = 2 #@param {type:"slider", min:2, max:8, step:1} rotation_range = 90 file_suffix = os.path.splitext(os.listdir(Training_Source)[0])[1] if (Use_Data_augmentation): print('Data Augmentation enabled') # load images as NumPy arrays and append them to images list if os.path.exists(Training_Source+'/.ipynb_checkpoints'): shutil.rmtree(Training_Source+'/.ipynb_checkpoints') images = [] for index, file in enumerate(glob.glob(Training_Source+'/*'+file_suffix)): images.append(imageio.imread(file)) # how many images we have print('Augmenting {} images'.format(len(images))) # apply xml_to_csv() function to convert all XML files in images/ folder into labels.csv labels_df = xml_to_csv(Training_Source_annotations) labels_df.to_csv(('/content/original_labels.csv'), index=None) # Apply flip augmentation aug = iaa.OneOf([ iaa.Fliplr(1), iaa.Flipud(1) ]) aug_2 = iaa.Affine(rotate=rotation_range, fit_output=True) aug_3 = iaa.Affine(rotate=rotation_range*2, fit_output=True) aug_4 = iaa.Affine(rotate=rotation_range*3, fit_output=True) #Here we create a folder that will hold the original image dataset and the augmented image dataset augmented_training_source = os.path.dirname(Training_Source)+'/'+os.path.basename(Training_Source)+'_augmentation' if os.path.exists(augmented_training_source): shutil.rmtree(augmented_training_source) os.mkdir(augmented_training_source) #Here we create a folder that will hold the original image annotation dataset and the augmented image annotation dataset (the bounding boxes). augmented_training_source_annotation = os.path.dirname(Training_Source_annotations)+'/'+os.path.basename(Training_Source_annotations)+'_augmentation' if os.path.exists(augmented_training_source_annotation): shutil.rmtree(augmented_training_source_annotation) os.mkdir(augmented_training_source_annotation) #Create the augmentation augmented_images_df = image_aug(labels_df, Training_Source+'/', augmented_training_source+'/', 'flip_', aug) # Concat resized_images_df and augmented_images_df together and save in a new all_labels.csv file all_labels_df = pd.concat([labels_df, augmented_images_df]) all_labels_df.to_csv('/content/combined_labels.csv', index=False) #Here we convert the new bounding boxes for the augmented images to PASCAL VOC .xml format def convert_to_xml(df,source,target_folder): grouped = df.groupby('filename') for file in os.listdir(source): #if file in grouped.filename: group_df = grouped.get_group(file) group_df = group_df.reset_index() group_df = group_df.drop(['index'], axis=1) #group_df = group_df.dropna(axis=0) writer = Writer(source+'/'+file,group_df.iloc[1]['width'],group_df.iloc[1]['height']) for i, row in group_df.iterrows(): writer.addObject(row['class'],round(row['xmin']),round(row['ymin']),round(row['xmax']),round(row['ymax'])) writer.save(target_folder+'/'+os.path.splitext(file)[0]+'.xml') convert_to_xml(all_labels_df,augmented_training_source,augmented_training_source_annotation) #Second round of augmentation if multiply_dataset_by > 2: aug_labels_df_2 = xml_to_csv(augmented_training_source_annotation) augmented_images_2_df = image_aug(aug_labels_df_2, augmented_training_source+'/', augmented_training_source+'/', 'rot1_90_', aug_2) all_aug_labels_df = pd.concat([augmented_images_df, augmented_images_2_df]) #all_labels_df.to_csv('/content/all_labels_aug.csv', index=False) for file in os.listdir(augmented_training_source_annotation): os.remove(os.path.join(augmented_training_source_annotation,file)) convert_to_xml(all_aug_labels_df,augmented_training_source,augmented_training_source_annotation) if multiply_dataset_by > 3: print('Augmenting again') aug_labels_df_3 = xml_to_csv(augmented_training_source_annotation) augmented_images_3_df = image_aug(aug_labels_df_3, augmented_training_source+'/', augmented_training_source+'/', 'rot2_90_', aug_2) all_aug_labels_df_3 = pd.concat([all_aug_labels_df, augmented_images_3_df]) for file in os.listdir(augmented_training_source_annotation): os.remove(os.path.join(augmented_training_source_annotation,file)) convert_to_xml(all_aug_labels_df_3,augmented_training_source,augmented_training_source_annotation) #This is a preliminary remover of potential duplicates in the augmentation #Ideally, duplicates are not even produced, but this acts as a fail safe. if multiply_dataset_by==4: for file in os.listdir(augmented_training_source): if file.startswith('rot2_90_flip_'): os.remove(os.path.join(augmented_training_source,file)) os.remove(os.path.join(augmented_training_source_annotation, os.path.splitext(file)[0]+'.xml')) if multiply_dataset_by > 4: print('And Again') aug_labels_df_4 = xml_to_csv(augmented_training_source_annotation) augmented_images_4_df = image_aug(aug_labels_df_4, augmented_training_source+'/',augmented_training_source+'/','rot3_90_', aug_2) all_aug_labels_df_4 = pd.concat([all_aug_labels_df_3, augmented_images_4_df]) for file in os.listdir(augmented_training_source_annotation): os.remove(os.path.join(augmented_training_source_annotation,file)) convert_to_xml(all_aug_labels_df_4,augmented_training_source,augmented_training_source_annotation) for file in os.listdir(augmented_training_source): if file.startswith('rot3_90_rot2_90_flip_'): os.remove(os.path.join(augmented_training_source,file)) os.remove(os.path.join(augmented_training_source_annotation, os.path.splitext(file)[0]+'.xml')) if file.startswith('rot3_90_rot1_90_flip_'): os.remove(os.path.join(augmented_training_source,file)) os.remove(os.path.join(augmented_training_source_annotation, os.path.splitext(file)[0]+'.xml')) if file.startswith('rot3_90_flip_'): os.remove(os.path.join(augmented_training_source,file)) os.remove(os.path.join(augmented_training_source_annotation, os.path.splitext(file)[0]+'.xml')) if file.startswith('rot2_90_flip_'): os.remove(os.path.join(augmented_training_source,file)) os.remove(os.path.join(augmented_training_source_annotation, os.path.splitext(file)[0]+'.xml')) if multiply_dataset_by > 5: print('And again') augmented_images_5_df = image_aug(labels_df, Training_Source+'/', augmented_training_source+'/', 'rot_90_', aug_2) all_aug_labels_df_5 = pd.concat([all_aug_labels_df_4,augmented_images_5_df]) for file in os.listdir(augmented_training_source_annotation): os.remove(os.path.join(augmented_training_source_annotation,file)) convert_to_xml(all_aug_labels_df_5,augmented_training_source,augmented_training_source_annotation) if multiply_dataset_by > 6: print('And again') augmented_images_df_6 = image_aug(labels_df, Training_Source+'/', augmented_training_source+'/', 'rot_180_', aug_3) all_aug_labels_df_6 = pd.concat([all_aug_labels_df_5,augmented_images_df_6]) for file in os.listdir(augmented_training_source_annotation): os.remove(os.path.join(augmented_training_source_annotation,file)) convert_to_xml(all_aug_labels_df_6,augmented_training_source,augmented_training_source_annotation) if multiply_dataset_by > 7: print('And again') augmented_images_df_7 = image_aug(labels_df, Training_Source+'/', augmented_training_source+'/', 'rot_270_', aug_4) all_aug_labels_df_7 = pd.concat([all_aug_labels_df_6,augmented_images_df_7]) for file in os.listdir(augmented_training_source_annotation): os.remove(os.path.join(augmented_training_source_annotation,file)) convert_to_xml(all_aug_labels_df_7,augmented_training_source,augmented_training_source_annotation) for file in os.listdir(Training_Source): shutil.copyfile(Training_Source+'/'+file,augmented_training_source+'/'+file) shutil.copyfile(Training_Source_annotations+'/'+os.path.splitext(file)[0]+'.xml',augmented_training_source_annotation+'/'+os.path.splitext(file)[0]+'.xml') # display new dataframe #augmented_images_df # os.chdir('/content/gdrive/My Drive/keras-yolo2') # #Change the name of the training folder # !sed -i 's@\"train_image_folder\":.*,@\"train_image_folder\": \"$augmented_training_source/\",@g' config.json # #Change annotation folder # !sed -i 's@\"train_annot_folder\":.*,@\"train_annot_folder\": \"$augmented_training_source_annotation/\",@g' config.json df_anno = [] dir_anno = augmented_training_source_annotation for fnm in os.listdir(dir_anno): if not fnm.startswith('.'): ## do not include hidden folders/files tree = ET.parse(os.path.join(dir_anno,fnm)) row = extract_single_xml_file(tree) row["fileID"] = os.path.splitext(fnm)[0] df_anno.append(row) df_anno = pd.DataFrame(df_anno) maxNobj = np.max(df_anno["Nobj"]) #Write the annotations to a csv file #df_anno.to_csv(model_path+'/annot.csv', index=False)#header=False, sep=',') #Show how many objects there are in the images plt.figure() plt.subplot(2,1,1) plt.hist(df_anno["Nobj"].values,bins=50) plt.title("max N of objects per image={}".format(maxNobj)) plt.show() #Show the classes and how many there are of each in the dataset class_obj = [] for ibbx in range(maxNobj): class_obj.extend(df_anno["bbx_{}_name".format(ibbx)].values) class_obj = np.array(class_obj) count = Counter(class_obj[class_obj != 'nan']) print(count) class_nm = list(count.keys()) class_labels = json.dumps(class_nm) class_count = list(count.values()) asort_class_count = np.argsort(class_count) class_nm = np.array(class_nm)[asort_class_count] class_count = np.array(class_count)[asort_class_count] xs = range(len(class_count)) plt.subplot(2,1,2) plt.barh(xs,class_count) plt.yticks(xs,class_nm) plt.title("The number of objects per class: {} objects in total".format(len(count))) plt.show() else: print('No augmentation will be used') pdf_export(augmentation = Use_Data_augmentation, pretrained_model = Use_pretrained_model) #@markdown ###Play this cell to visualise some example images from your **augmented** dataset to make sure annotations and images are properly matched. if (Use_Data_augmentation): df_anno_aug = [] dir_anno_aug = augmented_training_source_annotation for fnm in os.listdir(dir_anno_aug): if not fnm.startswith('.'): ## do not include hidden folders/files tree = ET.parse(os.path.join(dir_anno_aug,fnm)) row = extract_single_xml_file(tree) row["fileID"] = os.path.splitext(fnm)[0] df_anno_aug.append(row) df_anno_aug = pd.DataFrame(df_anno_aug) size = 3 ind_random = np.random.randint(0,df_anno_aug.shape[0],size=size) img_dir=augmented_training_source file_suffix = os.path.splitext(os.listdir(augmented_training_source)[0])[1] for irow in ind_random: row = df_anno_aug.iloc[irow,:] path = os.path.join(img_dir, row["fileID"] + file_suffix) # read in image img = imageio.imread(path) plt.figure(figsize=(12,12)) plt.imshow(img, cmap='gray') # plot image plt.title("Nobj={}, height={}, width={}".format(row["Nobj"],row["height"],row["width"])) # for each object in the image, plot the bounding box for iplot in range(row["Nobj"]): plt_rectangle(plt, label = row["bbx_{}_name".format(iplot)], x1=row["bbx_{}_xmin".format(iplot)], y1=row["bbx_{}_ymin".format(iplot)], x2=row["bbx_{}_xmax".format(iplot)], y2=row["bbx_{}_ymax".format(iplot)]) plt.show() ## show the plot print('These are the augmented training images.') else: print('Data augmentation disabled.') # else: # for irow in ind_random: # row = df_anno.iloc[irow,:] # path = os.path.join(img_dir, row["fileID"] + file_suffix) # # read in image # img = imageio.imread(path) # plt.figure(figsize=(12,12)) # plt.imshow(img, cmap='gray') # plot image # plt.title("Nobj={}, height={}, width={}".format(row["Nobj"],row["height"],row["width"])) # # for each object in the image, plot the bounding box # for iplot in range(row["Nobj"]): # plt_rectangle(plt, # label = row["bbx_{}_name".format(iplot)], # x1=row["bbx_{}_xmin".format(iplot)], # y1=row["bbx_{}_ymin".format(iplot)], # x2=row["bbx_{}_xmax".format(iplot)], # y2=row["bbx_{}_ymax".format(iplot)]) # plt.show() ## show the plot # print('These are the non-augmented training images.') ``` ## **3.3. Using weights from a pre-trained model as initial weights** --- <font size = 4> Here, you can set the the path to a pre-trained model from which the weights can be extracted and used as a starting point for this training session. **This pre-trained model needs to be a YOLOv2 model**. <font size = 4> This option allows you to perform training over multiple Colab runtimes or to do transfer learning using models trained outside of ZeroCostDL4Mic. **You do not need to run this section if you want to train a network from scratch**. <font size = 4> In order to continue training from the point where the pre-trained model left off, it is adviseable to also **load the learning rate** that was used when the training ended. This is automatically saved for models trained with ZeroCostDL4Mic and will be loaded here. If no learning rate can be found in the model folder provided, the default learning rate will be used. ``` # @markdown ##Loading weights from a pretrained network # Training_Source = "" #@param{type:"string"} # Training_Source_annotation = "" #@param{type:"string"} # Check if the right files exist Use_pretrained_model = False #@param {type:"boolean"} Weights_choice = "best" #@param ["last", "best"] pretrained_model_path = "" #@param{type:"string"} h5_file_path = pretrained_model_path+'/'+Weights_choice+'_weights.h5' if not os.path.exists(h5_file_path) and Use_pretrained_model: print('WARNING pretrained model does not exist') Use_pretrained_model = False # os.chdir('/content/gdrive/My Drive/keras-yolo2') # !sed -i 's@\"pretrained_weights\":.*,@\"pretrained_weights\": \"$h5_file_path\",@g' config.json if Use_pretrained_model: with open(os.path.join(pretrained_model_path, 'Quality Control', 'training_evaluation.csv'),'r') as csvfile: csvRead = pd.read_csv(csvfile, sep=',') if "learning rate" in csvRead.columns: #Here we check that the learning rate column exist (compatibility with model trained un ZeroCostDL4Mic bellow 1.4): print("pretrained network learning rate found") #find the last learning rate lastLearningRate = csvRead["learning rate"].iloc[-1] #Find the learning rate corresponding to the lowest validation loss min_val_loss = csvRead[csvRead['val_loss'] == min(csvRead['val_loss'])] #print(min_val_loss) bestLearningRate = min_val_loss['learning rate'].iloc[-1] if Weights_choice == "last": print('Last learning rate: '+str(lastLearningRate)) learning_rate = lastLearningRate if Weights_choice == "best": print('Learning rate of best validation loss: '+str(bestLearningRate)) learning_rate = bestLearningRate if not "learning rate" in csvRead.columns: #if the column does not exist, then initial learning rate is used instead #bestLearningRate = learning_rate #lastLearningRate = learning_rate print(bcolors.WARNING+'WARNING: The learning rate cannot be identified from the pretrained network. Default learning rate of '+str(bestLearningRate)+' will be used instead' + W) else: print('No pre-trained models will be used.') # !sed -i 's@\"warmup_epochs\":.*,@\"warmup_epochs\": 0,@g' config.json # !sed -i 's@\"learning_rate\":.*,@\"learning_rate\": $learning_rate,@g' config.json # with open(os.path.join(pretrained_model_path, 'Quality Control', 'lr.csv'),'r') as csvfile: # csvRead = pd.read_csv(csvfile, sep=',') # #print(csvRead) # if "learning rate" in csvRead.columns: #Here we check that the learning rate column exist (compatibility with model trained un ZeroCostDL4Mic bellow 1.4) # print("pretrained network learning rate found") # #find the last learning rate # lastLearningRate = csvRead["learning rate"].iloc[-1] # #Find the learning rate corresponding to the lowest validation loss # min_val_loss = csvRead[csvRead['val_loss'] == min(csvRead['val_loss'])] # #print(min_val_loss) # bestLearningRate = min_val_loss['learning rate'].iloc[-1] # if Weights_choice == "last": # print('Last learning rate: '+str(lastLearningRate)) # if Weights_choice == "best": # print('Learning rate of best validation loss: '+str(bestLearningRate)) # if not "learning rate" in csvRead.columns: #if the column does not exist, then initial learning rate is used instead # bestLearningRate = initial_learning_rate # lastLearningRate = initial_learning_rate # print(bcolors.WARNING+'WARNING: The learning rate cannot be identified from the pretrained network. Default learning rate of '+str(bestLearningRate)+' will be used instead' + W) pdf_export(augmentation = Use_Data_augmentation, pretrained_model = Use_pretrained_model) ``` #**4. Train the network** --- ## **4.1. Start training** --- <font size = 4>When playing the cell below you should see updates after each epoch (round). Network training can take some time. <font size = 4>* **CRITICAL NOTE:** Google Colab has a time limit for processing (to prevent using GPU power for datamining). Training time must be less than 12 hours! If training takes longer than 12 hours, please decrease the number of epochs or number of patches. <font size = 4>Once training is complete, the trained model is automatically saved on your Google Drive, in the **model_path** folder that was selected in Section 3. It is however wise to download the folder as all data can be erased at the next training if using the same folder. ``` #@markdown ##Start training # full_model_path = os.path.join(model_path,model_name) # if os.path.exists(full_model_path): # print(bcolors.WARNING+'Model folder already exists and has been overwritten.'+bcolors.NORMAL) # shutil.rmtree(full_model_path) # # Create a new directory # os.mkdir(full_model_path) # ------------ os.chdir('/content/gdrive/My Drive/keras-yolo2') if backend == "Full Yolo": if not os.path.exists('/content/gdrive/My Drive/keras-yolo2/full_yolo_backend.h5'): !wget https://github.com/rodrigo2019/keras_yolo2/releases/download/pre-trained-weights/full_yolo_backend.h5 elif backend == "Inception3": if not os.path.exists('/content/gdrive/My Drive/keras-yolo2/inception_backend.h5'): !wget https://github.com/rodrigo2019/keras_yolo2/releases/download/pre-trained-weights/inception_backend.h5 elif backend == "MobileNet": if not os.path.exists('/content/gdrive/My Drive/keras-yolo2/mobilenet_backend.h5'): !wget https://github.com/rodrigo2019/keras_yolo2/releases/download/pre-trained-weights/mobilenet_backend.h5 elif backend == "SqueezeNet": if not os.path.exists('/content/gdrive/My Drive/keras-yolo2/squeezenet_backend.h5'): !wget https://github.com/rodrigo2019/keras_yolo2/releases/download/pre-trained-weights/squeezenet_backend.h5 elif backend == "Tiny Yolo": if not os.path.exists('/content/gdrive/My Drive/keras-yolo2/tiny_yolo_backend.h5'): !wget https://github.com/rodrigo2019/keras_yolo2/releases/download/pre-trained-weights/tiny_yolo_backend.h5 #os.chdir('/content/drive/My Drive/Zero-Cost Deep-Learning to Enhance Microscopy/Various dataset/Detection_Dataset_2/BCCD.v2.voc') #if not os.path.exists(model_path+'/full_raccoon.h5'): # !wget --load-cookies /tmp/cookies.txt "https://docs.google.com/uc?export=download&confirm=$(wget --quiet --save-cookies /tmp/cookies.txt --keep-session-cookies --no-check-certificate 'https://docs.google.com/uc?export=download&id=1NWbrpMGLc84ow-4gXn2mloFocFGU595s' -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1\n/p')&id=1NWbrpMGLc84ow-4gXn2mloFocFGU595s" -O full_yolo_raccoon.h5 && rm -rf /tmp/cookies.txt full_model_file_path = full_model_path+'/best_weights.h5' os.chdir('/content/gdrive/My Drive/keras-yolo2/') #Change backend name !sed -i 's@\"backend\":.*,@\"backend\": \"$backend\",@g' config.json #Change the name of the training folder !sed -i 's@\"train_image_folder\":.*,@\"train_image_folder\": \"$Training_Source/\",@g' config.json #Change annotation folder !sed -i 's@\"train_annot_folder\":.*,@\"train_annot_folder\": \"$Training_Source_annotations/\",@g' config.json #Change the name of the saved model !sed -i 's@\"saved_weights_name\":.*,@\"saved_weights_name\": \"$full_model_file_path\",@g' config.json #Change warmup epochs for untrained model !sed -i 's@\"warmup_epochs\":.*,@\"warmup_epochs\": 3,@g' config.json #When defining a new model we should reset the pretrained model parameter !sed -i 's@\"pretrained_weights\":.*,@\"pretrained_weights\": \"No_pretrained_weights\",@g' config.json !sed -i 's@\"nb_epochs\":.*,@\"nb_epochs\": $number_of_epochs,@g' config.json !sed -i 's@\"train_times\":.*,@\"train_times\": $train_times,@g' config.json !sed -i 's@\"batch_size\":.*,@\"batch_size\": $batch_size,@g' config.json !sed -i 's@\"learning_rate\":.*,@\"learning_rate\": $learning_rate,@g' config.json !sed -i 's@\"object_scale":.*,@\"object_scale\": $false_negative_penalty,@g' config.json !sed -i 's@\"no_object_scale":.*,@\"no_object_scale\": $false_positive_penalty,@g' config.json !sed -i 's@\"coord_scale\":.*,@\"coord_scale\": $position_size_penalty,@g' config.json !sed -i 's@\"class_scale\":.*,@\"class_scale\": $false_class_penalty,@g' config.json #Write the annotations to a csv file df_anno.to_csv(full_model_path+'/annotations.csv', index=False)#header=False, sep=',') !sed -i 's@\"labels\":.*@\"labels\": $class_labels@g' config.json #Generate anchors for the bounding boxes os.chdir('/content/gdrive/My Drive/keras-yolo2') output = sp.getoutput('python ./gen_anchors.py -c ./config.json') anchors_1 = output.find("[") anchors_2 = output.find("]") config_anchors = output[anchors_1:anchors_2+1] !sed -i 's@\"anchors\":.*,@\"anchors\": $config_anchors,@g' config.json !sed -i 's@\"pretrained_weights\":.*,@\"pretrained_weights\": \"$h5_file_path\",@g' config.json # !sed -i 's@\"anchors\":.*,@\"anchors\": $config_anchors,@g' config.json if Use_pretrained_model: !sed -i 's@\"warmup_epochs\":.*,@\"warmup_epochs\": 0,@g' config.json !sed -i 's@\"learning_rate\":.*,@\"learning_rate\": $learning_rate,@g' config.json if Use_Data_augmentation: # os.chdir('/content/gdrive/My Drive/keras-yolo2') #Change the name of the training folder !sed -i 's@\"train_image_folder\":.*,@\"train_image_folder\": \"$augmented_training_source/\",@g' config.json #Change annotation folder !sed -i 's@\"train_annot_folder\":.*,@\"train_annot_folder\": \"$augmented_training_source_annotation/\",@g' config.json # ------------ if os.path.exists(full_model_path+"/Quality Control"): shutil.rmtree(full_model_path+"/Quality Control") os.makedirs(full_model_path+"/Quality Control") start = time.time() os.chdir('/content/gdrive/My Drive/keras-yolo2') train('config.json', full_model_path, percentage_validation) shutil.copyfile('/content/gdrive/My Drive/keras-yolo2/config.json',full_model_path+'/config.json') if os.path.exists('/content/gdrive/My Drive/keras-yolo2/best_map_weights.h5'): shutil.move('/content/gdrive/My Drive/keras-yolo2/best_map_weights.h5',full_model_path+'/best_map_weights.h5') # Displaying the time elapsed for training dt = time.time() - start mins, sec = divmod(dt, 60) hour, mins = divmod(mins, 60) print("Time elapsed:",hour, "hour(s)",mins,"min(s)",round(sec),"sec(s)") #Create a pdf document with training summary pdf_export(trained = True, augmentation = Use_Data_augmentation, pretrained_model = Use_pretrained_model) ``` # **5. Evaluate your model** --- <font size = 4>This section allows the user to perform important quality checks on the validity and generalisability of the trained model. <font size = 4>**We highly recommend to perform quality control on all newly trained models.** ``` # model name and path #@markdown ###Do you want to assess the model you just trained ? Use_the_current_trained_model = False #@param {type:"boolean"} #@markdown ###If not, please provide the name of the model folder: QC_model_folder = "" #@param {type:"string"} if (Use_the_current_trained_model): QC_model_folder = full_model_path #print(os.path.join(model_path, model_name)) QC_model_name = os.path.basename(QC_model_folder) if os.path.exists(QC_model_folder): print("The "+QC_model_name+" model will be evaluated") else: W = '\033[0m' # white (normal) R = '\033[31m' # red print(R+'!! WARNING: The chosen model does not exist !!'+W) print('Please make sure you provide a valid model path before proceeding further.') if Use_the_current_trained_model == False: if os.path.exists('/content/gdrive/My Drive/keras-yolo2/config.json'): os.remove('/content/gdrive/My Drive/keras-yolo2/config.json') shutil.copyfile(QC_model_folder+'/config.json','/content/gdrive/My Drive/keras-yolo2/config.json') #@markdown ###Which backend is the model using? backend = "Full Yolo" #@param ["Select Model","Full Yolo","Inception3","SqueezeNet","MobileNet","Tiny Yolo"] os.chdir('/content/gdrive/My Drive/keras-yolo2') if backend == "Full Yolo": if not os.path.exists('/content/gdrive/My Drive/keras-yolo2/full_yolo_backend.h5'): !wget https://github.com/rodrigo2019/keras_yolo2/releases/download/pre-trained-weights/full_yolo_backend.h5 elif backend == "Inception3": if not os.path.exists('/content/gdrive/My Drive/keras-yolo2/inception_backend.h5'): !wget https://github.com/rodrigo2019/keras_yolo2/releases/download/pre-trained-weights/inception_backend.h5 elif backend == "MobileNet": if not os.path.exists('/content/gdrive/My Drive/keras-yolo2/mobilenet_backend.h5'): !wget https://github.com/rodrigo2019/keras_yolo2/releases/download/pre-trained-weights/mobilenet_backend.h5 elif backend == "SqueezeNet": if not os.path.exists('/content/gdrive/My Drive/keras-yolo2/squeezenet_backend.h5'): !wget https://github.com/rodrigo2019/keras_yolo2/releases/download/pre-trained-weights/squeezenet_backend.h5 elif backend == "Tiny Yolo": if not os.path.exists('/content/gdrive/My Drive/keras-yolo2/tiny_yolo_backend.h5'): !wget https://github.com/rodrigo2019/keras_yolo2/releases/download/pre-trained-weights/tiny_yolo_backend.h5 ``` ## **5.1. Inspection of the loss function** --- <font size = 4>First, it is good practice to evaluate the training progress by comparing the training loss with the validation loss. The latter is a metric which shows how well the network performs on a subset of unseen data which is set aside from the training dataset. For more information on this, see for example [this review](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC6381354/) by Nichols *et al.* <font size = 4>**Training loss** describes an error value after each epoch for the difference between the model's prediction and its ground-truth target. <font size = 4>**Validation loss** describes the same error value between the model's prediction on a validation image and compared to it's target. <font size = 4>During training both values should decrease before reaching a minimal value which does not decrease further even after more training. Comparing the development of the validation loss with the training loss can give insights into the model's performance. <font size = 4>Decreasing **Training loss** and **Validation loss** indicates that training is still necessary and increasing the `number_of_epochs` is recommended. Note that the curves can look flat towards the right side, just because of the y-axis scaling. The network has reached convergence once the curves flatten out. After this point no further training is required. If the **Validation loss** suddenly increases again an the **Training loss** simultaneously goes towards zero, it means that the network is overfitting to the training data. In other words the network is remembering the exact patterns from the training data and no longer generalizes well to unseen data. In this case the training dataset has to be increased. ``` #@markdown ##Play the cell to show a plot of training errors vs. epoch number import csv from matplotlib import pyplot as plt lossDataFromCSV = [] vallossDataFromCSV = [] mAPDataFromCSV = [] with open(QC_model_folder+'/Quality Control/training_evaluation.csv','r') as csvfile: csvRead = csv.reader(csvfile, delimiter=',') next(csvRead) for row in csvRead: lossDataFromCSV.append(float(row[0])) vallossDataFromCSV.append(float(row[1])) mAPDataFromCSV.append(float(row[2])) epochNumber = range(len(lossDataFromCSV)) plt.figure(figsize=(20,15)) plt.subplot(3,1,1) plt.plot(epochNumber,lossDataFromCSV, label='Training loss') plt.plot(epochNumber,vallossDataFromCSV, label='Validation loss') plt.title('Training loss and validation loss vs. epoch number (linear scale)') plt.ylabel('Loss') plt.xlabel('Epoch number') plt.legend() plt.subplot(3,1,2) plt.semilogy(epochNumber,lossDataFromCSV, label='Training loss') plt.semilogy(epochNumber,vallossDataFromCSV, label='Validation loss') plt.title('Training loss and validation loss vs. epoch number (log scale)') plt.ylabel('Loss') plt.xlabel('Epoch number') plt.legend() #plt.savefig(os.path.dirname(QC_model_folder)+'/Quality Control/lossCurvePlots.png') #plt.show() plt.subplot(3,1,3) plt.plot(epochNumber,mAPDataFromCSV, label='mAP score') plt.title('mean average precision (mAP) vs. epoch number (linear scale)') plt.ylabel('mAP score') plt.xlabel('Epoch number') plt.legend() plt.savefig(QC_model_folder+'/Quality Control/lossCurveAndmAPPlots.png',bbox_inches='tight', pad_inches=0) plt.show() ``` ## **5.2. Error mapping and quality metrics estimation** --- <font size = 4>This section will display an overlay of the input images ground-truth (solid lines) and predicted boxes (dashed lines). Additionally, the below cell will show the mAP value of the model on the QC data together with plots of the Precision-Recall curves for all the classes in the dataset. If you want to read in more detail about these scores, we recommend [this brief explanation](https://medium.com/@jonathan_hui/map-mean-average-precision-for-object-detection-45c121a31173). <font size = 4> The images provided in the "Source_QC_folder" and "Target_QC_folder" should contain images (e.g. as .jpg)and annotations (.xml files)! <font size = 4>Since the training saves three different models, for the best validation loss (`best_weights`), best average precision (`best_mAP_weights`) and the model after the last epoch (`last_weights`), you should choose which ones you want to use for quality control or prediction. We recommend using `best_map_weights` because they should yield the best performance on the dataset. However, it can be worth testing how well `best_weights` perform too. <font size = 4>**mAP score:** This refers to the mean average precision of the model on the given dataset. This value gives an indication how precise the predictions of the classes on this dataset are when compared to the ground-truth. Values closer to 1 indicate a good fit. <font size = 4>**Precision:** This is the proportion of the correct classifications (true positives) in all the predictions made by the model. <font size = 4>**Recall:** This is the proportion of the detected true positives in all the detectable data. ``` #@markdown ##Choose the folders that contain your Quality Control dataset Source_QC_folder = "" #@param{type:"string"} Annotations_QC_folder = "" #@param{type:"string"} #@markdown ##Choose which model you want to evaluate: model_choice = "best_weights" #@param["best_weights","last_weights","best_map_weights"] file_suffix = os.path.splitext(os.listdir(Source_QC_folder)[0])[1] # Create a quality control/Prediction Folder if os.path.exists(QC_model_folder+"/Quality Control/Prediction"): shutil.rmtree(QC_model_folder+"/Quality Control/Prediction") os.makedirs(QC_model_folder+"/Quality Control/Prediction") #Delete old csv with box predictions if one exists if os.path.exists('/content/predicted_bounding_boxes.csv'): os.remove('/content/predicted_bounding_boxes.csv') if os.path.exists('/content/predicted_bounding_boxes_names.csv'): os.remove('/content/predicted_bounding_boxes_names.csv') if os.path.exists(Source_QC_folder+'/.ipynb_checkpoints'): shutil.rmtree(Source_QC_folder+'/.ipynb_checkpoints') os.chdir('/content/gdrive/My Drive/keras-yolo2') n_objects = [] for img in os.listdir(Source_QC_folder): full_image_path = Source_QC_folder+'/'+img print('----') print(img) n_obj = predict('config.json',QC_model_folder+'/'+model_choice+'.h5',full_image_path) n_objects.append(n_obj) K.clear_session() for img in os.listdir(Source_QC_folder): if img.endswith('detected'+file_suffix): shutil.move(Source_QC_folder+'/'+img,QC_model_folder+"/Quality Control/Prediction/"+img) #Here, we open the config file to get the classes fro the GT labels config_path = '/content/gdrive/My Drive/keras-yolo2/config.json' with open(config_path) as config_buffer: config = json.load(config_buffer) #Make a csv file to read into imagej macro, to create custom bounding boxes header = ['filename']+['xmin', 'ymin', 'xmax', 'ymax', 'confidence', 'class']*max(n_objects) with open('/content/predicted_bounding_boxes.csv', newline='') as inFile, open('/content/predicted_bounding_boxes_new.csv', 'w', newline='') as outfile: r = csv.reader(inFile) w = csv.writer(outfile) next(r, None) # skip the first row from the reader, the old header # write new header w.writerow(header) # copy the rest for row in r: w.writerow(row) df_bbox=pd.read_csv('/content/predicted_bounding_boxes_new.csv') df_bbox=df_bbox.transpose() new_header = df_bbox.iloc[0] #grab the first row for the header df_bbox = df_bbox[1:] #take the data less the header row df_bbox.columns = new_header #set the header row as the df header df_bbox.sort_values(by='filename',axis=1,inplace=True) df_bbox.to_csv(QC_model_folder+'/Quality Control/predicted_bounding_boxes_for_custom_ROI_QC.csv') F1_scores, AP, recall, precision = _calc_avg_precisions(config,Source_QC_folder,Annotations_QC_folder+'/',QC_model_folder+'/'+model_choice+'.h5',0.3,0.3) with open(QC_model_folder+"/Quality Control/QC_results.csv", "r") as file: x = from_csv(file) print(x) mAP_score = sum(AP.values())/len(AP) print('mAP score for QC dataset: '+str(mAP_score)) for i in range(len(AP)): if AP[i]!=0: fig = plt.figure(figsize=(8,4)) if len(recall[i]) == 1: new_recall = np.linspace(0,list(recall[i])[0],10) new_precision = list(precision[i])*10 fig = plt.figure(figsize=(3,2)) plt.plot(new_recall,new_precision) plt.axis([min(new_recall),1,0,1.02]) plt.xlabel('Recall',fontsize=14) plt.ylabel('Precision',fontsize=14) plt.title(config['model']['labels'][i]+', AP: '+str(round(AP[i],3)),fontsize=14) plt.fill_between(new_recall,new_precision,alpha=0.3) plt.savefig(QC_model_folder+'/Quality Control/P-R_curve_'+config['model']['labels'][i]+'.png', bbox_inches='tight', pad_inches=0) plt.show() else: new_recall = list(recall[i]) new_recall.append(new_recall[len(new_recall)-1]) new_precision = list(precision[i]) new_precision.append(0) plt.plot(new_recall,new_precision) plt.axis([min(new_recall),1,0,1.02]) plt.xlabel('Recall',fontsize=14) plt.ylabel('Precision',fontsize=14) plt.title(config['model']['labels'][i]+', AP: '+str(round(AP[i],3)),fontsize=14) plt.fill_between(new_recall,new_precision,alpha=0.3) plt.savefig(QC_model_folder+'/Quality Control/P-R_curve_'+config['model']['labels'][i]+'.png', bbox_inches='tight', pad_inches=0) plt.show() else: print('No object of class '+config['model']['labels'][i]+' was detected. This will lower the mAP score. Consider adding an image containing this class to your QC dataset to see if the model can detect this class at all.') # -------------------------------------------------------------- add_header('/content/predicted_bounding_boxes_names.csv','/content/predicted_bounding_boxes_names_new.csv') # This will display a randomly chosen dataset input and predicted output print('Below is an example input, prediction and ground truth annotation from your test dataset.') random_choice = random.choice(os.listdir(Source_QC_folder)) file_suffix = os.path.splitext(random_choice)[1] plt.figure(figsize=(30,15)) ### Display Raw input ### x = plt.imread(Source_QC_folder+"/"+random_choice) plt.subplot(1,3,1) plt.axis('off') plt.imshow(x, interpolation='nearest', cmap='gray') plt.title('Input', fontsize = 12) ### Display Predicted annotation ### df_bbox2 = pd.read_csv('/content/predicted_bounding_boxes_names_new.csv') for img in range(0,df_bbox2.shape[0]): df_bbox2.iloc[img] row = pd.DataFrame(df_bbox2.iloc[img]) if row[img][0] == random_choice: row = row.dropna() image = imageio.imread(Source_QC_folder+'/'+row[img][0]) #plt.figure(figsize=(12,12)) plt.subplot(1,3,2) plt.axis('off') plt.imshow(image, cmap='gray') # plot image plt.title('Prediction', fontsize=12) for i in range(1,int(len(row)-1),6): plt_rectangle(plt, label = row[img][i+5], x1=row[img][i],#.format(iplot)], y1=row[img][i+1], x2=row[img][i+2], y2=row[img][i+3])#, #fontsize=8) ### Display GT Annotation ### df_anno_QC_gt = [] for fnm in os.listdir(Annotations_QC_folder): if not fnm.startswith('.'): ## do not include hidden folders/files tree = ET.parse(os.path.join(Annotations_QC_folder,fnm)) row = extract_single_xml_file(tree) row["fileID"] = os.path.splitext(fnm)[0] df_anno_QC_gt.append(row) df_anno_QC_gt = pd.DataFrame(df_anno_QC_gt) #maxNobj = np.max(df_anno_QC_gt["Nobj"]) for i in range(0,df_anno_QC_gt.shape[0]): if df_anno_QC_gt.iloc[i]["fileID"]+file_suffix == random_choice: row = df_anno_QC_gt.iloc[i] img = imageio.imread(Source_QC_folder+'/'+random_choice) plt.subplot(1,3,3) plt.axis('off') plt.imshow(img, cmap='gray') # plot image plt.title('Ground Truth annotations', fontsize=12) # for each object in the image, plot the bounding box for iplot in range(row["Nobj"]): plt_rectangle(plt, label = row["bbx_{}_name".format(iplot)], x1=row["bbx_{}_xmin".format(iplot)], y1=row["bbx_{}_ymin".format(iplot)], x2=row["bbx_{}_xmax".format(iplot)], y2=row["bbx_{}_ymax".format(iplot)])#, #fontsize=8) ### Show the plot ### plt.savefig(QC_model_folder+'/Quality Control/QC_example_data.png',bbox_inches='tight',pad_inches=0) plt.show() #Make a pdf summary of the QC results qc_pdf_export() ``` # **6. Using the trained model** --- <font size = 4>In this section the unseen data is processed using the trained model (in section 4). First, your unseen images are uploaded and prepared for prediction. After that your trained model from section 4 is activated and finally saved into your Google Drive. ## **6.1. Generate prediction(s) from unseen dataset** --- <font size = 4>The current trained model (from section 4.2) can now be used to process images. If you want to use an older model, untick the **Use_the_current_trained_model** box and enter the name and path of the model to use. Predicted output images are saved in your **Result_folder** folder as restored image stacks (ImageJ-compatible TIFF images). <font size = 4>**`Data_folder`:** This folder should contain the images that you want to use your trained network on for processing. <font size = 4>**`Result_folder`:** This folder will contain the predicted output images. <font size = 4>**`Prediction_model_path`:** This should be the folder that contains your model. ``` #@markdown ### Provide the path to your dataset and to the folder where the predictions are saved, then play the cell to predict outputs from your unseen images. Data_folder = "" #@param {type:"string"} Result_folder = "" #@param {type:"string"} file_suffix = os.path.splitext(os.listdir(Data_folder)[0])[1] # model name and path #@markdown ###Do you want to use the current trained model? Use_the_current_trained_model = True #@param {type:"boolean"} #@markdown ###If not, provide the name of the model and path to model folder: Prediction_model_path = "" #@param {type:"string"} #@markdown ###Which model do you want to use? model_choice = "best_map_weights" #@param["best_weights","last_weights","best_map_weights"] #@markdown ###Which backend is the model using? backend = "Full Yolo" #@param ["Select Model","Full Yolo","Inception3","SqueezeNet","MobileNet","Tiny Yolo"] os.chdir('/content/gdrive/My Drive/keras-yolo2') if backend == "Full Yolo": if not os.path.exists('/content/gdrive/My Drive/keras-yolo2/full_yolo_backend.h5'): !wget https://github.com/rodrigo2019/keras_yolo2/releases/download/pre-trained-weights/full_yolo_backend.h5 elif backend == "Inception3": if not os.path.exists('/content/gdrive/My Drive/keras-yolo2/inception_backend.h5'): !wget https://github.com/rodrigo2019/keras_yolo2/releases/download/pre-trained-weights/inception_backend.h5 elif backend == "MobileNet": if not os.path.exists('/content/gdrive/My Drive/keras-yolo2/mobilenet_backend.h5'): !wget https://github.com/rodrigo2019/keras_yolo2/releases/download/pre-trained-weights/mobilenet_backend.h5 elif backend == "SqueezeNet": if not os.path.exists('/content/gdrive/My Drive/keras-yolo2/squeezenet_backend.h5'): !wget https://github.com/rodrigo2019/keras_yolo2/releases/download/pre-trained-weights/squeezenet_backend.h5 elif backend == "Tiny Yolo": if not os.path.exists('/content/gdrive/My Drive/keras-yolo2/tiny_yolo_backend.h5'): !wget https://github.com/rodrigo2019/keras_yolo2/releases/download/pre-trained-weights/tiny_yolo_backend.h5 if (Use_the_current_trained_model): print("Using current trained network") Prediction_model_path = full_model_path if Use_the_current_trained_model == False: if os.path.exists('/content/gdrive/My Drive/keras-yolo2/config.json'): os.remove('/content/gdrive/My Drive/keras-yolo2/config.json') shutil.copyfile(Prediction_model_path+'/config.json','/content/gdrive/My Drive/keras-yolo2/config.json') if os.path.exists(Prediction_model_path+'/'+model_choice+'.h5'): print("The "+os.path.basename(Prediction_model_path)+" network will be used.") else: W = '\033[0m' # white (normal) R = '\033[31m' # red print(R+'!! WARNING: The chosen model does not exist !!'+W) print('Please make sure you provide a valid model path and model name before proceeding further.') # Provide the code for performing predictions and saving them print("Images will be saved into folder:", Result_folder) # ----- Predictions ------ start = time.time() #Remove any files that might be from the prediction of QC examples. if os.path.exists('/content/predicted_bounding_boxes.csv'): os.remove('/content/predicted_bounding_boxes.csv') if os.path.exists('/content/predicted_bounding_boxes_new.csv'): os.remove('/content/predicted_bounding_boxes_new.csv') if os.path.exists('/content/predicted_bounding_boxes_names.csv'): os.remove('/content/predicted_bounding_boxes_names.csv') if os.path.exists('/content/predicted_bounding_boxes_names_new.csv'): os.remove('/content/predicted_bounding_boxes_names_new.csv') os.chdir('/content/gdrive/My Drive/keras-yolo2') if os.path.exists(Data_folder+'/.ipynb_checkpoints'): shutil.rmtree(Data_folder+'/.ipynb_checkpoints') n_objects = [] for img in os.listdir(Data_folder): full_image_path = Data_folder+'/'+img n_obj = predict('config.json',Prediction_model_path+'/'+model_choice+'.h5',full_image_path)#,Result_folder) n_objects.append(n_obj) K.clear_session() for img in os.listdir(Data_folder): if img.endswith('detected'+file_suffix): shutil.move(Data_folder+'/'+img,Result_folder+'/'+img) if os.path.exists('/content/predicted_bounding_boxes.csv'): #shutil.move('/content/predicted_bounding_boxes.csv',Result_folder+'/predicted_bounding_boxes.csv') print('Bounding box labels and coordinates saved to '+ Result_folder) else: print('For some reason the bounding box labels and coordinates were not saved. Check that your predictions look as expected.') #Make a csv file to read into imagej macro, to create custom bounding boxes header = ['filename']+['xmin', 'ymin', 'xmax', 'ymax', 'confidence', 'class']*max(n_objects) with open('/content/predicted_bounding_boxes.csv', newline='') as inFile, open('/content/predicted_bounding_boxes_new.csv', 'w', newline='') as outfile: r = csv.reader(inFile) w = csv.writer(outfile) next(r, None) # skip the first row from the reader, the old header # write new header w.writerow(header) # copy the rest for row in r: w.writerow(row) df_bbox=pd.read_csv('/content/predicted_bounding_boxes_new.csv') df_bbox=df_bbox.transpose() new_header = df_bbox.iloc[0] #grab the first row for the header df_bbox = df_bbox[1:] #take the data less the header row df_bbox.columns = new_header #set the header row as the df header df_bbox.sort_values(by='filename',axis=1,inplace=True) df_bbox.to_csv(Result_folder+'/predicted_bounding_boxes_for_custom_ROI.csv') # Displaying the time elapsed for training dt = time.time() - start mins, sec = divmod(dt, 60) hour, mins = divmod(mins, 60) print("Time elapsed:",hour, "hour(s)",mins,"min(s)",round(sec),"sec(s)") ``` ## **6.2. Inspect the predicted output** --- ``` # @markdown ##Run this cell to display a randomly chosen input and its corresponding predicted output. import random from matplotlib.pyplot import imread # This will display a randomly chosen dataset input and predicted output random_choice = random.choice(os.listdir(Data_folder)) print(random_choice) x = imread(Data_folder+"/"+random_choice) os.chdir(Result_folder) y = imread(Result_folder+"/"+os.path.splitext(random_choice)[0]+'_detected'+file_suffix) plt.figure(figsize=(20,8)) plt.subplot(1,3,1) plt.axis('off') plt.imshow(x, interpolation='nearest', cmap='gray') plt.title('Input') plt.subplot(1,3,2) plt.axis('off') plt.imshow(y, interpolation='nearest') plt.title('Predicted output'); add_header('/content/predicted_bounding_boxes_names.csv','/content/predicted_bounding_boxes_names_new.csv') #We need to edit this predicted_bounding_boxes_new.csv file slightly to display the bounding boxes df_bbox2 = pd.read_csv('/content/predicted_bounding_boxes_names_new.csv') for img in range(0,df_bbox2.shape[0]): df_bbox2.iloc[img] row = pd.DataFrame(df_bbox2.iloc[img]) if row[img][0] == random_choice: row = row.dropna() image = imageio.imread(Data_folder+'/'+row[img][0]) #plt.figure(figsize=(12,12)) plt.subplot(1,3,3) plt.axis('off') plt.title('Alternative Display of Prediction') plt.imshow(image, cmap='gray') # plot image for i in range(1,int(len(row)-1),6): plt_rectangle(plt, label = row[img][i+5], x1=row[img][i],#.format(iplot)], y1=row[img][i+1], x2=row[img][i+2], y2=row[img][i+3])#, #fontsize=8) #plt.margins(0,0) #plt.subplots_adjust(left=0., right=1., top=1., bottom=0.) #plt.gca().xaxis.set_major_locator(plt.NullLocator()) #plt.gca().yaxis.set_major_locator(plt.NullLocator()) plt.savefig('/content/detected_cells.png',bbox_inches='tight',transparent=True,pad_inches=0) plt.show() ## show the plot ``` ## **6.3. Download your predictions** --- <font size = 4>**Store your data** and ALL its results elsewhere by downloading it from Google Drive and after that clean the original folder tree (datasets, results, trained model etc.) if you plan to train or use new networks. Please note that the notebook will otherwise **OVERWRITE** all files which have the same name. #**Thank you for using YOLOv2!**
github_jupyter
# 受講者の演習環境バックアップをリストアします --- バックアップした受講者の演習環境を展開します。 # バックアップファイルを指定します リストアするバックアップファルを指定します。 - ホームディレクトリからの相対パスで指定します。 - フォルダを指定した場合、フォルダ内の全ての `*.tgz` ファイルが対象となります。 - バックアップファイルがローカルマシンにある場合は、下記の手順でアップロードできます。 1. ブラウザのHome画面で、リストア作業用フォルダを開きます。 2. 画面右上の[Upload]ボタンをクリックします。ファイル選択ダイアログが開きます。 3. ファイルを選択して[開く]ボタンをクリックします。 バックアップファイル名がリストされます。 4. バックアップファイル名の行の右端に表示される[Upload]ボタンをクリックします。 **次のセルを実行して、バックアップファイルを設定してください。** ``` BACKUP_FILE='backup/0123/student-a01@example.com-backup.tgz' ``` # バックアップを展開します - バックアップはファイル名に含まれる名前の受講者のフォルダに展開されます。 - 同一のファイルは上書きされます。 ``` import os, sys, re, hashlib, string, tempfile, shutil, subprocess def get_username_from_mail_address(mail_address): # Convert to lower and remove characters except for alphabets and digits wk = mail_address.split('@') local_part = wk[0].lower() result = re.sub(r'[^a-zA-Z0-9]', '', local_part) # Add top 6bytes of hash string md5 = hashlib.md5() md5.update(mail_address.encode('us-ascii')) h = md5.hexdigest()[0:6] result += 'x' result += h; return result; try: BACKUP_FILE except NameError: BACKUP_FILE=None if BACKUP_FILE is None: print('BACKUP_FILE にバックアップファイルを指定してください', file=sys.stderr) SRC_PATH=None elif os.path.isabs(BACKUP_FILE): SRC_PATH=os.path.realpath(BACKUP_FILE) else: SRC_PATH=os.path.realpath(os.path.join(os.getenv('HOME'), BACKUP_FILE)) backup_files=set() if SRC_PATH is None: print('バックアップファイルがありません', file=sys.stderr) elif os.path.isdir(SRC_PATH): for (root, dirs, files) in os.walk(SRC_PATH): for file in files: path = os.path.join(root, file) if path.endswith('.tgz') or path.endswith('.tar.gz'): backup_files.add(os.path.realpath(path)) elif os.path.exists(SRC_PATH): print('mode SINGLE FILE') backup_files.add(os.path.realpath(SRC_PATH)) else: print('{}: バックアップファイルが見つかりません'.format(BACKUP_FILE), file=sys.stderr) # with tempfile.TemporaryDirectory() as tmp_dir: for tgzfile in backup_files: basename = os.path.basename(tgzfile) m = re.compile(r'^(.+)-backup\.(tgz|tar\.gz)$').match(basename) user_mail = m.group(1) if (m is not None) else None if (user_mail is None) or (len(user_mail) < 1): print('WARNING: 受講者名が不明のファイル: {}'.format(tgzfile)) continue print('受講者[{}]のバックアップを展開します'.format(user_mail)) user_name = get_username_from_mail_address(user_mail) user_dir_info = os.stat(os.path.join('/home/jupyter/workspace', user_name)) user_uid = user_dir_info.st_uid user_gid = user_dir_info.st_gid user_tmp_dir = '{}/{}'.format(tmp_dir, user_name) os.makedirs(user_tmp_dir, exist_ok=True) try: tarcmd = 'tar -xz -C "{}" -f "{}"'.format(user_tmp_dir, tgzfile) cp = subprocess.run(tarcmd, shell=True, cwd=user_tmp_dir, stderr=subprocess.PIPE) for line in cp.stderr.splitlines(): print('tar> {}'.format(line.strip().decode('utf-8')), file=sys.stderr) if cp.returncode != 0: print('ERROR: tar コマンドが失敗しました', file=sys.stderr) continue except OSError as e: print('ERROR: tar コマンドが実行できません:{}'.format(e), file=sys.stderr) continue user_dir = '/home/jupyter/workspace/{}'.format(user_name) try: cmd = 'cd {}'.format(tmp_dir) \ + ' && sudo -n -s mkdir -p "{}"'.format(user_dir) \ + ' && sudo -n -s rsync -vhi -rLkKEtW "{}/" "{}/"'.format(user_tmp_dir, user_dir) \ + ' && sudo -n -s chown -R {}:{} "{}/"'.format(user_uid, user_gid, user_dir) \ + ' && sudo -n -s find "{}/" -name ".*" -prune'.format(user_dir) \ + ' -o -type d -execdir chmod 0755 "{}" "+"' \ + ' && sudo -n -s find "{}/" -name ".*" -prune'.format(user_dir) \ + ' -o -type f -execdir chmod 0644 "{}" "+"' \ + ' && true' cp = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) for line in cp.stdout.splitlines(): print('rsync> {}'.format(line.strip().decode('utf-8'))) for line in cp.stderr.splitlines(): print('rsync> {}'.format(line.strip().decode('utf-8')), file=sys.stderr) if cp.returncode == 0: print('-> 完了') else: print('ERROR: rsync コマンドが失敗しました', file=sys.stderr) continue except OSError as e: print(type(e)) print('ERROR: rsync コマンドが実行できません:{}'.format(e), file=sys.stderr) continue ```
github_jupyter
# Principal Component Analysis (PCA) from Scratch > The world doesn't need a yet another PCA tutorial, just like the world doesn't need another silly love song. But sometimes you still get the urge to write your own - toc: true - branch: master - badges: true - comments: true - metadata_key1: metadata_value1 - metadata_key2: metadata_value2 - description: There are many tutorials on PCA, but this one has interactive 3D graphs! - image: https://i.imgur.com/vKiH8As.png - redirect_to: https://drscotthawley.github.io/blog/2019/12/21/PCA-From-Scratch.html ![splash pic i made](https://i.imgur.com/vKiH8As.png) ### Relevance Principal Component Analysis (PCA) is a data-reduction technique that finds application in a wide variety of fields, including biology, sociology, physics, medicine, and audio processing. PCA may be used as a "front end" processing step that feeds into additional layers of machine learning, or it may be used by itself, for example when doing data visualization. It is so useful and ubiquitious that is is worth learning not only what it is for and what it is, but how to actually *do* it. In this interactive worksheet, we work through how to perform PCA on a few different datasets, writing our own code as we go. ### Other (better?) treatments My treatment here was written several months after viewing... - the [excellent demo page at setosa.io](http://setosa.io/ev/principal-component-analysis/) - this quick [1m30s video of a teapot](https://www.youtube.com/watch?v=BfTMmoDFXyE), - this [great StatsQuest video](https://www.youtube.com/watch?v=FgakZw6K1QQ) - this [lecture from Andrew Ng's course](https://www.youtube.com/watch?v=rng04VJxUt4) ## Basic Idea Put simply, PCA involves making a coordinate transformation (i.e., a rotation) from the arbitrary axes (or "features") you started with to a set of axes 'aligned with the data itself,' and doing this almost always means that you can get rid of a few of these 'components' of data that have small variance without suffering much in the way of accurcy while saving yourself a *ton* of computation. <small>Once you "get it," you'll find PCA to be almost no big deal, if it weren't for the fact that it's so darn useful!</small> We'll define the following terms as we go, but here's the process in a nutshell: 1. Covariance: Find the *covariance matrix* for your dataset 2. Eigenvectors: Find the *eigenvectors* of that matrix (these are the "components" btw) 3. Ordering: Sort the eigenvectors/'dimensions' from biggest to smallest variance 4. Projection / Data reduction: Use the eigenvectors corresponding to the largest variance to project the dataset into a reduced- dimensional space 6. (Check: How much did we lose by that truncation?) # Caveats Since PCA will involve making linear transformations, there are some situations where PCA won't help but...pretty much it's handy enough that it's worth giving it a shot! # Covariance If you've got two data dimensions and they vary together, then they are co-variant. **Example:** Two-dimensional data that's somewhat co-linear: ``` import numpy as np import matplotlib.pyplot as plt import plotly.graph_objects as go N = 100 x = np.random.normal(size=N) y = 0.5*x + 0.2*(np.random.normal(size=N)) fig = go.Figure(data=[go.Scatter(x=x, y=y, mode='markers', marker=dict(size=8,opacity=0.5), name="data" )]) fig.update_layout( xaxis_title="x", yaxis_title="y", yaxis = dict(scaleanchor = "x",scaleratio = 1) ) fig.show() ``` ### Variance So, for just the $x$ component of the above data, there's some *mean* value (which in this case is zero), and there's some *variance* about this mean: technically **the variance is the average of the squared differences from the mean.** If you're familiar with the standard deviation, usually denoted by $\sigma$, the variance is just the square of the standard deviation. If $x$ had units of meters, the variance $\sigma^2$ would have units of meters^2. Think of the variance as the "spread," or "extent" of the data, about some particular axis (or input, or "feature"). Similarly we can look at the variance in just the $y$ component of the data. For the above data, the variances in $x$ and $y$ are ``` print("Variance in x =",np.var(x)) print("Variance in y =",np.var(y)) ``` ### Covariance You'll notice in the above graph that as $x$ varies, so does $y$ -- pretty much. So $y$ is "*covariant*" with $x$. ["Covariance indicates the level to which two variables vary together."](https://docs.scipy.org/doc/numpy/reference/generated/numpy.cov.html) To compute it, it's kind of like the regular variance, except that instead of squaring the deviation from the mean for one variable, we multiply the deviations for the two variables: $${\rm Cov}(x,y) = {1\over N-1}\sum_{j=1}^N (x_j-\mu_x)(y_j-\mu_j),$$ where $\mu_x$ and $\mu_y$ are the means for the x- and y- componenets of the data, respectively. Note that you can reverse $x$ and $y$ and get the same result, and the covariance of a variable with itself is just the regular variance -- but with one caveat! The caveat is that we're dividing by $N-1$ instead of $N$, so unlike the regular variance we're not quite taking the mean. Why this? Well, for large datasets this makes essentially no difference, but for small numbers of data points, using $N$ can give values that tend to be a bit too small for most people's tastes, so the $N-1$ was introduced to "reduce small sample bias." In Python code, the covariance calculation looks like ``` def covariance(a,b): return ( (a - a.mean())*(b - b.mean()) ).sum() / (len(a)-1) print("Covariance of x & y =",covariance(x,y)) print("Covariance of y & x =",covariance(x,y)) print("Covariance of x with itself =",covariance(x,x),", variance of x =",np.var(x)) print("Covariance of y with itself =",covariance(y,y),", variance of x =",np.var(y)) ``` ## Covariance matrix So what we do is we take the covariance of every variable with every variable (including itself) and make a matrix out of it. Along the diagonal will be the variance of each variable (except for that $N-1$ in the denominator), and the rest of the matrix will be the covariances. Note that since the order of the variables doesn't matter when computing covariance, the matrix will be *symmetric* (i.e. it will equal its own transpose, i.e. will have a reflection symmetry across the diagonal) and thus will be a *square* matrix. Numpy gives us a handy thing to call: ``` data = np.stack((x,y),axis=1) # pack the x & y data together in one 2D array print("data.shape =",data.shape) cov = np.cov(data.T) # .T b/c numpy wants varibles along rows rather than down columns? print("covariance matrix =\n",cov) ``` # Some 3D data to work with Now that we know what a covariance matrix is, let's generate some 3D data that we can use for what's coming next. Since there are 3 variables or 3 dimensions, the covariance matrix will now be 3x3. ``` z = -.5*x + 2*np.random.uniform(size=N) data = np.stack((x,y,z)).T print("data.shape =",data.shape) cov = np.cov(data.T) print("covariance matrix =\n",cov) # Plot our data import plotly.graph_objects as go fig = go.Figure(data=[go.Scatter3d(x=x, y=y, z=z,mode='markers', marker=dict(size=8,opacity=0.5), name="data" )]) fig.update_layout( xaxis_title="x", yaxis_title="y", yaxis = dict(scaleanchor = "x",scaleratio = 1) ) fig.show() ``` (Note that even though our $z$ data didn't explicitly depend on $y$, the fact that $y$ is covariant with $x$ means that $y$ and $z$ 'coincidentally' have a nonzero covariance. This sort of thing shows up in many datasets where two variables are correlated and may give rise to 'confounding' factors.) So now we have a covariance matrix. The next thing in PCA is find the 'principal components'. This means the directions along which the data varies the most. You can kind of estimate these by rotating the 3D graph above. See also [this great YouTube video of a teapot](https://www.youtube.com/watch?v=BfTMmoDFXyE) (1min 30s) that explains PCA in this manner. To do Principal Component Analysis, we need to find the aforementioned "components," and this requires finding *eigenvectors* for our dataset's covariance matrix. # What is an eigenvector, *really*? First a **definition**. (Stay with me! We'll flesh this out in what comes after this.) Given some matrix (or 'linear operator') ${\bf A}$ with dimensions $n\times n$ (i.e., $n$ rows and $n$ columns), there exist a set of $n$ vectors $\vec{v}_i$ (each with dimension $n$, and $i = 1...n$ counts which vector we're talking about) **such that** multiplying one of these vectors by ${\bf A}$ results in a vector (anti)parallel to $\vec{v}_i$, with a length that's multiplied by some constant $\lambda_i$. In equation form: $${\bf A}\vec{v}_i = \lambda_i \vec{v}_i,\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ (1)$$ where the constants $\lambda_i$ are called *eigenvalues* and the vectors $\vec{v}_i$ are called *eigenvectors*. <span style="text-align:right; font-style:italic; font-size:70%;">(Note that I'm departing a bit from common notation that uses $\vec{x}_i$ instead of $\vec{v}_i$; I don't want people to get confused when I want to use $x$'s for coordinate variables.)</span> A graphical version of this is shown in Figure 1: ![picture of eigenvectors](https://i.imgur.com/rUcGpVn.png) > Figure 1. "An eigenvector is a vector that a linear operator sends to a multiple of itself" -- [Daniel McLaury](https://www.quora.com/What-does-Eigen-mean/answer/Daniel-McLaury) ### Brief Q & A before we go on: 1. "So what's with the 'eigen' part?" That's a German prefix, which in this context means "inherent" or "own". 2. "Can a non-square matrix have eigenvectors?" Well,...no, and think of it this way: If $\bf{A}$ were an $n\times m$ matrix (where $m <> n$), then it would be mapping from $n$ dimensions into $m$ dimensions, but on the "other side" of the equation with the $\lambda_i \vec{v}_i$, *that* would still have $n$ dimensions, so... you'd be saying an $n$-dimensional object equals an $m$-dimensional object, which is a no-go. 3. "But my dataset has many more rows than columns, so what am I supposed to do about that?" Just wait! It'll be ok. We're not actually going to take the eigenvectors of the dataset 'directly', we're going to take the eigenvectors of the *covariance matrix* of the dataset. 4. "Are eigenvectors important?" You bet! They get used in many areas of science. I first encountered them in quantum mechanics.* They describe the "principal vectors" of many objects, or "normal modes" of oscillating systems. They get used in [computer vision](https://www.visiondummy.com/2014/03/eigenvalues-eigenvectors/), and... lots of places. You'll see them almost anywhere matrices & tensors are employed, such as our topic for today: Data science! *<small>Ok that's not quite true: I first encountered them in an extremely boring Linear Algebra class taught by an extremely boring NASA engineer who thought he wanted to try teaching. But it wasn't until later that I learned anything about their relevance for...anything. Consquently I didn't "learn them" very well so writing this is a helpful review for me.</small> # How to find the eigenvectors of a matrix You call a library routine that does it for you, of course! ;-) ``` from numpy import linalg as LA lambdas, vs = LA.eig(cov) lambdas, vs ``` Ok sort of kidding; we'll do it "from scratch". But, one caveat before we start: Some matrices can be "weird" or "problematic" and have things like "singular values." There are sophisticated numerical libraries for doing this, and joking aside, for real-world numerical applications you're better off calling a library routine that other very smart and very careful people have written for you. But for now, we'll do the straightforward way which works pretty well for many cases. We'll follow the basic two steps: 1. Find the eigenvalues 2. 'Plug in' each eigenvalue to get a system of linear equations for the values of the components of the corresponding eigenvector 3. Solve this linear system. ## 1. Find the eigenvalues Ok I'm hoping you at least can recall what a [determinant](https://en.wikipedia.org/wiki/Determinant) of a matrix is. Many people, even if they don't know what a determinant is good for (e.g. tons of proofs & properties all rest on the determinant), they still at least remember how to calculate one. The way to get the eigenvalues is to take the determinant of the difference between a $\bf{A}$ and $\lambda$ times the *identity matrix* $\bf{I}$ (which is just ones along the diagonal and zeros otherwise) and set that difference equal to zero... $$det( \bf{A} - \lambda I) = 0 $$ > <small>Just another observation: Since ${\bf I}$ is a square matrix, that means $\bf{A}$ has to be a square matrix too.</small> Then solving for $\lambda$ will give you a *polynomial equation* in $\lambda$, the solutions to (or roots of) which are the eigenvectors $\lambda_i$. Let's do an example: $$ {\bf A} = \begin{bmatrix} -2 & 2 & 1\\ -5 & 5 & 1\\ -4 & 2 & 3 \end{bmatrix} $$ To find the eigenvalues we set $$ det( \bf{A} - \lambda I) = \begin{vmatrix} -2-\lambda & 2 & 1\\ -5 & 5-\lambda & 1\\ -4 & 2 & 3-\lambda \end{vmatrix} = 0.$$ This gives us the equation... $$0 = \lambda^3 - 6\lambda^2 + \lambda - 6$$ which has the 3 solutions (in descending order) $$ \lambda = 3, 2, 1.$$ <small>*(Aside: to create an integer matrix with integer eigenvalues, I used [this handy web tool](https://ericthewry.github.io/integer_matrices/))*.</small> Just to check that against the numpy library: ``` A = np.array([[-2,2,1],[-5,5,1],[-4,2,3]]) def sorted_eig(A): # For now we sort 'by convention'. For PCA the sorting is key. lambdas, vs = LA.eig(A) # Next line just sorts values & vectors together in order of decreasing eigenvalues lambdas, vs = zip(*sorted(zip(list(lambdas), list(vs.T)),key=lambda x: x[0], reverse=True)) return lambdas, np.array(vs).T # un-doing the list-casting from the previous line lambdas, vs = sorted_eig(A) lambdas # hold off on printing out the eigenvectors until we do the next part! ``` Close enough! # 2. Use the eigenvalues to get the eigenvectors Although it was anncounced in mid 2019 that [you can get eigenvectors directly from eigenvalues](https://arxiv.org/abs/1908.03795), the usual way people have done this for a very long time is to go back to the matrix $\bf{A}$ and solve the *linear system* of equation (1) above, for each of the eigenvalues. For example, for $\lambda_1=-1$, we have $$ {\bf}A \vec{v}_1 = -\vec{v}_1 $$ i.e. $$ \begin{bmatrix} -2 & 2 & 1\\ -5 & 5 & 1\\ -4 & 2 & 3 \end{bmatrix} \begin{bmatrix} v_{1x}\\ v_{1y}\\ v_{1z}\\ \end{bmatrix} = -\begin{bmatrix} v_{1x}\\ v_{1y}\\ v_{1z}\\ \end{bmatrix} $$ This amounts to 3 equations for 3 unknowns,...which I'm going to assume you can handle... For the other eigenvalues things proceed similarly. The solutions we get for the 3 eigenvalues are: $$\lambda_1 = 3: \ \ \ \vec{v}_1 = (1,2,1)^T$$ $$\lambda_2 = 2: \ \ \ \vec{v}_2 = (1,1,2)^T$$ $$\lambda_3 = 1: \ \ \ \vec{v}_3 = (1,1,1)^T$$ Since our original equation (1) allows us to scale eigenvectors by any artibrary constant, often we'll express eigenvectors as *unit* vectors $\hat{v}_i$. This will amount to dividing by the length of each vector, i.e. in our example multiplying by $(1/\sqrt{6},1/\sqrt{6},1/\sqrt{3})$. In this setting $$\lambda_1 = 3: \ \ \ \hat{v}_1 = (1/\sqrt{6},2/\sqrt{6},1/\sqrt{6})^T$$ $$\lambda_2 = 2: \ \ \ \hat{v}_2 = (1/\sqrt{6},1/\sqrt{6},2/\sqrt{6})^T$$ $$\lambda_3 = 1: \ \ \ \hat{v}_3 = (1,1,1)^T/\sqrt{3}$$ Checking our answers (left) with numpy's answers (right): ``` print(" "*15,"Ours"," "*28,"Numpy") print(np.array([1,2,1])/np.sqrt(6), vs[:,0]) print(np.array([1,1,2])/np.sqrt(6), vs[:,1]) print(np.array([1,1,1])/np.sqrt(3), vs[:,2]) ``` The fact that the first one differs by a multiplicative factor of -1 is not an issue. Remember: eigenvectors can be multiplied by an arbitrary constant. (Kind of odd that numpy doesn't choose the positive version though!) One more check: let's multiply our eigenvectors times A to see what we get: ``` print("A*v_1 / 3 = ",np.matmul(A, np.array([1,2,1]).T)/3 ) # Dividing by eigenvalue print("A*v_2 / 2 = ",np.matmul(A, np.array([1,1,2]).T)/2 ) # to get vector back print("A*v_3 / 1 = ",np.matmul(A, np.array([1,1,1]).T) ) ``` Great! Let's move on. Back to our data! # Eigenvectors for our sample 3D dataset Recall we named our 3x3 covariance matrix 'cov'. So now we'll compute its eigenvectors, and then re-plot our 3D data and also plot the 3 eigenvectors with it... ``` # Now that we know we can get the same answers as the numpy library, let's use it lambdas, vs = sorted_eig(cov) # Compute e'vals and e'vectors of cov matrix print("lambdas, vs =\n",lambdas,"\n",vs) # Re-plot our data fig = go.Figure(data=[go.Scatter3d(x=x, y=y, z=z,mode='markers', marker=dict(size=8,opacity=0.5), name="data" ) ]) # Draw some extra 'lines' showing eigenvector directions n_ev_balls = 50 # the lines will be made of lots of balls in a line ev_size= 3 # size of balls t = np.linspace(0,1,num=n_ev_balls) # parameterizer for drawing along vec directions for i in range(3): # do this for each eigenvector # Uncomment the next line to scale (unit) vector by size of the eigenvalue # vs[:,i] *= lambdas[i] ex, ey, ez = t*vs[0,i], t*vs[1,i], t*vs[2,i] fig.add_trace(go.Scatter3d(x=ex, y=ey, z=ez,mode='markers', marker=dict(size=ev_size,opacity=0.8), name="v_"+str(i+1))) fig.update_layout( xaxis_title="x", yaxis_title="y", yaxis = dict(scaleanchor = "x",scaleratio = 1) ) fig.show() ``` Things to note from the above graph: 1. The first (red) eigenvector points along the direction of biggest variance 2. The second (greenish) eigenvector points along the direction of second-biggest variance 3. The third (purple) eigenvector points along the direction of smallest variance. (If you edit the above code to rescale the vector length by the eigenvector, you'll really see these three point become apparent!) ## "Principal Component" Analysis Now we have our components (=eigenvectors), and we have them "ranked" by their "significance." Next we will *eliminate* one or more of the less-significant directions of variance. In other words, we will *project* the data onto the various *principal components* by projecting *along* the less-significant components. Or even simpler: We will "squish" the data along the smallest-variance directions. For the above 3D dataset, we're going to squish it into a 2D pancake -- by projecting along the direction of the 3rd (purple) eigenvector onto the plane defined by the 1st (red) and 2nd (greenish) eigenvectors. Yea, but how to do this projection? ## Projecting the data It's actually not that big of a deal. All we have to do is multiply by the eigenvector (matrix)! **OH WAIT! Hey, you want to see a cool trick!?** Check this out: ``` lambdas, vs = sorted_eig(cov) proj_cov = vs.T @ cov @ vs # project the covariance matrix, using eigenvectors proj_cov ``` What was THAT? Let me clean that up a bit for you... ``` proj_cov[np.abs(proj_cov) < 1e-15] = 0 proj_cov ``` **Important point:** What you just saw is the whole reason eigenvectors get used for so many things, because they give you a 'coordinate system' where different 'directions' *decouple* from each other. See, the system has its own (German: eigen) inherent set of orientations which are different the 'arbitrary' coordinates that we 'humans' may have assigned initially. The numbers in that matrix are the covariances *in the directions* of the eigenvectors, instead of in the directions of the original x, y, and z. So really all we have to do is make a *coordinate transformation* using the matrix of eigenvectors, and then in order to project we'll literally just *drop* a whole index's-worth of data-dimension in this new coordinate system. :-) So, instead of $x$, $y$ and $z$, let's have three coordinates which (following physicist-notation) we'll call $q_1$, $q_2$ and $q_3$, and these will run along the directions given by the three eigenvectors. Let's write our data as a N-by-3 matrix, where N is the number of data points we have. ``` data = np.stack((x,y,z),axis=1) data.shape # we had a 100 data points, so expecting 100x3 matrix ``` There are two ways of doing this, and I'll show you that they're numerically equivalent: 1. Use *all* the eigenvectors to "rotate" the full dataset into the new coordinate system. Then perform a projection by truncating the last column of the rotated data. 2. Truncate the last eigenvector, which will make a 3x2 projection matrix which will project the data onto the 2D plane defined by those two eigenvectors. Let's show them both: ``` print("\n 1. All data, rotated into new coordinate system") W = vs[:,0:3] # keep the all the eigenvectors new_data_all = data @ W # project all the data print("Checking: new_data_all.shape =",new_data_all.shape) print("New covariance matrix = \n",np.cov(new_data_all.T) ) print("\n 2. Truncated data projected onto principal axes of coordinate system") W = vs[:,0:2] # keep only the first and 2nd eigenvectors print("W.shape = ",W.shape) new_data_proj = data @ W # project print("Checking: new_data_proj.shape =",new_data_proj.shape) print("New covariance matrix in projected space = \n",np.cov(new_data_proj.T) ) # Difference between them diff = new_data_all[:,0:2] - new_data_proj print("\n Absolute maximum difference between the two methods = ",np.max(np.abs(diff))) ``` ...Nada. The 2nd method will be faster computationally though, because it doesn't calculate stuff you're going to throw away. One more comparison between the two methods. Let's take a look at the "full" dataset (in blue) vs. the projected dataset (in red): ``` fig = go.Figure(data=[(go.Scatter3d(x=new_data_all[:,0], y=new_data_all[:,1], z=new_data_all[:,2], mode='markers', marker=dict(size=4,opacity=0.5), name="full data" ))]) fig.add_trace(go.Scatter3d(x=new_data_proj[:,0], y=new_data_proj[:,1], z=new_data_proj[:,0]*0, mode='markers', marker=dict(size=4,opacity=0.5), name="projected" ) ) fig.update_layout(scene_aspectmode='data') fig.show() ``` <small>(Darn it, [if only Plot.ly would support orthographic projections](https://community.plot.ly/t/orthographic-projection-for-3d-plots/3897) [[2](https://community.plot.ly/t/orthographic-projection-instead-of-perspective-for-3d-plots/10035)] it'd be a lot easier to visually compare the two datasets!)</small> # Beyond 3D So typically we use PCA to throw out many more dimensions than just one. Often this is used for data visualization but it's also done for feature reduction, i.e. to send less data into your machine learning algorithm. (PCA can even be used just as a "multidimensional linear regression" algorithm, but you wouldn't want to!) ## How do you know how many dimensions to throw out? In other words, how many 'components' should you choose to keep when doing PCA? There are a few ways to make this *judgement call* -- it will involve a trade-off between accuracy and computational speed. You can make a graph of the amount of variance you get as a function of how many components you keep, and often there will be a an 'elbow' at some point on the graph indicating a good cut-off point to choose. Stay tuned as we do the next example; we'll make such a graph. For more on this topic, see [this post by Arthur Gonsales](https://towardsdatascience.com/an-approach-to-choosing-the-number-of-components-in-a-principal-component-analysis-pca-3b9f3d6e73fe). ## Example: Handwritten Digits The [scikit-learn library](https://scikit-learn.org/stable/auto_examples/classification/plot_digits_classification.html) uses this as an example and I like it. It goes as follows: 1. Take a dataset of tiny 8x8 pixel images of handwritten digits. 2. Run PCA to break it down from 8x8=64 dimensions to just two or 3 dimensions. 3. Show on a plot how the different digits cluster in different regions of the space. 4. (This part we'll save for the Appendix: Draw boundaries between the regions and use this as a classifier.) To be clear: In what follows, *each pixel* of the image counts as a "feature," i.e. as a dimension. Thus an entire image can be represented as a single point in a multidimensional space, in which distance from the origin along each dimension is given by the pixel intensity. In this example, the input space is *not* a 2D space that is 8 units wide and 8 units long, rather it consists of 8x8= 64 dimensions. ``` from sklearn.datasets import load_digits from sklearn.decomposition import PCA digits = load_digits() X = digits.data / 255.0 Y = digits.target print(X.shape, Y.shape,'\n') # Let's look a a few examples for i in range(8): # show 8 examples print("This is supposed to be a '",Y[i],"':",sep="") plt.imshow(X[i].reshape([8,8])) plt.show() ``` Now let's do the PCA thang... First we'll try going down to 2 dimensions. This isn't going to work super great but we'll try: ``` digits_cov = np.cov(X.T) print("digits_cov.shape = ",digits_cov.shape) lambdas, vs = sorted_eig(np.array(digits_cov)) W = vs[:,0:2] # just keep two dimensions proj_digits = X @ W print("proj_digits.shape = ", proj_digits.shape) # Make the plot fig = go.Figure(data=[go.Scatter(x=proj_digits[:,0], y=proj_digits[:,1],# z=Y, #z=proj_digits[:,2], mode='markers', marker=dict(size=6, opacity=0.7, color=Y), text=['digit='+str(j) for j in Y] )]) fig.update_layout( xaxis_title="q_1", yaxis_title="q_2", yaxis = dict(scaleanchor = "x",scaleratio = 1) ) fig.update_layout(scene_camera=dict(up=dict(x=0, y=0, z=1), center=dict(x=0, y=0, z=0), eye=dict(x=0, y=0, z=1.5))) fig.show() ``` This is 'sort of ok': There are some regions that are mostly one kind of digit. But you may say there's there's too much intermingling between classes for a lot of this plot. So let's try it again with 3 dimensions for PCA: ``` W = vs[:,0:3] # just three dimensions proj_digits = X @ W print("proj_digits.shape = ", proj_digits.shape) # Make the plot, separate them by "z" which is the digit of interest. fig = go.Figure(data=[go.Scatter3d(x=proj_digits[:,0], y=proj_digits[:,1], z=proj_digits[:,2], mode='markers', marker=dict(size=4, opacity=0.8, color=Y, showscale=True), text=['digit='+str(j) for j in Y] )]) fig.update_layout(title="8x8 Handwritten Digits", xaxis_title="q_1", yaxis_title="q_2", yaxis = dict(scaleanchor = "x",scaleratio = 1) ) fig.show() ``` *Now* we can start to see some definition! The 6's are pretty much in one area, the 2's are in another area, and the 0's are in still another, and so on. There is some intermingling to be sure (particularly between the 5's and 8's), but you can see that this 'kind of' gets the job done, and instead of dealing with 64 dimensions, we're down to 3! ## Graphing Variance vs. Components Earlier we asked the question of how many components one should keep. To answer this quantitatively, we note that the eigenvalues of the covariance matrix are themselves measures of the variance in the datset. So these eigenvalues encode the 'significance' that each feature-dimension has in the overall dataset. We can plot these eigenvalues in order and then look for a 'kink' or 'elbow' in the graph as a place to truncate our representation... ``` plt.plot( np.abs(lambdas)/np.sum(lambdas) ) plt.xlabel('Number of components') plt.ylabel('Significance') plt.show() ``` ...So, if we were wanting to represent this data in more than 3 dimensions but less than the full 64, we might choose around 10 principal compnents, as this looks like roughly where the 'elbow' in the graph lies. # Interpretability What is the meaning of the new coordinate axes or 'features' $q_1$, $q_2$, etc? Sometimes there exists a compelling physical intepretation of these features (e.g., as in the case of eigenmodes of coupled oscillators), but often...there may not be any. And yet we haven't even done any 'real machine learning' at this point! ;-) This is an important topic. Modern data regulations such as the European Union's [GDPR](https://en.wikipedia.org/wiki/General_Data_Protection_Regulation) require that models used in algorithmic decision-making be 'explainable'. If the data being fed into such algorithmics is already abstracted via methods such as PCA, this could be an issue. Thankfully, the linearity of the components mean that one can describe each principal component as a linear combination of inputs. ## Further reading There are [many books](https://www.google.com/search?client=ubuntu&channel=fs&q=book+pca+principal+component+analysis&ie=utf-8&oe=utf-8) devoted entirely to the intricacies of PCA and its applications. Hopefully this post has helped you get a better feel for how to construct a PCA transformation and what it might be good for. To expand on this see the following... ### Examples & links * ["Eigenstyle: Principal Component Analysis and Fashion"](https://graceavery.com/principalcomponentanalysisandfashion/) by Grace Avery. Uses PCA on Fashion-MNIST. It's good! * [Neat paper by my friend Dr. Ryan Bebej](https://link.springer.com/article/10.1007/s10914-008-9099-1) from when he was a student and used PCA to classify locomotion types of prehistoric acquatic mammals based on skeletal measurements alone. * [Andrew Ng's Machine Learning Course, Lecture on PCA](https://www.coursera.org/lecture/machine-learning/principal-component-analysis-algorithm-ZYIPa). How I first learned about this stuff. * [PCA using Python](https://towardsdatascience.com/pca-using-python-scikit-learn-e653f8989e60) by Michael Galarnyk. Does similar things to what I've done here, although maybe better! * [Plot.ly PCA notebook examples](https://plot.ly/python/v3/ipython-notebooks/principal-component-analysis/) # Appendix A: Overkill: Bigger Handwritten Digits Sure, 8x8 digit images are boring. What about 28x28 images, as in the [MNIST dataset](http://yann.lecun.com/exdb/mnist/)? Let's roll... ``` #from sklearn.datasets import fetch_mldata from sklearn.datasets import fetch_openml from random import sample #mnist = fetch_mldata('MNIST original') mnist = fetch_openml('mnist_784', version=1, cache=True) X2 = mnist.data / 255 Y2 = np.array(mnist.target,dtype=np.int) #Let's grab some indices for random suffling indices = list(range(X2.shape[0])) # Let's look a a few examples for i in range(8): # 8 is good i = sample(indices,1) print("This is supposed to be a ",Y2[i][0],":",sep="") plt.imshow(X2[i].reshape([28,28])) plt.show() # Like we did before... Almost the whole PCA method is the next 3 lines! mnist_cov = np.cov(X2.T) lambdas, vs = sorted_eig(np.array(mnist_cov)) W = vs[:,0:3] # Grab the 3 most significant dimensions # Plotting all 70,000 data points is going to be too dense too look at. # Instead let's grab a random sample of 5,000 points n_plot = 5000 indices = sample(list(range(X2.shape[0])), n_plot) proj_mnist = np.array(X2[indices] @ W, dtype=np.float32) # Last step of PCA: project fig = go.Figure(data=[go.Scatter3d(x=proj_mnist[:,0], y=proj_mnist[:,1], z=proj_mnist[:,2], mode='markers', marker=dict(size=4, opacity=0.7, color=Y2[indices], showscale=True), text=['digit='+str(j) for j in Y2[indices]] )]) fig.show() ``` ...bit of a mess. Not as cleanly separated as the 8x8 image examples. You can see that the 0's are well separated from the 1's and the 3's, but everything else is pretty mixed together. (I suspect the 1's are clustered strongly because they involve the most dark pixels.) If you wanted to push this further then either keeping more dimensions (thereby making it un-visualizable) or just using a different method entirely (e.g. t-SNE or even better: [UMAP](https://pair-code.github.io/understanding-umap/)) would be the way to go. Still, it's neat to see that you can get somewhat intelligible results in 3D even on this 'much harder' problem. # Appendix B: Because We Can: Turning it into a Classifier ...But let's not do a neural network because all I ever do are neural networks, and because I don't want to have take the time & space to explain how they work or load in external libraries. Let's do k-nearest-neighbors instead, because it's intuitively easy to grasp and it's not hard to code up: > For any new point we want to evaluate, we take a 'vote' of whatever some number (called $k$) of its nearest neighbor points are already assigned as, and we set the class of the new point according to that vote. <small>Making a efficient classifier is all about finding the *boundaries* between regions (and usually subject to some user-adjustable parameter like $k$ or some numerical threshold). Finding these boundaries can be about finding the 'edge cases' that cause the system to 'flip' (discontinuously) from one result to another. However, we are *not* going to make an efficient classifier today. ;-) </small> Let's go back to the 8x8 digits example, and split it into a training set and a testing set (so we can check ourselves): ``` # random shuffled ordering of the whole thing indices = sample(list(range(X.shape[0])), X.shape[0]) X_shuf, Y_shuf = X[indices,:], Y[indices] # 80-20 train-test split max_train_ind = int(0.8*X.shape[0]) X_train, Y_train = X_shuf[0:max_train_ind,:], Y_shuf[0:max_train_ind] X_test, Y_test = X_shuf[max_train_ind:-1,:], Y_shuf[max_train_ind:-1] # Do PCA on training set train_cov = np.cov(X_train.T) ell, v = sorted_eig(np.array(train_cov)) pca_dims = 3 # number of top 'dimensions' to take W_train = v[:,0:pca_dims] proj_train = X_train @ W_train # also project the testing set while we're at it proj_test = X_test @ W_train # yes, same W_train ``` Now let's make a little k-nearest neighbors routine... ``` from collections import Counter def knn_predict(xnew, proj_train, Y_train, k=3): """ xnew is a new data point that has the same shape as one row of proj_train. Given xnew, calculate the (squared) distance to all the points in X_train to find out which ones are nearest. """ distances = ((proj_train - xnew)**2).sum(axis=1) # stick on an extra column of indexing 'hash' for later use after we sort dists_i = np.stack( (distances, np.array(range(Y_train.shape[0]) )),axis=1 ) dists_i = dists_i[dists_i[:,0].argsort()] # sort in ascending order of distance knn_inds = (dists_i[0:k,-1]).astype(np.int) # Grab the indexes for k nearest neighbors # take 'votes': knn_targets = list(Y_train[knn_inds]) # which classes the nn's belong to votes = Counter(knn_targets) # count up how many of each class are represented return votes.most_common(1)[0][0] # pick the winner, or the first member of a tie # Let's test it on the first element of the testing set x, y_true = proj_test[0], Y_test[0] guess = knn_predict(x, proj_train, Y_train) print("guess = ",guess,", true = ",y_true) ``` Now let's try it for the 'unseen' data in the testing set, and see how we do... ``` mistakes, n_test = 0, Y_test.shape[0] for i in range(n_test): x = proj_test[i] y_pred = knn_predict(x, proj_train, Y_train, k=3) y_true = Y_test[i] if y_true != y_pred: mistakes += 1 if i < 20: # show some examples print("x, y_pred, y_true =",x, y_pred, y_true, "YAY!" if y_pred==y_true else " BOO. :-(") print("...skipping a lot...") print("Total Accuracy =", (n_test-mistakes)/n_test*100,"%") ``` ...eh! Not bad, not amazing. You can improve the accuracy if you go back up and increase the number of PCA dimensions beyond 3, and/or increase the value of $k$. Go ahead and try it! <small>(For 10 dimensions and $k=7$, I got 97.7% accuracy. The highest I ever got it was 99%, but that was really working overtime, computationally speaking; the point of PCA is to let you dramatically reduce your workload while retaining reasonably high accuracy.)</small> Just to reiterate: This is NOT supposed to be a state of the art classifier! It's just a toy that does pretty well and helps illustrate PCA without being hard to understand or code. # The End Thanks for sticking around! Hope this was interesting. PCA is pretty simple, and yet really useful! ...and writing this really helped *me* to better understand it. ;-)
github_jupyter
### Creating superposition states associated with discretized probability distributions #### Prerequisites Here are a few things you should be up to speed on before we start: - [Python fundamentals](https://qiskit.org/textbook/ch-prerequisites/python-and-jupyter-notebooks.html) - [Programming quantum computers using Qiskit](https://qiskit.org/textbook/ch-prerequisites/qiskit.html) - [Single qubit gates](https://qiskit.org/textbook/ch-states/single-qubit-gates.html) Additiona resources can be found [here](https://github.com/QForestCommunity/launchpad/blob/master/README.md). #### Dependencies We also need a couple of Python packages to build our distribution encoder: - [Qiskit](https://qiskit.org/) - [Numpy](https://numpy.org/) - [SciPy](https://www.scipy.org/) - [Matplotlib](https://matplotlib.org/) #### Contributors [Sashwat Anagolum](https://github.com/SashwatAnagolum) #### Qiskit Package Versions ``` import qiskit qiskit.__qiskit_version__ ``` #### Introduction Given a probability distribution $p$, we want to create a quantum state $|\psi\rangle$ such that $$|\psi\rangle = \sum_{i} \sqrt{p_i} |i\rangle$$ where $|i\rangle$ represents one of an orthonormal set of states. While we don't known when (for what kinds of distributions) we can do this, we do know that if you can efficiently integrate over a distribution classically, then we can efficiently construct a quantum state associated with a discretized version of that distribution. It may seem kind of trivial - we can integrate over the distribution classicaly, so why not just create the mixed state shown here? $$\sum_i p_i |i\rangle \langle i |$$ If all we needed to do was sample from the distribution, we could use this state - but then if we were efficiently integrating the distribution classicaly, say using Monte Carlo methods, we might as well sample from the classical distribution as well. The reason we avoid generating the distribution as a mixed quantum state is that we often need to perfom further, uniquely quantum, processing on it after creation - in this case, we cannot use the mixed state apporach. #### Encoding the distribution If we wanted to create a $N$ region discretization, we would need $n = log N$ qubits to represent the distribution. Let's look at a super simple case to start off: $N = 2$, so $n = 1$. We have probabilities $p_{0}^{(1)}$ and $p_1^{(1)}$, of a random variable following the distribution lying in region $0$ and region $1$, respectively, with $p^{(i)}_{j}$ representing the probability of measuring a random variable in region $j$ if it follows the discretized distribution over $i$ qubits. Since we only use one qubit, all we need to do is integrate over region $0$ to find the probability of a variable lying within it. Let's take a quick look at the Bloch sphere: ![Bloch Sphere](./img/load_probability_distributions/bloch.png) If a qubit is rotated about the y-axis by angle $\theta$, then the probability of measuring it as zero is given by $\cos (\frac{\theta}{2})^2$ - so we can figure out how much to rotate a qubit by if we're using it to encode a distribution: $$ \theta = 2 * \cos^{-1} \left ( \sqrt{p_{0}^{(1)}}\right )$$ $$p_{0}^{(1)} = \int_{x^{(1)}_{0}}^{x_{1}^{(1)}}p(x) dx$$ Where $x^{(1)}_{0}$ and $x_{1}^{(1)}$ are the first and second region boundaries when 1 qubit is used. This leaves us with $$|\psi \rangle = \sqrt{p_{0}^{(1)}} |0\rangle + \sqrt{p_{1}^{(1)}} |1\rangle$$ Awesome! Now that we know how to do it for distributions with two regions, let's see if we can expand it to include more regions - i.e., can we convert a quantum state encoding a $N$ region discretization into one encoding a discretization with $2N$ regions? To get started, let's avoid all the complicated integration stuff we'll need to do later by defining a function $f(i, n)$ such that $$f(i, n) = \frac{\int_{x_{k}^{(n + 1)}}^{x_{k + 1}^{(n + 1)}} p(x) dx}{\int^{x_{i + 1}^{(n)}}_{x_{i}^{(n)}} p(x) dx}$$ Where $k = 2 * \left ( \frac{i}{2} - \frac{i \% 2}{2} \right )$. The equation above probably looks a little hopeless, but all it does it computes the conditional probability of a value lying in the left subregion of region $i$ (when we have $N$ regions), given that it lies in region $i$. Why do we need this? We're assuming that dividing the distribution into $N$ regions is just an intermediary step in the process of dividing it into the desired $2^{m}$ regions - so $x_{k}^{(n + 1)}$ refers to the same boundary that $x_{i}^{(n)}$ does. Now that we've defined $f(i, n)$, all we need to do to figure out how much to rotate the $(n + 1)^{th}$ qubit is compute $$\theta_{i}^{(n + 1)} = 2 * \cos^{-1} \left ( \sqrt{f(i, n)}\right )$$ Now all we need to do is rotate the $(n + 1)^{th}$ qubit by $\theta_{i}^{(n + 1)}$ conditioned on the state $|i\rangle$ represented using $n$ qubits: $$\sqrt{p_{i}^{(n)}}|i\rangle \rightarrow \sqrt{p^{(n + 1)}_{k}}|k\rangle + \sqrt{p^{(n + 1)}_{k + 1}}|k+1\rangle$$ Since we showed that constructing a state for $n = 1$ was possible, and given a $2^n$ region discretization, we could convert into a distribution with $2^{(n + 1)}$ regions, we just inductively proved that we can construct a superposition state corresponding to a $2^n, n \in \mathbb{N}$ region discretized distribution - pretty cool! Now that we've gotten the concepts down, let's move on to building our own quantum distribution encoder. #### Required modules ``` from qiskit import QuantumRegister, ClassicalRegister from qiskit import Aer, execute, QuantumCircuit from qiskit.circuit.library.standard_gates import RYGate from numpy import pi, e, sqrt, arccos, log2 from scipy.integrate import quad %matplotlib inline import matplotlib.pyplot as plt ``` Let's define a function representing our distribution, so that we can change super quickly whenever we want to. We'll start off with a super simple function, like $N(0, 2)$: ``` def distribution(x): """ Returns the value of a chosen probability distribution at the given value of x. Mess around with this function to see how the encoder works! The current distribution being used is N(0, 2). """ # Use these with normal distributions mu = 0 sigma = 2 return (((e ** (-0.5 * ((x - mu) / sigma) ** 2)) / (sigma * sqrt(2 * pi))) / 0.99993665) ``` The 0.99993665 is a normalisation factor used to make sure the sum of probabilities over the regions we've chosen adds up to 1. Next, let's create everything else we need to compute $f(i, n)$: ``` def integrate(dist, lower, upper): """ Perform integration using numpy's quad method. We can use parametrized distributions as well by using this syntax instead: quad(integrand, lower, upper, args=(tupleOfArgsForIntegrand)) """ return quad(dist, lower, upper)[0] def computeRegionProbability(dist, regBounds, numRegions, j): """ Given a distribution dist, a list of adjacent regions regBounds, the current level of discretization numRegions, a region number j, computes the probability that the value random variable following dist lies in region j given that it lies in the larger region made up of regions [(j // 2) * 2, ((j + 2) // 2) * 2] """ totalRegions = len(regBounds) - 1 k = 2 * j prob = integrate(dist, regBounds[(totalRegions // numRegions) * k], regBounds[(totalRegions // numRegions) * (k + 1)]) / integrate( dist, regBounds[(totalRegions // numRegions) * ((k // 2) * 2)], regBounds[(totalRegions // numRegions) * (((k + 2) // 2) * 2)]) return prob ``` $computeRegionProbability$ gives us the value of $f(i, n)$. We're finally ready to start writing the quantum part of our program - let's start by creating the registers and circuit we need: ``` def encodeDist(dist, regBounds): numQubits = int(log2(len(regBounds) - 1)) a = QuantumRegister(2 * numQubits - 2) c = ClassicalRegister(numQubits) qc = QuantumCircuit(a, c) ``` Now we can create the looping construct we need to be able to iteratively divide the distribution into $2^m$ regions, starting from $n = 1$ ($2$ regions), and dividing until $n = log N$ ($N$ regions). We need to loop over the different regions in the current , and compute the value of $f(i, n)$ for each one: ``` for i in range(numQubits): numRegions = int(2 ** (i + 1)) for j in range(numRegions // 2): prob = computeRegionProbability(dist, regBounds, numRegions, j) ``` Now we need to apply the controlled rotations - but we also need to write in a special case for $n = 1$, because there are no qubits to condition the rotation on: ``` if not i: qc.ry(2 * arccos(sqrt(prob)), a[2 * numQubits - 3]) ``` Since we'll be using gates with an arbitrary number of control qubits, we use the ControlledGate: ``` else: cGate = RYGate(2 * arccos(sqrt(prob))).control(i) ``` We know that we need to use the qubits indexed by $[0, 1, ..., i - 1]$ as control qubits, and the $n^{th}$ one as the target - but before we can apply the gate we need to perform a few bit flips to make sure that the $n^{th}$ qubit is rotated only when the control qubits are in the state $|i\rangle$. We can figure out which qubits to flip using this function: ``` def getFlipList(i, j, numQubits): """ Given the current level of desired level of discretization, the current level of discretization i and a region number j, returns the binary bit string associated with j in the form of a list of bits to be flipped. """ binString = str(bin(j))[2:] binString = ("0" * (numQubits - len(binString))) + binString bitFlips = [] for k in range(numQubits - i, numQubits): if binString[k] == '0': bitFlips.append(3 * numQubits - 3 - k - i) return bitFlips ``` Here the variable j represents the region number, which we convert to binary, and then flip qubits so that the resulting binary string is all ones. After finding out which qubits we need to flip, we can create a controlled gate and append it to the quantum circuit back in $encodeDist$: ``` for k in listOfFlips: qc.x(a[k]) qubitsUsed = [a[k] for k in range(2 * numQubits - 2 - i, 2 * numQubits - 2)] qubitsUsed.append(a[2 * numQubits - 3 - i]) qc.append(cGate, qubitsUsed) for k in listOfFlips: qc.x(a[k]) ``` All that's left is to return the quantum circuit: ``` return qc, a, c ``` Here's the entire function, so that we can run it in the notebook: ``` def encodeDist(dist, regBounds): """ Discretize the distribution dist into multiple regions with boundaries given by regBounds, and store the associated quantum superposition state in a new quantum register reg. Please make sure the number of regions is a power of 2, i.e. len(regBounds) = (2 ** n) + 1. Additionally, the number of regions is limited to a maximum of 2^(n // 2 + 1), where n is the number of qubits available in the backend being used - this is due to the requirement of (n - 2) ancilla qubits in order to perform (n - 1) control operations with minimal possible depth. Returns a new quantum circuit containing the instructions and registers needed to create the superposition state, along with the size of the quantum register. """ numQubits = int(log2(len(regBounds) - 1)) a = QuantumRegister(2 * numQubits - 2) c = ClassicalRegister(numQubits) qc = QuantumCircuit(a, c) for i in range(numQubits): numRegions = int(2 ** (i + 1)) for j in range(numRegions // 2): prob = computeRegionProbability(dist, regBounds, numRegions, j) if not i: qc.ry(2 * arccos(sqrt(prob)), a[2 * numQubits - 3]) else: cGate = RYGate(2 * arccos(sqrt(prob))).control(i) listOfFlips = getFlipList(i, j, numQubits) for k in listOfFlips: qc.x(a[k]) qubitsUsed = [a[k] for k in range(2 * numQubits - 2 - i, 2 * numQubits - 2)] qubitsUsed.append(a[2 * numQubits - 3 - i]) qc.append(cGate, qubitsUsed) for k in listOfFlips: qc.x(a[k]) return qc, a, c ``` Finally, we can call our function, and compare the results with those from a classical computer - we also need a helper function that pads bit strings for us, so that we can plot the classical results on the same axis as the quantum ones: ``` def pad(x, numQubits): """ Utility function that returns a left padded version of the bit string passed. """ string = str(x)[2:] string = ('0' * (numQubits - len(string))) + string return string regBounds = [i for i in range(-16, 17)] qc, a, c = encodeDist(distribution, regBounds) numQubits = (qc.num_qubits + 2) // 2 for i in range(numQubits - 2, 2 * numQubits - 2): qc.measure(a[i], c[i - (numQubits - 2)]) backend = Aer.get_backend('qasm_simulator') shots = 100000 job = execute(qc, backend=backend, shots=shots) results = job.result().get_counts() resultsX = [] resultsY = [] for i in [pad(bin(x), numQubits) for x in range(2 ** (numQubits))]: resultsX.append(i) if i in results.keys(): resultsY.append(results[i]) else: resultsY.append(0) truthDisc = [integrate(distribution, regBounds[i], regBounds[i + 1]) * shots for i in range( len(regBounds) - 1)] plt.figure(figsize=[16, 9]) plt.plot(resultsX, resultsY) plt.plot(resultsX, truthDisc, '--') plt.legend(['quantum estimate', 'classical estimate']) plt.show() ``` Let's take a look at the quantum circuit: ``` circuit_drawer(qc, output='latex') ``` #### Things to do next Looks like we're done - awesome! Taking all the functions from this notebook and pasting them into a python file will give you a working copy of this program, provided you have all the dependencies installed - if you want a regular python file instead, you can get a copy [here](https://github.com/SashwatAnagolum/DoNew/blob/master/loadProbDist/loadProbDist.py). A possible next step after getting the hang of encoding distributions is to figure out ways to process the quantum state further, leading to purely quantum transformed versions of the distribution. Let me know if you figure out any other ways we can work with the quantum state we get using this circuit, or if you have any other questions - you can reach me at [sashwat.anagolum@gmail.com](mailto:sashwat.anagolum@gmail.com)
github_jupyter
``` import scipy.io as sio from scipy.misc import imread from preprocess.normalize import preprocess_signature import tf_signet from tf_cnn_model import TF_CNNModel import tensorflow as tf import numpy as np import pandas as pd import sys import os import scipy.io from find_largest_image import find_largest import tqdm from sklearn.model_selection import train_test_split from sklearn.svm import SVC from xgboost import XGBClassifier import random from numpy.random import choice from sklearn.neural_network import MLPClassifier from sklearn.metrics import accuracy_score, roc_curve import sklearn.pipeline as pipeline import sklearn.preprocessing as preprocessing from sklearn.model_selection import train_test_split data_folder = 'C:\\Users\\Mert\\Documents\\GitHub\\sigver_bmg\\data\\downloaded_pp_features\\gpds_signet_all' user_kernel='rbf' data_f = pd.read_csv(os.path.join(data_folder,'data_features.csv')) visual_f = pd.read_csv(os.path.join(data_folder,'visual_features.csv')) ``` # MODEL SELECTION & TRAINING ``` dev_exp_ratio = 0.66 sorted_id_list = np.sort(data_f['user_id'].unique()) dev_exp_splitter=int(len(sorted_id_list)*dev_exp_ratio) dev_val_user_ids = sorted_id_list[:dev_exp_splitter] exp_user_ids = sorted_id_list[dev_exp_splitter:] fakes_preds = [] gens_preds = [] for fold in np.arange(0,5): assert len(dev_val_user_ids)==581 np.random.shuffle(dev_val_user_ids) dev_user_ids = dev_val_user_ids[0:531] validation_user_ids = dev_val_user_ids[531:len(dev_val_user_ids)] train_idx, test_idx = train_test_split(np.arange(1,25), train_size=0.5, test_size=0.5) dev_df = data_f.loc[data_f['user_id'].isin(dev_user_ids)] dev_vf = visual_f.loc[dev_df.index] val_df = data_f.loc[data_f['user_id'].isin(validation_user_ids)] val_vf = visual_f.loc[val_df.index] dev_df_gen = dev_df.loc[dev_df['fakeness']==0] dev_df_fake = dev_df.loc[dev_df['fakeness']==1] dev_df_gen_12 = dev_df_gen.loc[dev_df_gen['sig_id'].isin(train_idx)] dev_df_valid_12 = dev_df_gen.loc[dev_df_gen['sig_id'].isin(test_idx)] train_idx, test_idx = train_test_split(np.arange(1,25), train_size=0.5) val_df_gen = val_df.loc[val_df['fakeness']==0] val_df_fake = val_df.loc[val_df['fakeness']==1] val_df_gen_12 = val_df_gen.loc[val_df_gen['sig_id'].isin(train_idx)] val_df_valid_gen_12 = val_df_gen.loc[val_df_gen['sig_id'].isin(test_idx)] for user_id in tqdm.tqdm(validation_user_ids, ascii=True): clf = SVC(C=1,gamma='scale',class_weight='balanced', probability=False, kernel=user_kernel) y_train = (pd.concat([val_df_gen_12.loc[val_df_gen_12['user_id']==user_id],dev_df_gen.loc[dev_df_gen['user_id']!=user_id]]))['user_id']==user_id X_train = visual_f.loc[y_train.index] clf.fit(X_train, y_train) y_valid_fakes = val_df_fake.loc[(val_df_fake['user_id']==user_id)] X_valid_f = visual_f.loc[y_valid_fakes.index] fakes_preds.append(clf.decision_function(X_valid_f)) y_valid_gens = val_df_valid_gen_12.loc[val_df_valid_gen_12['user_id']==user_id] X_valid_g = visual_f.loc[y_valid_gens.index] gens_preds.append(clf.decision_function(X_valid_g)) ``` # GLOBAL THRESHOLD SELECTION ``` flat_fakes_preds = np.expand_dims(np.array([item for sublist in fakes_preds for item in sublist]),axis=1) flat_gens_preds = np.expand_dims(np.array([item for sublist in gens_preds for item in sublist]),axis=1) all_preds = np.vstack((flat_fakes_preds,flat_gens_preds)) all_labels = np.vstack((np.zeros((flat_fakes_preds.shape[0],1)),np.ones((flat_gens_preds.shape[0],1)))) fpr,tpr,threshold = roc_curve(all_labels,all_preds) fnr = 1 - tpr EER = fpr[np.nanargmin(np.absolute((fnr - fpr)))] eer_th = threshold[np.nanargmin(np.absolute((fnr - fpr)))] print('EER_glob : ', EER*100,'\nEER_Threshold_glob : ', eer_th) glob_th = eer_th assert len(fakes_preds)==len(gens_preds) EER_accum=0 for idx,val in enumerate(fakes_preds): user_fakes_preds = np.expand_dims(np.array(fakes_preds[idx]),axis=1) user_gens_preds = np.expand_dims(np.array(gens_preds[idx]),axis=1) all_user_preds = np.vstack((user_fakes_preds,user_gens_preds)) all_user_labels = np.vstack((np.zeros((user_fakes_preds.shape[0],1)),np.ones((user_gens_preds.shape[0],1)))) fpr,tpr,threshold = roc_curve(all_user_labels,all_user_preds) fnr = 1 - tpr EER = fpr[np.nanargmin(np.absolute((fnr - fpr)))] EER_accum += EER print('EER_user : ', (EER_accum*100)/len(fakes_preds)) print(glob_th) ``` # TRAIN AND TEST ON THE EXPLOITATION SET ``` test_gens_preds = [] test_fakes_preds = [] train_idx, test_idx = train_test_split(np.arange(1,25), train_size=0.5) exp_df = data_f.loc[data_f['user_id'].isin(exp_user_ids)] exp_vf = visual_f.loc[exp_df.index] exp_df_gen = exp_df.loc[exp_df['fakeness']==0] exp_df_fake = exp_df.loc[exp_df['fakeness']==1] exp_df_fake_10 = exp_df_fake.loc[exp_df_fake['sig_id'].isin(choice(np.arange(1,31),10,replace=False))] exp_df_gen_12 = exp_df_gen.loc[exp_df_gen['sig_id'].isin(train_idx)] exp_df_valid_gen_10 = exp_df_gen.loc[exp_df_gen['sig_id'].isin(test_idx[0:10])] dev_val_df = data_f.loc[data_f['user_id'].isin(dev_val_user_ids)] dev_val_vf = visual_f.loc[dev_val_df.index] dev_val_df_gen = dev_val_df.loc[dev_val_df['fakeness']==0] dev_val_df_valid_gen_14 = dev_val_df_gen.loc[dev_val_df_gen['sig_id'].isin(choice(np.arange(1,25),14,replace=False))] for user_id in tqdm.tqdm(exp_user_ids, ascii=True): clf = SVC(C=1,gamma='scale',class_weight='balanced', probability=False, kernel=user_kernel) y_train = (pd.concat([exp_df_gen_12.loc[exp_df_gen_12['user_id']==user_id],dev_val_df_valid_gen_14.loc[dev_val_df_valid_gen_14['user_id']!=user_id]]))['user_id']==user_id X_train = visual_f.loc[y_train.index] clf.fit(X_train, y_train) y_valid_fakes = exp_df_fake_10.loc[(exp_df_fake_10['user_id']==user_id)] X_valid_f = visual_f.loc[y_valid_fakes.index] test_fakes_preds.append(clf.decision_function(X_valid_f)) y_valid_gens = exp_df_valid_gen_10.loc[exp_df_valid_gen_10['user_id']==user_id] X_valid_g = visual_f.loc[y_valid_gens.index] test_gens_preds.append(clf.decision_function(X_valid_g)) flat_test_fakes_preds = np.expand_dims(np.array([item for sublist in test_fakes_preds for item in sublist]),axis=1) flat_test_gens_preds = np.expand_dims(np.array([item for sublist in test_gens_preds for item in sublist]),axis=1) print("____At the EER threshold decided on the Validation set____") print("FRR : ",(1-len(flat_test_gens_preds[flat_test_gens_preds>=glob_th])/len(flat_test_gens_preds))*100) print("FARskilled : ",(1-len(flat_test_fakes_preds[flat_test_fakes_preds<glob_th])/len(flat_test_fakes_preds))*100) all_test_preds = np.vstack((flat_test_fakes_preds,flat_test_gens_preds)) all_test_labels = np.vstack((np.zeros((flat_test_fakes_preds.shape[0],1)),np.ones((flat_test_gens_preds.shape[0],1)))) fpr,tpr,threshold = roc_curve(all_test_labels,all_test_preds) fnr = 1 - tpr EER = fpr[np.nanargmin(np.absolute((fnr - fpr)))] eer_th = threshold[np.nanargmin(np.absolute((fnr - fpr)))] print('EER_glob for test set: ', EER*100,'\nEER_Threshold_glob for test set: ', eer_th) assert len(test_fakes_preds)==len(test_gens_preds) EER_accum=0 for idx,val in enumerate(test_fakes_preds): user_test_fakes_preds = np.expand_dims(np.array(test_fakes_preds[idx]),axis=1) user_test_gens_preds = np.expand_dims(np.array(test_gens_preds[idx]),axis=1) all_user_test_preds = np.vstack((user_test_fakes_preds,user_test_gens_preds)) all_user_test_labels = np.vstack((np.zeros((user_test_fakes_preds.shape[0],1)),np.ones((user_test_gens_preds.shape[0],1)))) fpr,tpr,threshold = roc_curve(all_user_test_labels,all_user_test_preds) fnr = 1 - tpr EER = fpr[np.nanargmin(np.absolute((fnr - fpr)))] EER_accum += EER print('EER_user for test set : ', (EER_accum*100)/len(test_fakes_preds)) ```
github_jupyter
# 2A.ml - Timeseries et machine learning Série temporelle et prédiction. Module [statsmodels](http://www.statsmodels.org/stable/index.html). ``` %matplotlib inline import matplotlib.pyplot as plt ``` Les séries temporelles diffèrent des problèmes de machine learning classique car les observations ne sont pas indépendantes. Ce notebook présente quelques traitements classiques et une façon assez simple d'appliquer un traitement de machine learning. ``` from jyquickhelper import add_notebook_menu add_notebook_menu() ``` Je ne vais pas refaire ici un cours sur les séries temporelles. Quelques références pour approfondir : * [Différencier (indéfiniment) les séries temporelles ?](https://freakonometrics.hypotheses.org/1876) * [Cours de Séries Temporelles - Arthur Charpentier](http://cours.mido.dauphine.fr/st/cours.html) * [Modèles de prévision Séries temporelles](http://freakonometrics.free.fr/M1_TS_2015.pdf) * [COURS DE SERIES TEMPORELLES THEORIE ET APPLICATIONS](https://perso.univ-rennes1.fr/arthur.charpentier/TS1.pdf) ## Données Prenons comme exemple une série venant de [Google Trend](https://www.google.com/trends/), par exemple le terme [macron](https://www.google.com/trends/explore?geo=FR&q=macron) pris sur la France. ``` from ensae_teaching_cs.data import google_trends t = google_trends("macron") # export CSV, donc pas à jour import pandas df = pandas.read_csv(t, sep=",") df.tail() df.plot(x="Week", y="macron", figsize=(14,4)) ``` ## Période, tendance On enlève tout ce qui précède 08/2014 car la série se comporte de façon différente. Monsieur Macron n'était probablement pas ministre à avant cette date. ``` df[df.Week >= "2014-08"].plot(x="Week", y="macron", figsize=(14,4)) ``` On peut étudier les corrélations entre les différentes dates. Le module le plus approprié est [statsmodels](http://statsmodels.sourceforge.net/devel/index.html). ``` data = df[df.Week >= "2014-08"].copy() ``` La série ne montre pas de période évidente. Regardons la tendance. ``` from statsmodels.tsa.tsatools import detrend notrend = detrend(data.macron) data["notrend"] = notrend data.plot(x="Week", y=["macron", "notrend"], figsize=(14,4)) ``` On vérifie pour la période. ``` from statsmodels.tsa.stattools import acf cor = acf(data.notrend) cor plt.plot(cor) ``` ## Auto-corrélation On recommence sur la série [chocolat](https://www.google.com/trends/explore?geo=FR&q=chocolat). ``` choco = pandas.read_csv(google_trends("chocolat"), sep=",") choco.plot(x="Week", y="chocolat", figsize=(14,4)) choco["notrend"] = detrend(choco.chocolat) cor = acf(choco.notrend) plt.plot(cor) ``` On regarde plus souvent les [auto-corrélations partielles](https://en.wikipedia.org/wiki/Partial_autocorrelation_function). ``` from statsmodels.tsa.stattools import pacf pcor = pacf(choco.notrend) plt.plot(pcor) ``` ## Tendance La fonction [detrend](http://statsmodels.sourceforge.net/stable/generated/statsmodels.tsa.tsatools.detrend.html#statsmodels.tsa.tsatools.detrend) retourne la tendance. On l'obtient en réalisant une régression linéaire de $Y$ sur le temps $t$. ``` from statsmodels.api import OLS import numpy y = data.macron X = numpy.ones((len(y), 2)) X[:,1] = numpy.arange(0,len(y)) reg = OLS(y,X) results = reg.fit() results.params from statsmodels.graphics.regressionplots import abline_plot fig = abline_plot(model_results=results) ax = fig.axes[0] ax.plot(X[:,1], y, 'b') ax.margins(.1) ``` ## Prédictions linéaires On sort ici du cadre linéaire pour utiliser le machine learning non linéaire pour faire de la prédiction. Pour éviter les trop gros problèmes de tendance, on travaillera sur la série différenciée. En théorie, il faudrait différencier jusqu'à ce qu'on enlève la tendance (voir [ARIMA](https://en.wikipedia.org/wiki/Autoregressive_integrated_moving_average)). ``` from ensae_teaching_cs.data import google_trends df = pandas.read_csv(google_trends("chocolat"), sep=",") df.plot(x="Week", y="chocolat", figsize=(14,4)) ``` On calcule la série différenciée. Quelques astuces. [pandas](http://pandas.pydata.org/) utilise les indices par défaut pour faire des opérations sur les colonnes. C'est pourquoi il faut convertir les tableaux extraits du dataframe en [numpy array](http://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html). **N'oubliez pas ce détail. Cela peut devenir très agaçant**. On peut aussi utiliser la fonction [diff](http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.DataFrame.diff.html). ``` df["diff"] = numpy.nan df.loc[1:, "diff"] = (df.iloc[1:, 1].values - df.iloc[:len(df)-1, 1].values) pandas.concat([df.head(n=3), df.tail(n=3)]) df.plot(x="Week", y="diff", figsize=(14,4)) ``` Sans information, la meilleure prédiction est la valeur de la veille (où celle dans le passé à l'horizon de prédiction considéré). Dans notre cas, c'est simplement la variance de la série différenciée : ``` (df["diff"].apply(lambda x:x**2).sum()/len(df))**0.5 from statsmodels.tsa.arima_model import ARMA arma_mod = ARMA(df["diff"].dropna().values, order=(8, 1)) res = arma_mod.fit() res.params ``` **à finir** train/test / prédiciton ## Machine learning On souhaite utiliser une random forest pour faire de la prédiction. On créé la matrice avec les séries décalées. ``` from statsmodels.tsa.tsatools import lagmat lag = 8 X = lagmat(df["diff"], lag) lagged = df.copy() for c in range(1,lag+1): lagged["lag%d" % c] = X[:, c-1] pandas.concat([lagged.head(), lagged.tail()]) ``` On découpe en train/test de façon non aléatoire car c'est une série temporelle. ``` xc = ["lag%d" % i for i in range(1,lag+1)] split = 0.66 isplit = int(len(lagged) * split) xt = lagged[10:][xc] yt = lagged[10:]["diff"] X_train, y_train, X_test, y_test = xt[:isplit], yt[:isplit], xt[isplit:], yt[isplit:] ``` On peut maintenant faire du machine learning sur la série décalé. ``` from sklearn.linear_model import LinearRegression clr = LinearRegression() clr.fit(X_train, y_train) from sklearn.metrics import r2_score r2 = r2_score(y_test.values, clr.predict(X_test)) r2 plt.scatter(y_test.values, clr.predict(X_test)) ``` Non linéaire ``` from sklearn.ensemble import RandomForestRegressor clrf = RandomForestRegressor() clrf.fit(X_train, y_train) from sklearn.metrics import r2_score r2 = r2_score(y_test.values, clrf.predict(X_test)) r2 ``` C'est mieux. ``` plt.scatter(y_test.values, clrf.predict(X_test)) ``` Le modèle prédit bien les extrêmes, il faudrait sans doute les enlever ou utiliser une échelle logarithmique pour réduire leur importance.
github_jupyter
``` import argparse import sys import os import random from tqdm.notebook import tqdm import numpy as np import pandas as pd import torch from sklearn.model_selection import KFold,StratifiedKFold import cv2 import gc import math import matplotlib.pyplot as plt from scipy.stats.mstats import gmean from tensorflow.keras.layers import Input,Dense,Dropout,Embedding,Concatenate,Flatten,LSTM ,Bidirectional,GRU from tensorflow.keras.activations import relu ,sigmoid,softmax from tensorflow.keras.losses import CategoricalCrossentropy import tensorflow as tf import tensorflow_addons as tfa from tensorflow_addons.optimizers import AdamW def seed_all(seed_value): random.seed(seed_value) # Python np.random.seed(seed_value) # cpu vars torch.manual_seed(seed_value) # cpu vars tf.random.set_seed(seed_value+1000) #os.environ['PYTHONHASHSEED'] = str(seed_value) #os.environ['TF_DETERMINISTIC_OPS'] = '1' #os.environ['TF_KERAS'] = '1' if torch.cuda.is_available(): torch.cuda.manual_seed(seed_value) torch.cuda.manual_seed_all(seed_value) # gpu vars torch.backends.cudnn.deterministic = True #needed torch.backends.cudnn.benchmark = False seed_all(42) ``` # Config ``` class Config: n_folds=10 random_state=42 tbs = 1024 vbs = 512 data_path="data" result_path="results" models_path="models" ``` # plot and util ``` def write_to_txt(file_name,column): with open(file_name, 'w') as f: for item in column: f.write("%s\n" % item) ``` # Load data ``` train=pd.read_csv(os.path.join(Config.data_path,"train.csv")) test=pd.read_csv(os.path.join(Config.data_path,"test.csv")) aae=pd.read_csv(os.path.join(Config.data_path,"amino_acid_embeddings.csv")) submission=pd.read_csv(os.path.join(Config.data_path,"SampleSubmission.csv")) ``` # Prepare and split data ``` train["Sequence_len"]=train["Sequence"].apply(lambda x : len(x)) test["Sequence_len"]=test["Sequence"].apply(lambda x : len(x)) max_seq_length = 550 # max seq length in this data set is 550 #stratified k fold train["folds"]=-1 kf = StratifiedKFold(n_splits=Config.n_folds, random_state=Config.random_state, shuffle=True) for fold, (_, val_index) in enumerate(kf.split(train,train["target"])): train.loc[val_index, "folds"] = fold train.head() # reduce seq length if max_seq_length>550 : train["Sequence"] = train["Sequence"].apply(lambda x: "".join(list(x)[0:max_seq_length])) test["Sequence"] = test["Sequence"].apply(lambda x: "".join(list(x)[0:max_seq_length])) voc_set = set(['P', 'V', 'I', 'K', 'N', 'B', 'F', 'Y', 'E', 'W', 'R', 'D', 'X', 'S', 'C', 'U', 'Q', 'A', 'M', 'H', 'L', 'G', 'T']) voc_set_map = { k:v for k , v in zip(voc_set,range(1,len(voc_set)+1))} number_of_class = train["target"].nunique() def encode(text_tensor, label): encoded_text = [ voc_set_map[e] for e in list(text_tensor.numpy().decode())] return encoded_text, label def encode_map_fn(text, label): # py_func doesn't set the shape of the returned tensors. encoded_text, label = tf.py_function(encode, inp=[text, label], Tout=(tf.int64, tf.int64)) encoded_text.set_shape([None]) label=tf.one_hot(label,number_of_class) label.set_shape([number_of_class]) return encoded_text, label def get_data_loader(file,batch_size,labels): label_data=tf.data.Dataset.from_tensor_slices(labels) data_set=tf.data.TextLineDataset(file) data_set=tf.data.Dataset.zip((data_set,label_data)) data_set=data_set.repeat() data_set = data_set.shuffle(len(labels)) data_set=data_set.map(encode_map_fn,tf.data.experimental.AUTOTUNE) data_set=data_set.padded_batch(batch_size) data_set = data_set.prefetch(buffer_size=tf.data.experimental.AUTOTUNE) return data_set def get_data_loader_test(file,batch_size,labels): label_data=tf.data.Dataset.from_tensor_slices(labels.target) data_set=tf.data.TextLineDataset(file) data_set=tf.data.Dataset.zip((data_set,label_data)) data_set=data_set.map(encode_map_fn,tf.data.experimental.AUTOTUNE) data_set=data_set.padded_batch(batch_size) data_set = data_set.prefetch(buffer_size=tf.data.experimental.AUTOTUNE) return data_set ``` # Model ``` def model(): name = "seq" dropout_rate = 0.1 learning_rate = 0.001 sequnce = Input([None],name="sequnce") EMB_layer = Embedding(input_dim = len(voc_set)+1, output_dim = 128, name = "emb_layer") GRU_layer_2 = GRU(units=256, name = "gru_2", return_sequences = False) BIDIR_layer_2 = Bidirectional(GRU_layer_2, name="bidirectional_2") Dens_layer_1 = Dense(units=512, activation=relu, kernel_regularizer=None, bias_regularizer=None, name=name+"_dense_layer_1") Dens_layer_2 = Dense(units=256, activation=relu, kernel_regularizer=None, bias_regularizer=None, name=name+"_dense_layer_2") output = Dense(units=number_of_class, activation=softmax, kernel_regularizer=None, bias_regularizer=None, name=name+"_dense_layer_output") dropout_1 = Dropout(dropout_rate) emb_layer = EMB_layer(sequnce) logits = output(Dens_layer_2(dropout_1(Dens_layer_1(BIDIR_layer_2(emb_layer))))) model = tf.keras.Model(inputs={"sequnce":sequnce, },outputs=logits) optimizer = tf.keras.optimizers.Adam(learning_rate=learning_rate) loss= tfa.losses.SigmoidFocalCrossEntropy(reduction=tf.keras.losses.Reduction.AUTO) #loss=CategoricalCrossentropy() model.compile(optimizer=optimizer, loss=loss, metrics=[tf.keras.metrics.CategoricalAccuracy(name="Acc")]) model.summary() return model ``` # training ``` def trainn(fold): model_path=f"model_{fold}.h5" df_train = train[train["folds"] != fold].reset_index(drop=True) df_valid = train[train["folds"] == fold].reset_index(drop=True) write_to_txt(f"data/train_{fold}.txt",df_train.Sequence) write_to_txt(f"data/valid_{fold}.txt",df_valid.Sequence) train_label=df_train["target"] valid_label=df_valid["target"] train_dl = get_data_loader(f"data/train_{fold}.txt",Config.tbs,train_label) valid_dl = get_data_loader(f"data/valid_{fold}.txt",Config.vbs,valid_label) checkpoint = tf.keras.callbacks.ModelCheckpoint(filepath=os.path.join(Config.models_path,model_path), save_weights_only=True,monitor = 'val_loss', save_best_only=True,mode="min", verbose=1) callbacks=[checkpoint] my_model = model() history = my_model.fit(train_dl, validation_data=valid_dl, epochs=19, verbose=1, batch_size=Config.tbs, validation_batch_size=Config.vbs, validation_steps=len(df_valid)//Config.vbs, steps_per_epoch=len(df_train)/Config.tbs, callbacks=callbacks ) def predict(fold): model_path=f"model_{fold}.h5" write_to_txt(f"data/test_{fold}.txt",test.Sequence) test["target"]=0 test_label=test["target"] test_dl = get_data_loader_test(f"data/test_{fold}.txt",Config.vbs,test) my_model = model() my_model.load_weights(os.path.join(Config.models_path,model_path)) prediction=my_model.predict(test_dl) return prediction trainn(4) p=predict(4) sub=test[["ID"]].copy() for i in range(number_of_class): sub["target_{}".format(i)]=p[:,i] sub.head() sub.to_csv(os.path.join(Config.result_path,"sub_p4_epoch19.csv"),index=False) ```
github_jupyter
``` import os import sys import argparse import tensorflow as tf from tensorflow import keras import pandas as pd from data_loader import read_trainset, DataGenerator import parse_config # comment out if using tensorflow 2.x if parse_config.USING_RTX_20XX: config = tf.compat.v1.ConfigProto() config.gpu_options.allow_growth = True tf.compat.v1.keras.backend.set_session(tf.compat.v1.Session(config=config)) MODEL_NAME = '../models/epoch3.hdf5' img_size = (256,256,3) batch_size=16 test_images_dir = '/media/keil/baltar/intracranial-hemorrhage-detection-data/stage_2_test_images/' testset_filename = "../submissions/stage_2_sample_submission.csv" def read_testset(filename): """ Read the submission sample csv Args: filename (str): Filename of the sample submission Returns: df (panda dataframe): Return a dataframe for inference. """ df = pd.read_csv(filename) df["Image"] = df["ID"].str.slice(stop=12) df["Diagnosis"] = df["ID"].str.slice(start=13) df = df.loc[:, ["Label", "Diagnosis", "Image"]] df = df.set_index(['Image', 'Diagnosis']).unstack(level=-1) return df def create_submission(model, data, test_df): print('+'*50) print("Creating predictions on test dataset") pred = model.predict_generator(data, verbose=1) out_df = pd.DataFrame(pred, index=test_df.index, columns=test_df.columns) test_df = out_df.stack().reset_index() test_df.insert(loc=0, column='ID', value=test_df['Image'].astype(str) + "_" + test_df['Diagnosis']) test_df = test_df.drop(["Image", "Diagnosis"], axis=1) print("Saving submissions to submission.csv") test_df.to_csv('../submissions/stage2-final-submission-v2.csv', index=False) return test_df test_df = read_testset(testset_filename) test_generator = DataGenerator(list_IDs = test_df.index, batch_size = batch_size, img_size = img_size, img_dir = test_images_dir) best_model = keras.models.load_model(MODEL_NAME, compile=False) #test_df shape: (121232, 6) -- 121232 files in stage_2_test via keil$ ls -1 stage_2_test_images/ | wc -l | less assert len(test_generator.indices) == len(test_df == len(test_generator.list_IDs)) #checks out test_df.head() ``` What is going on is the batch size is not evenly divisable by the img count in the test2_stage of 121232/batch of 20 = remainder of 8 images thus the size of 121240 which I was seeing. Confirming now by using a batchsize of 16 which is evenly divisible... will confirm again via batch size = 1 ``` # step through the functon line by line: # create_submission(best_model, test_generator, test_df) # def create_submission(model, data, test_df): pred_batch16 = best_model.predict_generator(test_generator, verbose=1) pred_batch16.shape #good to go.... :D ffs # After getting predictions here is some pandas gymnastics... out_df = pd.DataFrame(pred_batch16, index=test_df.index, columns=test_df.columns) test_df = out_df.stack().reset_index() test_df.insert(loc=0, column='ID', value=test_df['Image'].astype(str) + "_" + test_df['Diagnosis']) test_df = test_df.drop(["Image", "Diagnosis"], axis=1) test_df.to_csv('../submissions/stage2-final-submission-v2.csv', index=False) pred.shape temp_df = pd.DataFrame(pred) temp_df.to_csv('./temp_csv.csv') temp_df.head() ```
github_jupyter
``` # Import Numpy & PyTorch import numpy as np import torch ``` ### create tensors ``` x = torch.tensor(4.) w = torch.tensor(5., requires_grad=True) b = torch.tensor(6., requires_grad=True) # Print tensors print(x) print(w) print(b) ``` ### Equation of a straight line #### y = w * x + b ##### we can automatically compute the derivative of y w.r.t. the tensors that have requires_grad set to True ``` # Arithmetic operations y = w * x + b print(y) ``` #### compute gradients ##### we can automatically compute the derivative of y w.r.t. the tensors that have requires_grad set to True ``` y.backward() # Display gradients print('dy/dw:', w.grad) #dy/dw= x print('dy/db:', b.grad) ####https://www.kaggle.com/aakashns/pytorch-basics-linear-regression-from-scratch ####https://medium.com/dsnet/linear-regression-with-pytorch-3dde91d60b50 #####https://www.kaggle.com/krishanudb/basic-computation-graph-using-pytorch/code ##https://www.kaggle.com/leostep/pytorch-dense-network-for-house-pricing-regression import torch import torch.optim as optim import torch.nn as nn import numpy as np import matplotlib.pyplot as plt input_size = 1 output_size = 1 num_epochs = 10000 learning_rate = 0.001 x_train = np.array([[3.3], [4.4], [5.5], [6.71], [6.93], [4.168],[9.779], [6.182], [7.59], [2.167], [7.042], [10.791], [5.313], [7.997], [3.1]], dtype=np.float32) y_train = np.array([[1.7], [2.76], [2.09], [3.19], [1.694], [1.573], [3.366], [2.596], [2.53], [1.221], [2.827], [3.465], [1.65], [2.904], [1.3]], dtype=np.float32) model = nn.Linear(input_size, output_size) # Loss Function: criterion = nn.MSELoss() optimizer = optim.SGD(model.parameters(), lr=learning_rate) ####https://www.kaggle.com/kunal627/titanic-logistic-regression-with-python ####https://www.kaggle.com/kiranscaria/titanic-pytorch ####https://www.kaggle.com/dpamgautam/pytorch-linear-regression ####https://bennydai.files.wordpress.com/2018/02/iris-example-pytorch-implementation.pdf ##https://www.kaggle.com/dpamgautam/linear-and-logistic-regression-using-pytorch #### ols--> house price: https://towardsdatascience.com/create-a-model-to-predict-house-prices-using-python-d34fe8fad88f import pandas as pd import numpy as np dataset = pd.read_csv('titanic_raw.csv') X_test = pd.read_csv('titanic_test.csv') dataset_title = [i.split(',')[1].split('.')[0].strip() for i in dataset['Name']] dataset['Title'] = pd.Series(dataset_title) dataset['Title'].value_counts() dataset['Title'] = dataset['Title'].replace(['Lady', 'the Countess', 'Countess', 'Capt', 'Col', 'Don', 'Dr', 'Major', 'Rev', 'Sir', 'Jonkheer', 'Dona', 'Ms', 'Mme', 'Mlle'], 'Rare') dataset_title = [i.split(',')[1].split('.')[0].strip() for i in X_test['Name']] X_test['Title'] = pd.Series(dataset_title) X_test['Title'].value_counts() X_test['Title'] = X_test['Title'].replace(['Lady', 'the Countess', 'Countess', 'Capt', 'Col', 'Don', 'Dr', 'Major', 'Rev', 'Sir', 'Jonkheer', 'Dona', 'Ms', 'Mme', 'Mlle'], 'Rare') dataset['FamilyS'] = dataset['SibSp'] + dataset['Parch'] + 1 X_test['FamilyS'] = X_test['SibSp'] + X_test['Parch'] + 1 def family(x): if x < 2: return 'Single' elif x == 2: return 'Couple' elif x <= 4: return 'InterM' else: return 'Large' dataset['FamilyS'] = dataset['FamilyS'].apply(family) X_test['FamilyS'] = X_test['FamilyS'].apply(family) dataset['Embarked'].fillna(dataset['Embarked'].mode()[0], inplace=True) X_test['Embarked'].fillna(X_test['Embarked'].mode()[0], inplace=True) dataset['Age'].fillna(dataset['Age'].median(), inplace=True) X_test['Age'].fillna(X_test['Age'].median(), inplace=True) X_test['Fare'].fillna(X_test['Fare'].median(), inplace=True) ``` ### see data type ``` titanic.dtypes ## see data type ``` ### remove columns ### Do we have NAs? ``` print('Columns with null values:\n', titanic.isnull().sum()) #### make a copy of the data frame t1 = titanic.copy(deep = True) t_drop=t1.dropna() print('Columns with null values:\n', t_drop.isnull().sum()) t2 = titanic.copy(deep = True) ##another copy ```
github_jupyter
# Módulo 2: HTML: Requests y BeautifulSoup ## Parsing Pagina12 <img src='https://www.pagina12.com.ar/assets/media/logos/logo_pagina_12_n.svg?v=1.0.178' width=300></img> En este módulo veremos cómo utilizar las bibliotecas `requests` y `bs4` para programar scrapers de sitios HTML. Nos propondremos armar un scraper de noticias del diario <a href='www.pagina12.com.ar'>Página 12</a>. Supongamos que queremos leer el diario por internet. Lo primero que hacemos es abrir el navegador, escribir la URL del diario y apretar Enter para que aparezca la página del diario. Lo que ocurre en el momento en el que apretamos Enter es lo siguiente: 1. El navegador envía una solicitud a la URL pidiéndole información. 2. El servidor recibe la petición y procesa la respuesta. 3. El servidor envía la respuesta a la IP de la cual recibió la solicitud. 4. Nuestro navegador recibe la respuesta y la muestra **formateada** en pantalla. Para hacer un scraper debemos hacer un programa que replique este flujo de forma automática para luego extraer la información deseada de la respuesta. Utilizaremos `requests` para realizar peticiones y recibir las respuestas y `bs4` para *parsear* la respuesta y extraer la información.<br> Te dejo unos links que tal vez te sean de utilidad: - [Códigos de status HTTP](https://developer.mozilla.org/es/docs/Web/HTTP/Status) - [Documentación de requests](https://requests.kennethreitz.org/en/master/) - [Documentación de bs4](https://www.crummy.com/software/BeautifulSoup/bs4/doc/) ``` import requests url = 'https://www.pagina12.com.ar/' p12 = requests.get(url) p12.status_code p12.content ``` Muchas veces la respuesta a la solicitud puede ser algo que no sea un texto: una imagen, un archivo de audio, un video, etc. ``` p12.text ``` Analicemos otros elementos de la respuesta ``` p12.headers p12.request.headers ``` El contenido de la request que acabamos de hacer está avisando que estamos utilizando la biblioteca requests para python y que no es un navegador convencional. Se puede modificar ``` p12.cookies from bs4 import BeautifulSoup s = BeautifulSoup(p12.text, 'lxml') type(s) print(s.prettify()) ``` Primer ejercicio: obtener un listado de links a las distintas secciones del diario.<br> Usar el inspector de elementos para ver dónde se encuentra la información. ``` secciones = s.find('ul', attrs={'class':'hot-sections'}).find_all('li') secciones [seccion.text for seccion in secciones] seccion = secciones[0] seccion.a.get('href') ``` Estamos interesados en los links, no en el texto ``` links_secciones = [seccion.a.get('href') for seccion in secciones] links_secciones ``` Carguemos la página de una sección para ver cómo se compone ``` sec = requests.get(links_secciones[0]) sec sec.request.url soup_seccion = BeautifulSoup(sec.text, 'lxml') print(soup_seccion.prettify()) ``` La página se divide en un artículo promocionado y una lista `<ul>` con el resto de los artículos ``` featured_article = soup_seccion.find('div', attrs={'class':'featured-article__container'}) featured_article featured_article.a.get('href') article_list = soup_seccion.find('ul', attrs={'class':'article-list'}) def obtener_notas(soup): ''' Función que recibe un objeto de BeautifulSoup de una página de una sección y devuelve una lista de URLs a las notas de esa sección ''' lista_notas = [] # Obtengo el artículo promocionado featured_article = soup.find('div', attrs={'class':'featured-article__container'}) if featured_article: lista_notas.append(featured_article.a.get('href')) # Obtengo el listado de artículos article_list = soup.find('ul', attrs={'class':'article-list'}) for article in article_list.find_all('li'): if article.a: lista_notas.append(article.a.get('href')) return lista_notas ``` Probemos la función ``` lista_notas = obtener_notas(soup_seccion) lista_notas ``` ## Clase 6 En esta clase te voy a hablar un poco del manejo de errores. Para eso vamos a tomar como ejemplo uno de los links que obtuvimos con la función que tenías que armar en la clase anterior. Código de error != 200 ``` r = requests.get(lista_notas[0]) if r.status_code == 200: # Procesamos la respuesta print('procesamos..') else: # Informar el error print('informamos...') url_nota = lista_notas[0] print(url_nota) ``` Supongamos que el link a la nota está mal cargado, o que sacaron la nota del sitio, o que directamente no está funcionando la web de página 12. ``` url_mala = url_nota.replace('2','3') print(url_mala) ``` Esto lo hacemos sólo para simular una URL mal cargada o un sevidor caído ``` r = requests.get(url_mala) if r.status_code == 200: # Procesamos la respuesta print('procesamos..') else: # Informar el error print('informamos status code != 200') ``` Obtuvimos un error que interrumpió la ejecución del código. No llegamos a imprimir el status code. Muchas veces estos errores son inevitables y no dependen de nosotros. Lo que sí depende de nosotros es cómo procesarlos y escribir un código que sea robusto y resistente a los errores. ``` try: nota = requests.get(url_mala) except: print('Error en la request!\n') print('El resto del programa continúa...') ``` Las buenas prácticas de programación incluyen el manejo de errores para darle robustez al código ``` try: nota = requests.get(url_mala) except Exception as e: print('Error en la request:') print(e) print('\n') print('El resto del programa continúa...') ``` Lo mismo ocurre cuando encadenamos búsquedas. Retomemos esta línea ``` featured_article.a.get('href') ``` Si no existe el tag "a", obtendremos un error que dice que un objeto None no tiene ningún método .get('href') ``` try: featured_article.a.get('href') except: pass ```
github_jupyter
STAT 453: Deep Learning (Spring 2020) Instructor: Sebastian Raschka (sraschka@wisc.edu) Course website: http://pages.stat.wisc.edu/~sraschka/teaching/stat453-ss2020/ GitHub repository: https://github.com/rasbt/stat453-deep-learning-ss20 ``` %load_ext watermark %watermark -a 'Sebastian Raschka' -v -p torch ``` - Runs on CPU or GPU (if available) # Convolutional GAN (Not Great) ## Imports ``` import time import numpy as np import torch import torch.nn.functional as F from torchvision import datasets from torchvision import transforms import torch.nn as nn from torch.utils.data import DataLoader if torch.cuda.is_available(): torch.backends.cudnn.deterministic = True ``` ## Settings and Dataset ``` ########################## ### SETTINGS ########################## # Device device = torch.device("cuda:1" if torch.cuda.is_available() else "cpu") # Hyperparameters random_seed = 42 generator_learning_rate = 0.0001 discriminator_learning_rate = 0.0001 num_epochs = 100 BATCH_SIZE = 128 LATENT_DIM = 100 IMG_SHAPE = (1, 28, 28) IMG_SIZE = 1 for x in IMG_SHAPE: IMG_SIZE *= x ########################## ### MNIST DATASET ########################## # Note transforms.ToTensor() scales input images # to 0-1 range train_dataset = datasets.MNIST(root='data', train=True, transform=transforms.ToTensor(), download=True) test_dataset = datasets.MNIST(root='data', train=False, transform=transforms.ToTensor()) train_loader = DataLoader(dataset=train_dataset, batch_size=BATCH_SIZE, num_workers=4, shuffle=True) test_loader = DataLoader(dataset=test_dataset, batch_size=BATCH_SIZE, num_workers=4, shuffle=False) # Checking the dataset for images, labels in train_loader: print('Image batch dimensions:', images.shape) print('Image label dimensions:', labels.shape) break ``` ## Model ``` ########################## ### MODEL ########################## class Flatten(nn.Module): def forward(self, input): return input.view(input.size(0), -1) class Reshape1(nn.Module): def forward(self, input): return input.view(input.size(0), 16, 7, 7) class GAN(torch.nn.Module): def __init__(self): super(GAN, self).__init__() self.generator = nn.Sequential( nn.Linear(LATENT_DIM, 784), nn.LeakyReLU(inplace=True), Reshape1(), nn.ConvTranspose2d(in_channels=16, out_channels=16, kernel_size=(2, 2), stride=(2, 2), padding=0), nn.LeakyReLU(inplace=True), nn.Conv2d(in_channels=16, out_channels=8, padding=1, kernel_size=(2, 2)), nn.LeakyReLU(inplace=True), nn.ConvTranspose2d(in_channels=8, out_channels=8, kernel_size=(3, 3), stride=(2, 2), padding=1), nn.LeakyReLU(inplace=True), nn.Conv2d(in_channels=8, out_channels=4, padding=1, kernel_size=(3, 3)), nn.LeakyReLU(inplace=True), nn.Conv2d(in_channels=4, out_channels=1, padding=0, kernel_size=(2, 2)), nn.Tanh() ) self.discriminator = nn.Sequential( nn.Conv2d(in_channels=1, out_channels=8, padding=1, kernel_size=(3, 3)), nn.LeakyReLU(inplace=True), nn.Conv2d(in_channels=8, out_channels=8, padding=1, stride=2, kernel_size=(3, 3)), nn.LeakyReLU(inplace=True), nn.Conv2d(in_channels=8, out_channels=16, padding=1, kernel_size=(3, 3)), nn.LeakyReLU(inplace=True), nn.Conv2d(in_channels=16, out_channels=16, padding=1, stride=2, kernel_size=(3, 3)), nn.LeakyReLU(inplace=True), nn.Conv2d(in_channels=16, out_channels=32, padding=1, kernel_size=(3, 3)), nn.LeakyReLU(inplace=True), nn.Conv2d(in_channels=32, out_channels=32, padding=1, stride=2, kernel_size=(3, 3)), nn.LeakyReLU(inplace=True), nn.AdaptiveAvgPool2d(1), Flatten(), nn.Linear(32, 16), nn.LeakyReLU(inplace=True), nn.Linear(16, 1), nn.Sigmoid() ) def generator_forward(self, z): img = self.generator(z) return img def discriminator_forward(self, img): pred = model.discriminator(img) return pred.view(-1) torch.manual_seed(random_seed) #del model model = GAN() model = model.to(device) print(model) ### ## FOR DEBUGGING """ outputs = [] def hook(module, input, output): outputs.append(output) #for i, layer in enumerate(model.discriminator): # if isinstance(layer, torch.nn.modules.conv.Conv2d): # model.discriminator[i].register_forward_hook(hook) for i, layer in enumerate(model.generator): if isinstance(layer, torch.nn.modules.conv.Conv2d): model.generator[i].register_forward_hook(hook) """ optim_gener = torch.optim.Adam(model.generator.parameters(), lr=generator_learning_rate) optim_discr = torch.optim.Adam(model.discriminator.parameters(), lr=discriminator_learning_rate) ``` ## Training ``` start_time = time.time() discr_costs = [] gener_costs = [] for epoch in range(num_epochs): model = model.train() for batch_idx, (features, targets) in enumerate(train_loader): # Normalize images to [-1, 1] range features = (features - 0.5)*2. features = features.view(-1, IMG_SIZE).to(device) targets = targets.to(device) valid = torch.ones(targets.size(0)).float().to(device) fake = torch.zeros(targets.size(0)).float().to(device) ### FORWARD AND BACK PROP # -------------------------- # Train Generator # -------------------------- # Make new images z = torch.zeros((targets.size(0), LATENT_DIM)).uniform_(-1.0, 1.0).to(device) generated_features = model.generator_forward(z) # Loss for fooling the discriminator discr_pred = model.discriminator_forward(generated_features.view(targets.size(0), 1, 28, 28)) gener_loss = F.binary_cross_entropy(discr_pred, valid) optim_gener.zero_grad() gener_loss.backward() optim_gener.step() # -------------------------- # Train Discriminator # -------------------------- discr_pred_real = model.discriminator_forward(features.view(targets.size(0), 1, 28, 28)) real_loss = F.binary_cross_entropy(discr_pred_real, valid) discr_pred_fake = model.discriminator_forward(generated_features.view(targets.size(0), 1, 28, 28).detach()) fake_loss = F.binary_cross_entropy(discr_pred_fake, fake) discr_loss = 0.5*(real_loss + fake_loss) optim_discr.zero_grad() discr_loss.backward() optim_discr.step() discr_costs.append(discr_loss.item()) gener_costs.append(gener_loss.item()) ### LOGGING if not batch_idx % 100: print ('Epoch: %03d/%03d | Batch %03d/%03d | Gen/Dis Loss: %.4f/%.4f' %(epoch+1, num_epochs, batch_idx, len(train_loader), gener_loss, discr_loss)) print('Time elapsed: %.2f min' % ((time.time() - start_time)/60)) print('Total Training Time: %.2f min' % ((time.time() - start_time)/60)) ### For Debugging """ for i in outputs: print(i.size()) """ ``` ## Evaluation ``` %matplotlib inline import matplotlib.pyplot as plt plt.plot(range(len(gener_costs)), gener_costs, label='generator loss') plt.plot(range(len(discr_costs)), discr_costs, label='discriminator loss') plt.legend() plt.show() ########################## ### VISUALIZATION ########################## model.eval() # Make new images z = torch.zeros((5, LATENT_DIM)).uniform_(-1.0, 1.0).to(device) generated_features = model.generator_forward(z) imgs = generated_features.view(-1, 28, 28) fig, axes = plt.subplots(nrows=1, ncols=5, figsize=(20, 2.5)) for i, ax in enumerate(axes): axes[i].imshow(imgs[i].to(torch.device('cpu')).detach(), cmap='binary') ```
github_jupyter
<!--BOOK_INFORMATION--> <img align="left" style="padding-right:10px;" src="fig/cover-small.jpg"> *This notebook contains an excerpt from the [Whirlwind Tour of Python](http://www.oreilly.com/programming/free/a-whirlwind-tour-of-python.csp) by Jake VanderPlas; the content is available [on GitHub](https://github.com/jakevdp/WhirlwindTourOfPython).* *The text and code are released under the [CC0](https://github.com/jakevdp/WhirlwindTourOfPython/blob/master/LICENSE) license; see also the companion project, the [Python Data Science Handbook](https://github.com/jakevdp/PythonDataScienceHandbook).* <!--NAVIGATION--> < [Built-In Data Structures](06-Built-in-Data-Structures.ipynb) | [Contents](Index.ipynb) | [Defining and Using Functions](08-Defining-Functions.ipynb) > # Control Flow *Control flow* is where the rubber really meets the road in programming. Without it, a program is simply a list of statements that are sequentially executed. With control flow, you can execute certain code blocks conditionally and/or repeatedly: these basic building blocks can be combined to create surprisingly sophisticated programs! Here we'll cover *conditional statements* (including "``if``", "``elif``", and "``else``"), *loop statements* (including "``for``" and "``while``" and the accompanying "``break``", "``continue``", and "``pass``"). ## Conditional Statements: ``if``-``elif``-``else``: Conditional statements, often referred to as *if-then* statements, allow the programmer to execute certain pieces of code depending on some Boolean condition. A basic example of a Python conditional statement is this: ``` x = -15 if x == 0: print(x, "is zero") elif x > 0: print(x, "is positive") elif x < 0: print(x, "is negative") else: print(x, "is unlike anything I've ever seen...") ``` Note especially the use of colons (``:``) and whitespace to denote separate blocks of code. Python adopts the ``if`` and ``else`` often used in other languages; its more unique keyword is ``elif``, a contraction of "else if". In these conditional clauses, ``elif`` and ``else`` blocks are optional; additionally, you can optinally include as few or as many ``elif`` statements as you would like. ## ``for`` loops Loops in Python are a way to repeatedly execute some code statement. So, for example, if we'd like to print each of the items in a list, we can use a ``for`` loop: ``` for N in [2, 3, 5, 7]: print(N, end=' ') # print all on same line ``` Notice the simplicity of the ``for`` loop: we specify the variable we want to use, the sequence we want to loop over, and use the "``in``" operator to link them together in an intuitive and readable way. More precisely, the object to the right of the "``in``" can be any Python *iterator*. An iterator can be thought of as a generalized sequence, and we'll discuss them in [Iterators](10-Iterators.ipynb). For example, one of the most commonly-used iterators in Python is the ``range`` object, which generates a sequence of numbers: ``` for i in range(10): print(i, end=' ') ``` Note that the range starts at zero by default, and that by convention the top of the range is not included in the output. Range objects can also have more complicated values: ``` # range from 5 to 10 list(range(5, 10)) # range from 0 to 10 by 2 list(range(0, 10, 2)) ``` You might notice that the meaning of ``range`` arguments is very similar to the slicing syntax that we covered in [Lists](06-Built-in-Data-Structures.ipynb#Lists). Note that the behavior of ``range()`` is one of the differences between Python 2 and Python 3: in Python 2, ``range()`` produces a list, while in Python 3, ``range()`` produces an iterable object. ## ``while`` loops The other type of loop in Python is a ``while`` loop, which iterates until some condition is met: ``` i = 0 while i < 10: print(i, end=' ') i += 1 ``` The argument of the ``while`` loop is evaluated as a boolean statement, and the loop is executed until the statement evaluates to False. ## ``break`` and ``continue``: Fine-Tuning Your Loops There are two useful statements that can be used within loops to fine-tune how they are executed: - The ``break`` statement breaks-out of the loop entirely - The ``continue`` statement skips the remainder of the current loop, and goes to the next iteration These can be used in both ``for`` and ``while`` loops. Here is an example of using ``continue`` to print a string of odd numbers. In this case, the result could be accomplished just as well with an ``if-else`` statement, but sometimes the ``continue`` statement can be a more convenient way to express the idea you have in mind: ``` for n in range(20): # if the remainder of n / 2 is 0, skip the rest of the loop if n % 2 == 0: continue print(n, end=' ') ``` Here is an example of a ``break`` statement used for a less trivial task. This loop will fill a list with all Fibonacci numbers up to a certain value: ``` a, b = 0, 1 amax = 100 L = [] while True: (a, b) = (b, a + b) if a > amax: break L.append(a) print(L) ``` Notice that we use a ``while True`` loop, which will loop forever unless we have a break statement! ## Loops with an ``else`` Block One rarely used pattern available in Python is the ``else`` statement as part of a ``for`` or ``while`` loop. We discussed the ``else`` block earlier: it executes if all the ``if`` and ``elif`` statements evaluate to ``False``. The loop-``else`` is perhaps one of the more confusingly-named statements in Python; I prefer to think of it as a ``nobreak`` statement: that is, the ``else`` block is executed only if the loop ends naturally, without encountering a ``break`` statement. As an example of where this might be useful, consider the following (non-optimized) implementation of the *Sieve of Eratosthenes*, a well-known algorithm for finding prime numbers: ``` L = [] nmax = 30 for n in range(2, nmax): for factor in L: if n % factor == 0: break else: # no break L.append(n) print(L) ``` The ``else`` statement only executes if none of the factors divide the given number. The ``else`` statement works similarly with the ``while`` loop. <!--NAVIGATION--> < [Built-In Data Structures](06-Built-in-Data-Structures.ipynb) | [Contents](Index.ipynb) | [Defining and Using Functions](08-Defining-Functions.ipynb) >
github_jupyter
``` import numpy as np import pprint import sys if "../" not in sys.path: sys.path.append("../") from lib.envs.gridworld import GridworldEnv pp = pprint.PrettyPrinter(indent=2) env = GridworldEnv() ``` The implemented function in the policy evaluation is the following : ![Formula](FormulaIterativePolicy.png) ``` # Taken from Policy Evaluation Exercise! def policy_eval(policy, env, discount_factor=1.0, theta=0.00001): """ Evaluate a policy given an environment and a full description of the environment's dynamics. Args: policy: [S, A] shaped matrix representing the policy. env: OpenAI env. env.P represents the transition probabilities of the environment. env.P[s][a] is a list of transition tuples (prob, next_state, reward, done). env.nS is a number of states in the environment. env.nA is a number of actions in the environment. theta: We stop evaluation once our value function change is less than theta for all states. discount_factor: Gamma discount factor. Returns: Vector of length env.nS representing the value function. """ # Start with a random (all 0) value function V = np.zeros(env.nS) while True: delta = 0 # For each state, perform a "full backup" for s in range(env.nS): v = 0 # Look at the possible next actions for a, action_prob in enumerate(policy[s]): # For each action, look at the possible next states... for prob, next_state, reward, done in env.P[s][a]: # Calculate the expected value v += action_prob * prob * (reward + discount_factor * V[next_state]) # How much our value function changed (across any states) delta = max(delta, np.abs(v - V[s])) V[s] = v # Stop evaluating once our value function change is below a threshold if delta < theta: break return np.array(V) def policy_improvement(env, policy_eval_fn=policy_eval, discount_factor=1.0): """ Policy Improvement Algorithm. Iteratively evaluates and improves a policy until an optimal policy is found. Args: env: The OpenAI envrionment. policy_eval_fn: Policy Evaluation function that takes 3 arguments: policy, env, discount_factor. discount_factor: gamma discount factor. Returns: A tuple (policy, V). policy is the optimal policy, a matrix of shape [S, A] where each state s contains a valid probability distribution over actions. V is the value function for the optimal policy. """ # Start with a random policy policy = np.ones([env.nS, env.nA]) / env.nA while True: # Implement this! break return policy, np.zeros(env.nS) policy, v = policy_improvement(env) print("Policy Probability Distribution:") print(policy) print("") print("Reshaped Grid Policy (0=up, 1=right, 2=down, 3=left):") print(np.reshape(np.argmax(policy, axis=1), env.shape)) print("") print("Value Function:") print(v) print("") print("Reshaped Grid Value Function:") print(v.reshape(env.shape)) print("") # Test the value function expected_v = np.array([ 0, -1, -2, -3, -1, -2, -3, -2, -2, -3, -2, -1, -3, -2, -1, 0]) np.testing.assert_array_almost_equal(v, expected_v, decimal=2) ```
github_jupyter
___ <a href='https://github.com/ai-vithink'> <img src='https://avatars1.githubusercontent.com/u/41588940?s=200&v=4' /></a> ___ # Seaborn Exercises Time to practice your new seaborn skills! Try to recreate the plots below (don't worry about color schemes, just the plot itself. ## The Data We will be working with a famous titanic data set for these exercises. Later on in the Machine Learning section of the course, we will revisit this data, and use it to predict survival rates of passengers. For now, we'll just focus on the visualization of the data with seaborn: ``` import seaborn as sns import matplotlib.pyplot as plt %matplotlib inline import scipy.stats as stats from IPython.display import HTML HTML('''<script> code_show_err=false; function code_toggle_err() { if (code_show_err){ $('div.output_stderr').hide(); } else { $('div.output_stderr').show(); } code_show_err = !code_show_err } $( document ).ready(code_toggle_err); </script> To toggle on/off output_stderr, click <a href="javascript:code_toggle_err()">here</a>.''') # To hide warnings, which won't change the desired outcome. %%HTML <style type="text/css"> table.dataframe td, table.dataframe th { border: 3px black solid !important; color: black !important; } # For having gridlines import warnings warnings.filterwarnings("ignore") sns.set_style('darkgrid') sns.set_style('whitegrid') titanic = sns.load_dataset('titanic') titanic.head() ``` # Exercises **Recreate the plots below using the titanic dataframe. There are very few hints since most of the plots can be done with just one or two lines of code and a hint would basically give away the solution. Keep careful attention to the x and y labels for hints.** **Note! In order to not lose the plot image, make sure you don't code in the cell that is directly above the plot, there is an extra cell above that one which won't overwrite that plot!* ** ``` # CODE HERE # REPLICATE EXERCISE PLOT IMAGE BELOW # BE CAREFUL NOT TO OVERWRITE CELL BELOW # THAT WOULD REMOVE THE EXERCISE PLOT IMAGE! a = sns.jointplot(x = 'fare',y='age',data=titanic) a.annotate(stats.pearsonr) # CODE HERE # REPLICATE EXERCISE PLOT IMAGE BELOW # BE CAREFUL NOT TO OVERWRITE CELL BELOW # THAT WOULD REMOVE THE EXERCISE PLOT IMAGE! sns.distplot(titanic['fare'],bins=30,kde=False,color='red') # CODE HERE # REPLICATE EXERCISE PLOT IMAGE BELOW # BE CAREFUL NOT TO OVERWRITE CELL BELOW # THAT WOULD REMOVE THE EXERCISE PLOT IMAGE! sns.boxplot(x='class',y='age',data=titanic,palette='rainbow') # CODE HERE # REPLICATE EXERCISE PLOT IMAGE BELOW # BE CAREFUL NOT TO OVERWRITE CELL BELOW # THAT WOULD REMOVE THE EXERCISE PLOT IMAGE! sns.swarmplot(x='class',y='age',data=titanic,palette='Set2') # CODE HERE # REPLICATE EXERCISE PLOT IMAGE BELOW # BE CAREFUL NOT TO OVERWRITE CELL BELOW # THAT WOULD REMOVE THE EXERCISE PLOT IMAGE! sns.countplot(x='sex',data=titanic) # CODE HERE # REPLICATE EXERCISE PLOT IMAGE BELOW # BE CAREFUL NOT TO OVERWRITE CELL BELOW # THAT WOULD REMOVE THE EXERCISE PLOT IMAGE! titanic.head() tc = titanic.corr() tc sns.heatmap(tc,cmap='coolwarm') plt.title('titanic.corr()') # CODE HERE # REPLICATE EXERCISE PLOT IMAGE BELOW # BE CAREFUL NOT TO OVERWRITE CELL BELOW # THAT WOULD REMOVE THE EXERCISE PLOT IMAGE! g = sns.FacetGrid(data=titanic,col='sex') g.map(plt.hist,'age') ``` # Great Job! ### That is it for now! We'll see a lot more of seaborn practice problems in the machine learning section!
github_jupyter
# Tutorial 6: Population Level Modeling (with PopNet) In this tutorial we will focus on modeling of populations and population firing rates. This is done with the PopNet simulator application of bmtk which uses [DiPDE](https://github.com/AllenInstitute/dipde) engine as a backend. We will first build our networks using the bmtk NetworkBuilder and save them into the SONATA data format. Then we will show how to simulate the firing rates over a given time-source. Requirements: * BMTK * DiPDE ## 1. Building the network #### Converting existing networks Like BioNet for biophysically detailed modeling, and PointNet with point-based networks, PopNet stores networks in the SONATA data format. PopNet supports simulating networks of individual cells at the population level. First thing you have to do is modify the node-types and edge-types of an existing network to use Population level models (rather than models of individual cells. <div class="alert alert-warning"> **WARNING** - Converting a network of individual nodes into population of nodes is good for a quick and naive simulation, but for faster and more reliable results it's best to build a network from scratch (next section). </div> Here is the node-types csv file of a network set to work with BioNet ``` import pandas as pd pd.read_csv('sources/chapter06/converted_network/V1_node_types_bionet.csv', sep=' ') ``` vs the equivelent form for PopNet ``` pd.read_csv('sources/chapter06/converted_network/V1_node_types_popnet.csv', sep=' ') ``` Some things to note: * **model_type** is now a population for all nodes, rather than individual biophysical/point types * We have set **model_template** to dipde:Internal which will tell the simulator to use special DiPDE model types * We are using new **dynamic_params** files with parameters that have been adjusted to appropiate range for DiPDE models. * **morophology_file** and **model_processing**, which were used to set and processes individual cell morphologies, is no longer applicable. We must make similar adjustments to our edge_types.csv files. And finally when we run the simulation we must tell PopNet to cluster nodes together using the **group_by** property ```python network = popnet.PopNetwork.from_config(configure, group_by='node_type_id') ``` #### Building a network We will create a network of two populations, one population of excitatory cells and another of inhibitory cells. Then we will save the network into SONATA formated data files. The first step is to use the NetworkBuilder to instantiate a new network with two populations: ``` from bmtk.builder import NetworkBuilder net = NetworkBuilder('V1') net.add_nodes(pop_name='excitatory', # name of specific population optional ei='e', # Optional location='VisL4', # Optional model_type='population', # Required, indicates what types of cells are being model model_template='dipde:Internal', # Required, instructs what DiPDE objects will be created dynamics_params='exc_model.json' # Required, contains parameters used by DiPDE during initialization of object ) net.add_nodes(pop_name='inhibitory', ei='i', model_type='population', model_template='dipde:Internal', dynamics_params='inh_model.json') ``` Next we will create connections between the two populations: ``` net.add_edges(source={'ei': 'e'}, target={'ei': 'i'}, syn_weight=0.005, nsyns=20, delay=0.002, dynamics_params='ExcToInh.json') net.add_edges(source={'ei': 'i'}, target={'ei': 'e'}, syn_weight=-0.002, nsyns=10, delay=0.002, dynamics_params='InhToExc.json') ``` and finally we must build and save the network ``` net.build() net.save_nodes(output_dir='network') net.save_edges(output_dir='network') ``` ##### External Nodes The *dipde:Internal* nodes we created don't carry intrinsic firing rates, and instead we will use External Populations to drive the network activity. To do this we will create a separate network of 'virtual' populations, or alternativly use model_type=dipde:External, that connect to our excitatory population. Note: we could add 'virtual' populations directly to our V1 network. However creating them as a separate network provides a great advantage if/when we want to replace our external connections with a different model (Or if we want to remove the reccurrent connections and simulation with only feed-foward activity). ``` input_net = NetworkBuilder('LGN') input_net.add_nodes(pop_name='tON', ei='e', model_type='virtual') input_net.add_edges(target=net.nodes(ei='e'), syn_weight=0.0025, nsyns=10, delay=0.002, dynamics_params='input_ExcToExc.json') input_net.build() input_net.save_nodes(output_dir='network') input_net.save_edges(output_dir='network') ``` ## 2. Setting up the PopNet environment Before running the simulation we need to set up our simulation environment, inlcuding setting up run-scripts, configuration parameters, and placing our parameter files in their appropiate location. The easiest way to do this is through the command-line: ```bash $ python -m bmtk.utils.sim_setup -n network --run-time 1500.0 popnet ``` Which creates initial files to run a 1500 ms simulation using the network files found in our ./network directory. #### Inputs We next need to set the firing rates of the External Population. There are multiple ways to set this value which will be discussed later. The best way is to set the firing rates using a input-rates file for each External Population, we can fetch an existing one using the command: ```bash $ wget https://github.com/AllenInstitute/bmtk/raw/develop/docs/examples/pop_2pops/lgn_rates.csv ``` Then we must open the simulation_config.json file with a text editor and add the lgn_rates.csv file as a part of our inputs: ```json { "inputs": { "LGN_pop_rates": { "input_type": "csv", "module": "pop_rates", "rates": "${BASE_DIR}/lgn_rates.csv", "node_set": "LGN" } } } ``` ## 3. Running the simulation The call to sim_setup created a file run_pointnet.py which we can run directly in a command line: ```bash $ python run_popnet.py config.json ``` Or we can run it directly using the following python code: ``` from bmtk.simulator import popnet configure = popnet.config.from_json('simulation_config.json') configure.build_env() network = popnet.PopNetwork.from_config(configure) sim = popnet.PopSimulator.from_config(configure, network) sim.run() ``` ## 4. Analyzing results As specified in the "output" section of simulation_config.json, the results will be written to ouput/spike_rates.csv. The BMTK analyzer includes code for ploting and analyzing the firing rates of our network: ``` from bmtk.analyzer.firing_rates import plot_rates_popnet plot_rates_popnet('network/V1_node_types.csv', 'output/firing_rates.csv', model_keys='pop_name') ```
github_jupyter