code
stringlengths
2.5k
150k
kind
stringclasses
1 value
``` from cbrain.imports import * from cbrain.utils import * from cbrain.normalization import * import h5py from sklearn.preprocessing import OneHotEncoder class DataGeneratorClassification(tf.keras.utils.Sequence): def __init__(self, data_fn, input_vars, output_vars, percentile_path, data_name, norm_fn=None, input_transform=None, output_transform=None, batch_size=1024, shuffle=True, xarray=False, var_cut_off=None, normalize_flag=True, bin_size=100): # Just copy over the attributes self.data_fn, self.norm_fn = data_fn, norm_fn self.input_vars, self.output_vars = input_vars, output_vars self.batch_size, self.shuffle = batch_size, shuffle self.bin_size = bin_size self.percentile_bins = load_pickle(percentile_path)['Percentile'][data_name] self.enc = OneHotEncoder(sparse=False) classes = np.arange(self.bin_size+2) self.enc.fit(classes.reshape(-1,1)) # Open datasets self.data_ds = xr.open_dataset(data_fn) if norm_fn is not None: self.norm_ds = xr.open_dataset(norm_fn) # Compute number of samples and batches self.n_samples = self.data_ds.vars.shape[0] self.n_batches = int(np.floor(self.n_samples) / self.batch_size) # Get input and output variable indices self.input_idxs = return_var_idxs(self.data_ds, input_vars, var_cut_off) self.output_idxs = return_var_idxs(self.data_ds, output_vars) self.n_inputs, self.n_outputs = len(self.input_idxs), len(self.output_idxs) # Initialize input and output normalizers/transformers if input_transform is None: self.input_transform = Normalizer() elif type(input_transform) is tuple: ## normalize flag added by Ankitesh self.input_transform = InputNormalizer( self.norm_ds,normalize_flag, input_vars, input_transform[0], input_transform[1], var_cut_off) else: self.input_transform = input_transform # Assume an initialized normalizer is passed if output_transform is None: self.output_transform = Normalizer() elif type(output_transform) is dict: self.output_transform = DictNormalizer(self.norm_ds, output_vars, output_transform) else: self.output_transform = output_transform # Assume an initialized normalizer is passed # Now close the xarray file and load it as an h5 file instead # This significantly speeds up the reading of the data... if not xarray: self.data_ds.close() self.data_ds = h5py.File(data_fn, 'r') def __len__(self): return self.n_batches # TODO: Find a better way to implement this, currently it is the hardcoded way. def _transform_to_one_hot(self,Y): ''' return shape = batch_size X 64 X bin_size ''' Y_trans = [] out_vars = ['PHQ','TPHYSTND','FSNT', 'FSNS', 'FLNT', 'FLNS'] var_dict = {} var_dict['PHQ'] = Y[:,:30] var_dict['TPHYSTND'] = Y[:,30:60] var_dict['FSNT'] = Y[:,60] var_dict['FSNS'] = Y[:,61] var_dict['FLNT'] = Y[:,62] var_dict['FLNS'] = Y[:,63] perc = self.percentile_bins for var in out_vars[:2]: all_levels_one_hot = [] for ilev in range(30): bin_index = np.digitize(var_dict[var][:,ilev],perc[var][ilev]) one_hot = self.enc.transform(bin_index.reshape(-1,1)) all_levels_one_hot.append(one_hot) var_one_hot = np.stack(all_levels_one_hot,axis=1) Y_trans.append(var_one_hot) for var in out_vars[2:]: bin_index = np.digitize(var_dict[var][:], perc[var]) one_hot = self.enc.transform(bin_index.reshape(-1,1))[:,np.newaxis,:] Y_trans.append(one_hot) return np.concatenate(Y_trans,axis=1) def __getitem__(self, index): # Compute start and end indices for batch start_idx = index * self.batch_size end_idx = start_idx + self.batch_size # Grab batch from data batch = self.data_ds['vars'][start_idx:end_idx] # Split into inputs and outputs X = batch[:, self.input_idxs] Y = batch[:, self.output_idxs] # Normalize X = self.input_transform.transform(X) Y = self.output_transform.transform(Y) #shape batch_size X 64 Y = self._transform_to_one_hot(Y) return X, Y def on_epoch_end(self): self.indices = np.arange(self.n_batches) if self.shuffle: np.random.shuffle(self.indices) scale_dict = load_pickle('/export/nfs0home/ankitesg/CBrain_project/CBRAIN-CAM/nn_config/scale_dicts/009_Wm2_scaling.pkl') TRAINFILE = 'CI_SP_M4K_train_shuffle.nc' NORMFILE = 'CI_SP_M4K_NORM_norm.nc' data_path = '/scratch/ankitesh/data/' data_gen = DataGeneratorClassification( data_fn=f'{data_path}{TRAINFILE}', input_vars= ['QBP','TBP','PS', 'SOLIN', 'SHFLX', 'LHFLX'], output_vars=['PHQ','TPHYSTND','FSNT', 'FSNS', 'FLNT', 'FLNS'], percentile_path='/export/nfs0home/ankitesg/data/percentile_data.pkl', data_name = 'M4K', input_transform = ('mean', 'maxrs'), output_transform = scale_dict, norm_fn = f'{data_path}{NORMFILE}', batch_size=1024 ) data_gen[0][0].shape data_gen[0][1].shape ```
github_jupyter
``` import warnings warnings.filterwarnings('ignore') import pandas as pd from plotnine import * %ls test = pd.read_csv('shoppingmall_info_template.csv', encoding='cp949') test.shape test.head() test.columns test.head() test['Category'] = test['Name'].str.extract(r'^(스타필드|롯데몰)\s.*') test import folium geo_df = test map = folium.Map(location=[geo_df['Latitude'].mean(), geo_df['Longitude'].mean()], zoom_start=17, tiles='stamenwatercolor') for i, row in geo_df.iterrows(): mall_name = row['Name'] + '-' + row['Address'] if row['Category'] == '롯데몰': icon = folium.Icon(color='red',icon='info-sign') elif row['Category'] == '스타필드': icon = folium.Icon(color='blue',icon='info-sign') else: icon = folium.Icon(color='green',icon='info-sign') folium.Marker( [row['Latitude'], row['Longitude']], popup=mall_name, icon=icon ).add_to(map) # for n in geo_df.index: # mall_name = geo_df['Name'][n] \ # + '-' + geo_df['Address'][n] # folium.Marker([geo_df['latitude'][n], # geo_df['longitude'][n]], # popup=mall_name, # icon=folium.Icon(color='pink',icon='info-sign'), # ).add_to(map) # folium.Marker( # location=[37.545614, 127.224064], # popup = mall_name, # icon=folium.Icon(icon='cloud') # ).add_to(map) # folium.Marker( # location=[37.511683, 127.059108], # popup = mall_name, # icon=folium.Icon(icon='cloud') # ).add_to(map) map import folium geo_df = test map = folium.Map(location=[geo_df['Latitude'].mean(), geo_df['Longitude'].mean()], zoom_start=6, tiles='stamenwatercolor') for i, row in geo_df.iterrows(): mall_name = row['Name'] + '-' + row['Address'] if row['Category'] == '롯데몰': icon = folium.Icon(color='red',icon='info-sign') elif row['Category'] == '스타필드': icon = folium.Icon(color='blue',icon='info-sign') else: icon = folium.Icon(color='green',icon='info-sign') folium.Marker( [row['Latitude'], row['Longitude']], popup=mall_name, icon=icon ).add_to(map) map.choropleth( geo_data = test, name='choropleth', data = test, columns=['Traffic_no'], key_on='feature.id', fill_color='Set1', fill_opacity=0.7, line_opacity=0.2, ) folium.LayerControl().add_to(map) test['Traffic_no'] # 교통 가능 수 import plotly.plotly as py map = folium.Map( location=[geo_df['Latitude'].mean(), geo_df['Longitude'].mean()], zoom_start=6, tiles='stamenwatercolor') map.choropleth( geo_data = test, name='choropleth', data = test, columns=['Traffic_no'], key_on='feature.id', fill_color='Set1', fill_opacity=0.7, line_opacity=0.2, ) folium.LayerControl().add_to(map) ```
github_jupyter
# Developing an AI application Going forward, AI algorithms will be incorporated into more and more everyday applications. For example, you might want to include an image classifier in a smart phone app. To do this, you'd use a deep learning model trained on hundreds of thousands of images as part of the overall application architecture. A large part of software development in the future will be using these types of models as common parts of applications. In this project, you'll train an image classifier to recognize different species of flowers. You can imagine using something like this in a phone app that tells you the name of the flower your camera is looking at. In practice you'd train this classifier, then export it for use in your application. We'll be using [this dataset](http://www.robots.ox.ac.uk/~vgg/data/flowers/102/index.html) of 102 flower categories, you can see a few examples below. <img src='assets/Flowers.png' width=500px> The project is broken down into multiple steps: * Load and preprocess the image dataset * Train the image classifier on your dataset * Use the trained classifier to predict image content We'll lead you through each part which you'll implement in Python. When you've completed this project, you'll have an application that can be trained on any set of labeled images. Here your network will be learning about flowers and end up as a command line application. But, what you do with your new skills depends on your imagination and effort in building a dataset. For example, imagine an app where you take a picture of a car, it tells you what the make and model is, then looks up information about it. Go build your own dataset and make something new. First up is importing the packages you'll need. It's good practice to keep all the imports at the beginning of your code. As you work through this notebook and find you need to import a package, make sure to add the import up here. ``` # Imports here %matplotlib inline %config InlineBackend.figure_format = 'retina' import matplotlib.pyplot as plt import torch from torch import nn from torch import optim import torch.nn.functional as F from torchvision import datasets, transforms, models ``` ## Load the data Here you'll use `torchvision` to load the data ([documentation](http://pytorch.org/docs/0.3.0/torchvision/index.html)). The data should be included alongside this notebook, otherwise you can [download it here](https://s3.amazonaws.com/content.udacity-data.com/nd089/flower_data.tar.gz). The dataset is split into three parts, training, validation, and testing. For the training, you'll want to apply transformations such as random scaling, cropping, and flipping. This will help the network generalize leading to better performance. You'll also need to make sure the input data is resized to 224x224 pixels as required by the pre-trained networks. The validation and testing sets are used to measure the model's performance on data it hasn't seen yet. For this you don't want any scaling or rotation transformations, but you'll need to resize then crop the images to the appropriate size. The pre-trained networks you'll use were trained on the ImageNet dataset where each color channel was normalized separately. For all three sets you'll need to normalize the means and standard deviations of the images to what the network expects. For the means, it's `[0.485, 0.456, 0.406]` and for the standard deviations `[0.229, 0.224, 0.225]`, calculated from the ImageNet images. These values will shift each color channel to be centered at 0 and range from -1 to 1. ``` data_dir = '../flowers' train_dir = data_dir + '/train' valid_dir = data_dir + '/valid' test_dir = data_dir + '/test' means = [0.485, 0.456, 0.406] stdvs = [0.229, 0.224, 0.225] # TODO: Define your transforms for the training, validation, and testing sets train_transforms = transforms.Compose([transforms.RandomRotation(30), transforms.RandomResizedCrop(224), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize(means,stdvs)]) valid_transforms = transforms.Compose([transforms.Resize(255), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize(means,stdvs)]) test_transforms = transforms.Compose([transforms.Resize(255), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize(means,stdvs)]) # TODO: Load the datasets with ImageFolder train_data = datasets.ImageFolder(train_dir, transform=train_transforms) valid_data = datasets.ImageFolder(valid_dir, transform=valid_transforms) test_data = datasets.ImageFolder(test_dir, transform=test_transforms) # TODO: Using the image datasets and the trainforms, define the dataloaders trainloader = torch.utils.data.DataLoader(train_data, batch_size=64, shuffle=True) validloader = torch.utils.data.DataLoader(valid_data, batch_size=64) testloader = torch.utils.data.DataLoader(test_data, batch_size=64) ``` ### Label mapping You'll also need to load in a mapping from category label to category name. You can find this in the file `cat_to_name.json`. It's a JSON object which you can read in with the [`json` module](https://docs.python.org/2/library/json.html). This will give you a dictionary mapping the integer encoded categories to the actual names of the flowers. ``` import json with open('cat_to_name.json', 'r') as f: cat_to_name = json.load(f) categories = len(cat_to_name) ``` # Building and training the classifier Now that the data is ready, it's time to build and train the classifier. As usual, you should use one of the pretrained models from `torchvision.models` to get the image features. Build and train a new feed-forward classifier using those features. We're going to leave this part up to you. Refer to [the rubric](https://review.udacity.com/#!/rubrics/1663/view) for guidance on successfully completing this section. Things you'll need to do: * Load a [pre-trained network](http://pytorch.org/docs/master/torchvision/models.html) (If you need a starting point, the VGG networks work great and are straightforward to use) * Define a new, untrained feed-forward network as a classifier, using ReLU activations and dropout * Train the classifier layers using backpropagation using the pre-trained network to get the features * Track the loss and accuracy on the validation set to determine the best hyperparameters We've left a cell open for you below, but use as many as you need. Our advice is to break the problem up into smaller parts you can run separately. Check that each part is doing what you expect, then move on to the next. You'll likely find that as you work through each part, you'll need to go back and modify your previous code. This is totally normal! When training make sure you're updating only the weights of the feed-forward network. You should be able to get the validation accuracy above 70% if you build everything right. Make sure to try different hyperparameters (learning rate, units in the classifier, epochs, etc) to find the best model. Save those hyperparameters to use as default values in the next part of the project. One last important tip if you're using the workspace to run your code: To avoid having your workspace disconnect during the long-running tasks in this notebook, please read in the earlier page in this lesson called Intro to GPU Workspaces about Keeping Your Session Active. You'll want to include code from the workspace_utils.py module. **Note for Workspace users:** If your network is over 1 GB when saved as a checkpoint, there might be issues with saving backups in your workspace. Typically this happens with wide dense layers after the convolutional layers. If your saved checkpoint is larger than 1 GB (you can open a terminal and check with `ls -lh`), you should reduce the size of your hidden layers and train again. ``` # TODO: Build and train your network model = models.densenet161(pretrained=True) for param in model.parameters(): param.requires_grad = False from collections import OrderedDict classifier = nn.Sequential(OrderedDict([ ('fc1', nn.Linear(2208, 512)), ('relu1', nn.ReLU()), ('drop1', nn.Dropout(0.2)), ('fc2', nn.Linear(512, 256)), ('relu2', nn.ReLU()), ('drop2', nn.Dropout(0.2)), ('fc3', nn.Linear(256, categories)), ('output', nn.LogSoftmax(dim=1)) ])) model.classifier = classifier criterion = nn.NLLLoss() optimizer = optim.Adam(model.classifier.parameters(), lr=0.003) device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") model.to(device) epochs = 5 steps = 0 every_step = 50 running_loss, valid_loss = 0,0 for e in range(epochs): for images, labels in trainloader: images, labels = images.to(device), labels.to(device) optimizer.zero_grad() log_ps = model.forward(images) loss = criterion(log_ps, labels) loss.backward() running_loss += loss.item() optimizer.step() steps += 1 if steps % every_step == 0: valid_loss = 0 accuracy = 0 with torch.no_grad(): model.eval() for images, labels in validloader: images, labels = images.to(device), labels.to(device) log_ps = model.forward(images) ps = torch.exp(log_ps) valid_loss += criterion(log_ps, labels).item() top_p, top_class = ps.topk(1, dim=1) equals = top_class == labels.view(*top_class.shape) accuracy += torch.mean(equals.type(torch.FloatTensor)) print(f"Epoch {e + 1}/{epochs}.. " f"Train loss: {running_loss/every_step:.3f}.. " f"Test loss: {valid_loss/len(validloader):.3f}.. " f"Test accuracy: {accuracy/len(validloader):.3f}") running_loss = 0 model.train() ``` ## Testing your network It's good practice to test your trained network on test data, images the network has never seen either in training or validation. This will give you a good estimate for the model's performance on completely new images. Run the test images through the network and measure the accuracy, the same way you did validation. You should be able to reach around 70% accuracy on the test set if the model has been trained well. ``` # TODO: Do validation on the test set model.to(device) model.eval() accuracy = 0 with torch.no_grad(): for images, labels in testloader: images, labels = images.to(device), labels.to(device) log_ps = model.forward(images) ps = torch.exp(log_ps) top_p, top_class = ps.topk(1, dim=1) equals = top_class == labels.view(*top_class.shape) accuracy += torch.mean(equals.type(torch.FloatTensor)) model.train() print(f"Test accuracy: {accuracy/len(testloader):.3f}") ``` ## Save the checkpoint Now that your network is trained, save the model so you can load it later for making predictions. You probably want to save other things such as the mapping of classes to indices which you get from one of the image datasets: `image_datasets['train'].class_to_idx`. You can attach this to the model as an attribute which makes inference easier later on. ```model.class_to_idx = image_datasets['train'].class_to_idx``` Remember that you'll want to completely rebuild the model later so you can use it for inference. Make sure to include any information you need in the checkpoint. If you want to load the model and keep training, you'll want to save the number of epochs as well as the optimizer state, `optimizer.state_dict`. You'll likely want to use this trained model in the next part of the project, so best to save it now. ``` # TODO: Save the checkpoint model.class_to_idx = train_data.class_to_idx checkpoint = {'input_size': 2208, 'output_size': categories, 'state_dict': model.state_dict(), 'epochs': 5, 'optimizer_state': optimizer.state_dict(), 'class_to_idx': model.class_to_idx, 'hidden_layers':[512, 256]} torch.save(checkpoint, 'checkpoint.pth') ``` ## Loading the checkpoint At this point it's good to write a function that can load a checkpoint and rebuild the model. That way you can come back to this project and keep working on it without having to retrain the network. ``` # TODO: Write a function that loads a checkpoint and rebuilds the model def load_checkpoint(filepath): model = models.densenet161() checkpoint = torch.load(filepath) input = checkpoint['input_size'] hidden_layers = checkpoint['hidden_layers'] output = checkpoint['output_size'] classifier = nn.Sequential(OrderedDict([ ('fc1', nn.Linear(input, hidden_layers[0])), ('relu1', nn.ReLU()), ('drop1', nn.Dropout(0.2)), ('fc2', nn.Linear(hidden_layers[0], hidden_layers[1])), ('relu2', nn.ReLU()), ('drop2', nn.Dropout(0.2)), ('fc3', nn.Linear(hidden_layers[1], output)), ('output', nn.LogSoftmax(dim=1)) ])) model.classifier = classifier model.load_state_dict(checkpoint['state_dict']) model.class_to_idx = checkpoint['class_to_idx'] optimizer = optim.Adam(model.classifier.parameters(), lr=0.003) optimizer.load_state_dict(checkpoint['optimizer_state']) return model model = load_checkpoint('checkpoint.pth') ``` # Inference for classification Now you'll write a function to use a trained network for inference. That is, you'll pass an image into the network and predict the class of the flower in the image. Write a function called `predict` that takes an image and a model, then returns the top $K$ most likely classes along with the probabilities. It should look like ```python probs, classes = predict(image_path, model) print(probs) print(classes) > [ 0.01558163 0.01541934 0.01452626 0.01443549 0.01407339] > ['70', '3', '45', '62', '55'] ``` First you'll need to handle processing the input image such that it can be used in your network. ## Image Preprocessing You'll want to use `PIL` to load the image ([documentation](https://pillow.readthedocs.io/en/latest/reference/Image.html)). It's best to write a function that preprocesses the image so it can be used as input for the model. This function should process the images in the same manner used for training. First, resize the images where the shortest side is 256 pixels, keeping the aspect ratio. This can be done with the [`thumbnail`](http://pillow.readthedocs.io/en/3.1.x/reference/Image.html#PIL.Image.Image.thumbnail) or [`resize`](http://pillow.readthedocs.io/en/3.1.x/reference/Image.html#PIL.Image.Image.thumbnail) methods. Then you'll need to crop out the center 224x224 portion of the image. Color channels of images are typically encoded as integers 0-255, but the model expected floats 0-1. You'll need to convert the values. It's easiest with a Numpy array, which you can get from a PIL image like so `np_image = np.array(pil_image)`. As before, the network expects the images to be normalized in a specific way. For the means, it's `[0.485, 0.456, 0.406]` and for the standard deviations `[0.229, 0.224, 0.225]`. You'll want to subtract the means from each color channel, then divide by the standard deviation. And finally, PyTorch expects the color channel to be the first dimension but it's the third dimension in the PIL image and Numpy array. You can reorder dimensions using [`ndarray.transpose`](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.ndarray.transpose.html). The color channel needs to be first and retain the order of the other two dimensions. ``` from PIL import Image import numpy as np def process_image(image): ''' Scales, crops, and normalizes a PIL image for a PyTorch model, returns an Numpy array ''' # TODO: Process a PIL image for use in a PyTorch model size = (256,256) image = image.resize(size) image = image.crop((16,16,16 + 224,16 + 224)) np_image = np.array(image).astype('float64')/255 np_image -= means np_image /= stdvs np_image = np_image.transpose((2,1,0)) return np_image im = Image.open(test_dir + '/10/image_07090.jpg') imshow(process_image(im)); ``` To check your work, the function below converts a PyTorch tensor and displays it in the notebook. If your `process_image` function works, running the output through this function should return the original image (except for the cropped out portions). ``` def imshow(image, ax=None, title=None): """Imshow for Tensor.""" if ax is None: fig, ax = plt.subplots() # PyTorch tensors assume the color channel is the first dimension # but matplotlib assumes is the third dimension image = image.transpose((1, 2, 0)) # Undo preprocessing mean = np.array([0.485, 0.456, 0.406]) std = np.array([0.229, 0.224, 0.225]) image = std * image + mean # Image needs to be clipped between 0 and 1 or it looks like noise when displayed image = np.clip(image, 0, 1) ax.imshow(image) return ax ``` ## Class Prediction Once you can get images in the correct format, it's time to write a function for making predictions with your model. A common practice is to predict the top 5 or so (usually called top-$K$) most probable classes. You'll want to calculate the class probabilities then find the $K$ largest values. To get the top $K$ largest values in a tensor use [`x.topk(k)`](http://pytorch.org/docs/master/torch.html#torch.topk). This method returns both the highest `k` probabilities and the indices of those probabilities corresponding to the classes. You need to convert from these indices to the actual class labels using `class_to_idx` which hopefully you added to the model or from an `ImageFolder` you used to load the data ([see here](#Save-the-checkpoint)). Make sure to invert the dictionary so you get a mapping from index to class as well. Again, this method should take a path to an image and a model checkpoint, then return the probabilities and classes. ```python probs, classes = predict(image_path, model) print(probs) print(classes) > [ 0.01558163 0.01541934 0.01452626 0.01443549 0.01407339] > ['70', '3', '45', '62', '55'] ``` ``` def predict(image_path, model, topk=5): ''' Predict the class (or classes) of an image using a trained deep learning model. ''' model.eval() model.to(device) class_id = model.class_to_idx # TODO: Implement the code to predict the class from an image file image = Image.open(image_path) image = process_image(image) image = torch.from_numpy(image) image = image.float().cuda() image.to(device) with torch.no_grad(): probs, classes = torch.exp(model(image.unsqueeze_(0))).topk(topk, dim = 1) probs = probs.cpu().numpy()[0,:] classes = classes.cpu().numpy()[0,:] classes = [key for key in class_id.__iter__() if class_id[key] in classes] return probs, classes probs, classes = predict(test_dir + '/10/image_07090.jpg', model) print(probs) print(classes) ``` ## Sanity Checking Now that you can use a trained model for predictions, check to make sure it makes sense. Even if the testing accuracy is high, it's always good to check that there aren't obvious bugs. Use `matplotlib` to plot the probabilities for the top 5 classes as a bar graph, along with the input image. It should look like this: <img src='assets/inference_example.png' width=300px> You can convert from the class integer encoding to actual flower names with the `cat_to_name.json` file (should have been loaded earlier in the notebook). To show a PyTorch tensor as an image, use the `imshow` function defined above. ``` # TODO: Display an image along with the top 5 classes imshow(process_image(Image.open(test_dir + '/10/image_07090.jpg')), title = cat_to_name['10']); fig, ax1 = plt.subplots(figsize=(6,9)) ax1.barh(np.arange(5), probs) ax1.set_aspect(0.1) ax1.set_yticks(np.arange(5)) ax1.set_yticklabels([cat_to_name[i] for i in classes]) ```
github_jupyter
<h3>Implementation Of Doubly Linked List in Python</h3> <p> It is similar to Single Linked List but the only Difference lies that it where in Single Linked List we had a link to the next data element ,In Doubly Linked List we also have the link to previous data element with addition to next link</p> <ul> <b>It has three parts</b> <li> Data Part :This stores the data element of the Node and also consists the reference of the address of the next and previous element </li> <li>Next :This stores the address of the next pointer via links</li> <li>Previous :This stores the address of the previous element/ pointer via links </li> </ul> ``` from IPython.display import Image Image(filename='C:/Users/prakhar/Desktop/Python_Data_Structures_and_Algorithms_Implementations/Images/DoublyLinkedList.png',width=800, height=400) #save the images from github to your local machine and then give the absolute path of the image class Node: # All the operation are similar to Single Linked List with just an addition of Previous which points towards the Prev address via links def __init__(self, data=None, next=None, prev=None): self.data = data self.next = next self.prev = prev class Double_LL(): def __init__(self): self.head = None def print_forward(self): if self.head is None: print("Linked List is empty") return itr = self.head llstr = '' while itr: llstr += str(itr.data) + ' --> ' itr = itr.next print(llstr) def print_backward(self): if self.head is None: print("Linked list is empty") return last_node = self.get_last_node() itr = last_node llstr = '' while itr: llstr += itr.data + '-->' itr = itr.prev print("Link list in reverse: ", llstr) def get_last_node(self): itr = self.head while itr.next: itr = itr.next return itr def get_length(self): count = 0 itr = self.head while itr: count += 1 itr = itr.next return count def insert_at_begining(self, data): if self.head == None: node = Node(data, self.head, None) self.head = node else: node = Node(data, self.head, None) self.head.prev = node self.head = node def insert_at_end(self, data): if self.head is None: self.head = Node(data, None, None) return itr = self.head while itr.next: itr = itr.next itr.next = Node(data, None, itr) def insert_at(self, index, data): if index < 0 or index > self.get_length(): raise Exception("Invalid Index") if index == 0: self.insert_at_begining(data) return count = 0 itr = self.head while itr: if count == index - 1: node = Node(data, itr.next, itr) if node.next: node.next.prev = node itr.next = node break itr = itr.next count += 1 def remove_at(self, index): if index < 0 or index >= self.get_length(): raise Exception("Invalid Index") if index == 0: self.head = self.head.next self.head.prev = None return count = 0 itr = self.head while itr: if count == index: itr.prev.next = itr.next if itr.next: itr.next.prev = itr.prev break itr = itr.next count += 1 def insert_values(self, data_list): self.head = None for data in data_list: self.insert_at_end(data) from IPython.display import Image Image(filename='C:/Users/prakhar/Desktop/Python_Data_Structures_and_Algorithms_Implementations/Images/DLL_insertion_at_beginning.png',width=800, height=400) #save the images from github to your local machine and then give the absolute path of the image ``` <p> Insertion at Beginning</p> ``` from IPython.display import Image Image(filename='C:/Users/prakhar/Desktop/Python_Data_Structures_and_Algorithms_Implementations/Images/DLL_insertion.png',width=800, height=400) #save the images from github to your local machine and then give the absolute path of the image ``` <p>Inserting Node at Index</p> ``` if __name__ == '__main__': ll = Double_LL() ll.insert_values(["banana", "mango", "grapes", "orange"]) ll.print_forward() ll.print_backward() ll.insert_at_end("figs") ll.print_forward() ll.insert_at(0, "jackfruit") ll.print_forward() ll.insert_at(6, "dates") ll.print_forward() ll.insert_at(2, "kiwi") ll.print_forward() ```
github_jupyter
``` #import libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns sns.set(font_scale = 1.2, style = 'darkgrid') %matplotlib inline import warnings warnings.filterwarnings("ignore") #change display into using full screen from IPython.core.display import display, HTML display(HTML("<style>.container { width:100% !important; }</style>")) #import .csv file data = pd.read_csv('FB_data_platform.csv') ``` # 1. Data Exploration & Cleaning ### 1. Have a first look at data ``` data.head() #Consider only those records where amount spent > 0 data = data[(data['Amount spent (INR)'] > 0)] data.shape ``` ### 2. Drop Columns that are extra ``` #We see that Reporting Starts and Reporting Ends are additional columns which we don't require. So we drop them data.drop(['Reporting ends','Reporting starts'],axis = 1, inplace = True) #look at the data again data.head() #check rows and columns in data data.shape ``` #### So, there are 62 rows and 14 columns in the data ### 3. Deal with Null Values ``` #let's look if any column has null values data.isnull().sum() ``` #### From this we can infer that some columns have Null values (basically blank). Let's look at them: **1. Results & Result Type:** This happened when there was no conversion (Result). **2. Result rate, Cost per result:** As both these metrics depend on Result, so these are also blank. This was bound to happen because not every single day and every ad got a result (conversion). **So it is safe to replace all nulls in Results and Result rate column with 0.** ``` #Fill all blanks in Results with 0 data['Results'] = data['Results'].fillna(0) data['Result rate'] = data['Result rate'].fillna(0) #check how many nulls are still there data.isnull().sum() ``` #### Voila! Results & Result rate column has no nulls now. Let's see what column Results Type is all about. ``` data['Result Type'].value_counts() ``` So we infer that 'Result Type' is basically the type of conversion event taking place. It can be either Page Like, Post Like, On-Facebook Lead, Custom Conversion etc. **Since, we are analysing just one campaign here, we can drop this column as it has same meaning throughout data set.** If we were analysing multiple campaigns, with different objectives, then keeping this column would have made sense. ``` #Drop Result Type column from data data.drop(['Result Type'],axis = 1, inplace = True) #check how many nulls are still there data.isnull().sum() ``` Now we need to deal with **Cost per result**. The cases where CPA is Null means that there was no conversion. So ideally, in these cases the CPA should be very high (in case a conversion actually happened). #### So, let's leave this column as it is because we can't assign any value for records where no conversion happened. ``` data.info() ``` # 2. Feature Engineering ### 1. We can divide Frequency in buckets ``` data['Frequency'] = data['Frequency'].apply(lambda x:'1 to 2' if x<2 else '2 to 3' if x>=2 and x<3 else '3 to 4' if x>=3 and x<4 else '4 to 5' if x>=4 and x<5 else 'More than 5') data.head() ``` ### 2. Split Ad name into Ad Format and Ad Headline ``` data['Ad_name'] = data['Ad name'] data.head() data[['Ad Format','Ad Headline']] = data.Ad_name.str.split("-", expand = True) data.head() data.drop(['Ad name','Ad_name'],axis = 1, inplace = True) data.head() data.info(verbose = 1) data.to_csv('Clean_Data_Platform.csv') ``` ## Now our data is clean. Here are our features that we will use for analysis - **1. Campaign Name** - Name of campaign - **2. Ad Set Name** - Targeting - **3. Platform** - Facebook / Instagram - **4. Results** - How many conversions were achieved - **5. Amount spent** - How much money was spent on ad campaign - **6. Frequency** - On an average how many times did one user see the ad - **7. Result Rate** - Conversion Rate - **8. CTR** - Click Through Rate - **9. CPM** - Cost per 1000 impressions - **10. Cost per result** - Average Cost required for 1 conversion - **11. Ad Format** - Whether the ad crative is **Image/Video/Carousel** - **12. Ad Headline** - The headline used in ad So, our target variable here is **Results** and we will analyse the effect of other variable on our target variable. # 3. Relationship Visualization ### 1. Effect of Platform + Ad Format ``` # increase figure size plt.figure(figsize = (20, 5)) # subplot 1 plt.subplot(1, 6, 1) sns.barplot(x = 'Platform', y = 'Amount spent (INR)', data = data, hue = 'Ad Format', estimator = np.sum, ci = None) plt.title("Total Amount Spent") plt.xticks(rotation = 90) # subplot 2 plt.subplot(1, 6, 2) sns.barplot(x = 'Platform', y = 'Clicks (all)', data = data, hue = 'Ad Format', estimator = np.sum, ci = None) plt.title("Total Clicks") plt.xticks(rotation = 90) # subplot 3 plt.subplot(1, 6, 3) sns.barplot(x = 'Platform', y = 'CTR (all)', data = data, hue = 'Ad Format', estimator = np.sum, ci = None) plt.title("CTR") plt.xticks(rotation = 90) # subplot 4 plt.subplot(1, 6, 4) sns.barplot(x = 'Platform', y = 'Results', data = data, hue = 'Ad Format', estimator = np.sum, ci = None) plt.title("Total Conversions") plt.xticks(rotation = 90) # subplot 5 plt.subplot(1, 6, 5) sns.barplot(x = 'Platform', y = 'Cost per result', data = data, hue = 'Ad Format', estimator = np.sum, ci = None) plt.title("Avg. Cost per Conversion") plt.xticks(rotation = 90) # subplot 6 plt.subplot(1,6, 6) sns.barplot(x = 'Platform', y = 'Result rate', data = data, hue = 'Ad Format', estimator = np.sum, ci = None) plt.title("CVR") plt.xticks(rotation = 90) plt.tight_layout(pad = 0.7) plt.show() ``` ### 2. Effect of Platform + Frequency ``` data = data.sort_values(by = ['Frequency']) # increase figure size plt.figure(figsize = (25, 6)) # subplot 1 plt.subplot(1, 6, 1) sns.barplot(hue = 'Platform', y = 'Amount spent (INR)', data = data, x = 'Frequency', estimator = np.sum, ci = None) plt.title("Total Amount Spent") plt.xticks(rotation = 90) # subplot 2 plt.subplot(1, 6, 2) sns.barplot(hue = 'Platform', y = 'Clicks (all)', data = data, x = 'Frequency', estimator = np.sum, ci = None) plt.title("Total Clicks") plt.xticks(rotation = 90) # subplot 3 plt.subplot(1, 6, 3) sns.barplot(hue = 'Platform', y = 'CTR (all)', data = data, x = 'Frequency', estimator = np.sum, ci = None) plt.title("CTR") plt.xticks(rotation = 90) # subplot 4 plt.subplot(1, 6, 4) sns.barplot(hue = 'Platform', y = 'Results', data = data, x = 'Frequency', estimator = np.sum, ci = None) plt.title("Total Conversions") plt.xticks(rotation = 90) # subplot 5 plt.subplot(1, 6, 5) sns.barplot(hue = 'Platform', y = 'Cost per result', data = data, x = 'Frequency', estimator = np.sum, ci = None) plt.title("Avg. Cost per Conversion") plt.xticks(rotation = 90) # subplot 6 plt.subplot(1, 6, 6) sns.barplot(hue = 'Platform', y = 'Result rate', data = data, x = 'Frequency', estimator = np.sum, ci = None) plt.title("CVR") plt.xticks(rotation = 90) plt.tight_layout(pad = 0.7) plt.show() ```
github_jupyter
# Along isopycnal spice gradients Here we consider the properties of spice gradients along isopycnals. We do this using the 2 point differences and their distributions. This is similar (generalization) to the spice gradients that Klymak et al 2015 considered. ``` import numpy as np import xarray as xr import glidertools as gt from cmocean import cm as cmo import gsw import matplotlib.pyplot as plt plt.style.use('seaborn-colorblind') plt.rcParams['font.size'] = 16 ds_659_rho = xr.open_dataset('data/sg_O2_659_isopycnal_grid_4m_27_sept_2021.nc') ds_660_rho = xr.open_dataset('data/sg_O2_660_isopycnal_grid_4m_27_sept_2021.nc') # compute spice # Pick constant alpha and beta for convenience (can always update later) alpha_659 = gsw.alpha(ds_659_rho.SA, ds_659_rho.CT, ds_659_rho.ctd_pressure) alpha_660 = gsw.alpha(ds_660_rho.SA, ds_660_rho.CT, ds_660_rho.ctd_pressure) #alpha = 8.3012133e-05 #beta = 0.00077351 # dCT_659 = ds_659_rho.CT - ds_659_rho.CT.mean('dives') dSA_659 = ds_659_rho.SA - ds_659_rho.SA.mean('dives') ds_659_rho['Spice'] = (2*alpha_659*dCT_659).rename('Spice') # remove a mean per isopycnal dCT_660 = ds_660_rho.CT - ds_660_rho.CT.mean('dives') dSA_660 = ds_660_rho.SA - ds_660_rho.SA.mean('dives') ds_660_rho['Spice'] = (2*alpha_660*dCT_660).rename('Spice') plt.figure(figsize=(12,6)) plt.subplot(211) ds_660_rho.Spice.sel(rho_grid=27.2, method='nearest').plot(label='27.2') ds_660_rho.Spice.sel(rho_grid=27.4, method='nearest').plot(label='27.4') ds_660_rho.Spice.sel(rho_grid=27.6, method='nearest').plot(label='27.6') plt.legend() plt.title('660') plt.subplot(212) ds_659_rho.Spice.sel(rho_grid=27.2, method='nearest').plot(label='27.2') ds_659_rho.Spice.sel(rho_grid=27.4, method='nearest').plot(label='27.4') ds_659_rho.Spice.sel(rho_grid=27.6, method='nearest').plot(label='27.6') plt.legend() plt.title('659') plt.tight_layout() ``` ### Analysis at a couple of single depths ``` #def great_circle_distance(lon1, lat1, lon2, lat2): def great_circle_distance(X1, X2): """Calculate the great circle distance between one or multiple pairs of points given in spherical coordinates. Spherical coordinates are expected in degrees. Angle definition follows standard longitude/latitude definition. This uses the arctan version of the great-circle distance function (en.wikipedia.org/wiki/Great-circle_distance) for increased numerical stability. Parameters ---------- lon1: float scalar or numpy array Longitude coordinate(s) of the first element(s) of the point pair(s), given in degrees. lat1: float scalar or numpy array Latitude coordinate(s) of the first element(s) of the point pair(s), given in degrees. lon2: float scalar or numpy array Longitude coordinate(s) of the second element(s) of the point pair(s), given in degrees. lat2: float scalar or numpy array Latitude coordinate(s) of the second element(s) of the point pair(s), given in degrees. Calculation of distances follows numpy elementwise semantics, so if an array of length N is passed, all input parameters need to be arrays of length N or scalars. Returns ------- distance: float scalar or numpy array The great circle distance(s) (in degrees) between the given pair(s) of points. """ # Change form of input to make compliant with pdist lon1 = X1[0] lat1 = X1[1] lon2 = X2[0] lat2 = X2[1] # Convert to radians: lat1 = np.array(lat1) * np.pi / 180.0 lat2 = np.array(lat2) * np.pi / 180.0 dlon = (lon1 - lon2) * np.pi / 180.0 # Evaluate trigonometric functions that need to be evaluated more # than once: c1 = np.cos(lat1) s1 = np.sin(lat1) c2 = np.cos(lat2) s2 = np.sin(lat2) cd = np.cos(dlon) # This uses the arctan version of the great-circle distance function # from en.wikipedia.org/wiki/Great-circle_distance for increased # numerical stability. # Formula can be obtained from [2] combining eqns. (14)-(16) # for spherical geometry (f=0). return ( 180.0 / np.pi * np.arctan2( np.sqrt((c2 * np.sin(dlon)) ** 2 + (c1 * s2 - s1 * c2 * cd) ** 2), s1 * s2 + c1 * c2 * cd, ) ) from scipy.spatial.distance import pdist ``` #### 27.4 ``` spatial_bins=np.logspace(2,6,17) def select_data(rho_sel): # function to find the dX and dSpice from the different data sets and merging them ds_sel = ds_660_rho.sel(rho_grid=rho_sel, method='nearest') lon_sel = ds_sel.longitude.values.reshape((-1,1)) lat_sel = ds_sel.latitude.values.reshape((-1,1)) time_sel = ds_sel.days.values.reshape((-1,1)) Spice_sel = ds_sel.Spice.values.reshape((-1,1)) Xvec = np.concatenate([lon_sel, lat_sel], axis=1) # mXn, where m is number of obs and n is dimension dX_660 = pdist(Xvec, great_circle_distance)*110e3 # convert to m dTime_660 = pdist(time_sel, 'cityblock') dSpice_660 = pdist(Spice_sel, 'cityblock') # we just want to know the abs diff ds_sel = ds_659_rho.sel(rho_grid=rho_sel, method='nearest') lon_sel = ds_sel.longitude.values.reshape((-1,1)) lat_sel = ds_sel.latitude.values.reshape((-1,1)) time_sel = ds_sel.days.values.reshape((-1,1)) Spice_sel = ds_sel.Spice.values.reshape((-1,1)) Xvec = np.concatenate([lon_sel, lat_sel], axis=1) # mXn, where m is number of obs and n is dimension dX_659 = pdist(Xvec, great_circle_distance)*110e3 # convert to m dTime_659 = pdist(time_sel, 'cityblock') dSpice_659 = pdist(Spice_sel, 'cityblock') # we just want to know the abs diff # combine data dX = np.concatenate([dX_659, dX_660]) dTime = np.concatenate([dTime_659, dTime_660]) dSpice = np.concatenate([dSpice_659, dSpice_660]) # condition cond = (dTime <= 2e-3*dX**(2/3)) return dX[cond], dSpice[cond] rho_sel = 27.25 dX_sel, dSpice_sel = select_data(rho_sel) # estimate pdfs Hspice, xedges, yedges = np.histogram2d(dX_sel, dSpice_sel/dX_sel, bins=(spatial_bins, np.logspace(-14, -6, 37))) xmid = 0.5*(xedges[0:-1] + xedges[1:]) ymid = 0.5*(yedges[0:-1] + yedges[1:]) #dX_edges = xedges[1:] - xedges[0:-1] #dY_edges = yedges[1:] - yedges[0:-1] Hspice_Xdnorm = Hspice/ Hspice.sum(axis=1).reshape((-1,1)) mean_dist = np.zeros((len(xmid,))) for i in range(len(xmid)): mean_dist[i] = np.sum(Hspice_Xdnorm[i, :]*ymid) plt.figure(figsize=(7,5)) plt.pcolor(xedges, yedges, Hspice_Xdnorm.T, norm=colors.LogNorm(vmin=1e-3, vmax=0.3), cmap=cmo.amp) plt.plot(xmid, mean_dist , linewidth=2., color='cyan', label='Mean') plt.plot(xmid, 1e-6*xmid**-.6, '--',linewidth=2, color='gray', label='L$^{-0.6}$') plt.colorbar(label='PDF') plt.xscale('log') plt.yscale('log') plt.xlabel('L [m]') plt.ylabel(r'$|dSpice/dx|$ [kg m$^{-4}$]') plt.legend(loc='lower left') plt.ylim([1e-13, 1e-6]) plt.xlim([1e2, 1e5]) plt.grid() plt.title('$\sigma$='+str(rho_sel)+'kg m$^{-3}$') plt.tight_layout() plt.savefig('./figures/figures_spice_gradients_panel1.pdf') ``` ### Compute the structure functions at many depths ### Structure functions Here we consider the structure functions; quantities like $<d\tau ^n>$. Power law scalings go as, at $k^{-\alpha}$ in power spectrum will appear at $r^{\alpha-1}$ in spectra. So a power law scaling of 2/3 corresponds to $-5/3$, while shallower than 2/3 would correspond to shallower. ``` rho_sels = ds_660_rho.rho_grid[0:-1:10] rho_sels # estimate the structure functions # We will do the distribution calculations at a few depths spatial_bins=np.logspace(2,6,17) S2 = np.zeros((len(rho_sels),len(spatial_bins)-1)) S4 = np.zeros((len(rho_sels),len(spatial_bins)-1)) for count, rho_sel in enumerate(rho_sels): print(count) dX_cond, dSpice_cond = select_data(rho_sel) # compute the structure functions for i in range(len(spatial_bins)-1): S2[count, i] = np.nanmean(dSpice_cond[ (dX_cond> spatial_bins[i]) & (dX_cond <= spatial_bins[i+1])]**2) S4[count, i] = np.nanmean(dSpice_cond[ (dX_cond> spatial_bins[i]) & (dX_cond <= spatial_bins[i+1])]**4) ``` Unlike the surface buoyancy gradients, there is less of a suggestion of saturation at the small scales. Suggesting that even if the is a natural limit to the smallest gradients (wave mixing or such), it is not reached at a few 100m. This result seems to be similar, regardless of the isopycnal we are considering (tried this by changing the density level manually). Things to try: - Second order structure functions (do they look more like k^-1 or k^-2?) - 4th order structure functions could also help as a summary metric ``` import matplotlib.colors as colors from matplotlib import ticker np.linspace(-4.5,0, 19) np.linspace(-11,-8, 22) plt.figure(figsize=(10, 7)) lev_exp = np.linspace(-11,-8, 22) levs = np.power(10, lev_exp) cnt = plt.contourf(xmid, rho_sels, S2, levels=levs, norm = colors.LogNorm(3e-11), extend='both', cmap=cmo.tempo_r) for c in cnt.collections: c.set_edgecolor("face") plt.xscale('log') plt.colorbar(ticks=[1e-11, 1e-10, 1e-9, 1e-8], label=r'$\left< \delta \tau ^2\right> $ [kg$^2$ m$^{-6}$]') plt.ylim([27.65, 27.15]) plt.xlim([3e2, 1e5]) plt.ylabel(r'$\rho$ [kg m$^{-3}$]') plt.xlabel('L [m]') plt.tight_layout() plt.savefig('figures/figure_iso_spec_freq_panel4.pdf') spatial_bins_mid = 0.5*(spatial_bins[0:-1] + spatial_bins[1:]) np.any(np.isnan(y)) # Fit slope npres = len(rho_sels) m_mean = np.zeros((npres,)) x = spatial_bins_mid[(spatial_bins_mid>=1e3) & (spatial_bins_mid<=40e3)] for i in range(npres): y = S2[i, (spatial_bins_mid>=1e3) & (spatial_bins_mid<=40e3)] if ~np.any(np.isnan(y)): m_mean[i],b = np.polyfit(np.log(x), np.log(y),1) else: m_mean[i] = np.nan np.mean(m_mean[20:60]) plt.figure(figsize=(3,7)) plt.plot(m_mean, rho_sels, color='k', linewidth=2) plt.vlines([0,2/3,1], 27.15, 27.65, linestyles='--') plt.gca().invert_yaxis() plt.ylim([27.65, 27.15]) plt.xlim([-.1,1.1]) plt.xlabel('Slope') plt.ylabel(r'$\rho$ [kg m$^{-3}$]') plt.tight_layout() plt.savefig('figures/figure_iso_spec_freq_panel5.pdf') np.linspace(2, 20, 19) plt.figure(figsize=(10, 7)) cnt = plt.contourf(xmid, rho_sels, S4/ S2**2, levels=np.linspace(2, 20, 19), extend='both', cmap=cmo.turbid_r) for c in cnt.collections: c.set_edgecolor("face") plt.xscale('log') plt.colorbar(ticks=[3, 6, 9, 12,15, 18], label=r'$\left< \delta \tau ^4 \right> / \left< \delta \tau ^2\right>^2 $ ') plt.ylim([27.65, 27.15]) plt.xlim([3e2, 1e5]) plt.ylabel(r'$\rho$ [kg m$^{-3}$]') plt.xlabel('L [m]') plt.tight_layout() plt.savefig('figures/figure_iso_spec_freq_panel6.pdf') #plt.gca().invert_yaxis() ``` The second order structure of spice follow as power law of about 2/3, which corresponds to about -5/3 slope of tracers. This is slightly at odds with the $k^{-2}$. scaling seen in wavenumber. However, note that this is still very far from $r^0$ (constant) that one might expect is the $k^{-1}$ case (which is what theory would predict).
github_jupyter
<a href="https://colab.research.google.com/github/penningjoy/MachineLearningwithsklearn/blob/main/Part_2__FeatureEngineering.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ### Feature Selection Feature Selection is a very important part of Feature Engineering process. You don't want features that are not relevant and unrelated to your target and thus do not have to participate in the Machine Learning process. Reasons behind performing feature selection -- * Reduction in Training time because you have less garbage * Reduced Dimension * More General and easier model * Better Interpretability #### Removing features with low variance It involves removing features which has only one value and other instances share the same value on this feature. There is no variance in its instances. Therefore it will not contribute anything to the prediction. And thus it's best to remove them. ``` import sklearn.feature_selection as fs import numpy as np X = np.array([[0, 0, 1], [0, 1, 0], [1, 0, 0], [0, 1, 1], [0, 1, 0], [0, 1, 1]]) ''' VarianceThreshold function removes features with low variance based on a threshold. Threshold is the variance threshold. ''' variance = fs.VarianceThreshold(threshold = 0.2) variance.fit(X) X_transformed = variance.transform(X) print(" Original Data ") print(" ------------- ") print(X) print(" ") print(" Label Encoded Data ") print(" -------------- ") print(X_transformed) ``` #### Select K-Best Features ``` import sklearn.datasets as datasets X, Y = datasets.make_classification(n_samples=300, n_features=10, n_informative=4) # Choosing the f_classif as the metric and K is 3 kbest = fs.SelectKBest( fs.f_classif, 3) kbest.fit(X,Y) X_transformed = kbest.transform(X) print(" Original Data ") print(" ------------- ") print(X) print(" ") print(" Label Encoded Data ") print(" -------------- ") print(X_transformed) ``` #### Feature Selection by other model ``` import sklearn.feature_selection as fs import sklearn.datasets as datasets from sklearn.model_selection import train_test_split from sklearn.ensemble import GradientBoostingClassifier import sklearn.metrics as metrics X, Y = datasets.make_classification(n_samples=500, n_features=20, n_informative=6,random_state=21) gbclassifier = GradientBoostingClassifier(n_estimators=20) gbclassifier.fit(X,Y) print("Feature Selection using GBDT") print(gbclassifier.feature_importances_) gbdtmodel = fs.SelectFromModel(gbclassifier, prefit= True) # The features with very low importance will be removed X_transformed = gbdtmodel.transform(X) print(" Original Data Shape ") print(" ------------- ") print(X.shape) print(" ") print(" Transformed Data Shape after Feature Selection ") print(" -------------- ") print(X_transformed.shape) ``` ### Feature Extraction ``` ``` from sklearn.feature_extraction.text import CountVectorizer corpus = [ "I have an apple.", "The apple is red", "I like the apple", "I like the orange", "Apple and orange are fruit", "The orange is yellow" ] counterVec = CountVectorizer() counterVec.fit(corpus) print("Get all the feature names of this corpus") print(counterVec.get_feature_names()) print("The number of feature is {}".format(len( counterVec.get_feature_names()))) corpus_data = counterVec.transform(corpus) print("The transform data's shape is {}".format(corpus_data.toarray().shape)) print(corpus_data.toarray())
github_jupyter
# CarND Object Detection Lab Let's get started! ``` import tensorflow as tf import numpy as np import matplotlib.pyplot as plt from PIL import Image from PIL import ImageDraw from PIL import ImageColor import time from scipy.stats import norm %matplotlib inline plt.style.use('ggplot') ``` ## MobileNets [*MobileNets*](https://arxiv.org/abs/1704.04861), as the name suggests, are neural networks constructed for the purpose of running very efficiently (high FPS, low memory footprint) on mobile and embedded devices. *MobileNets* achieve this with 3 techniques: 1. Perform a depthwise convolution followed by a 1x1 convolution rather than a standard convolution. The 1x1 convolution is called a pointwise convolution if it's following a depthwise convolution. The combination of a depthwise convolution followed by a pointwise convolution is sometimes called a separable depthwise convolution. 2. Use a "width multiplier" - reduces the size of the input/output channels, set to a value between 0 and 1. 3. Use a "resolution multiplier" - reduces the size of the original input, set to a value between 0 and 1. These 3 techniques reduce the size of cummulative parameters and therefore the computation required. Of course, generally models with more paramters achieve a higher accuracy. *MobileNets* are no silver bullet, while they perform very well larger models will outperform them. ** *MobileNets* are designed for mobile devices, NOT cloud GPUs**. The reason we're using them in this lab is automotive hardware is closer to mobile or embedded devices than beefy cloud GPUs. ### Convolutions #### Vanilla Convolution Before we get into the *MobileNet* convolution block let's take a step back and recall the computational cost of a vanilla convolution. There are $N$ kernels of size $D_k * D_k$. Each of these kernels goes over the entire input which is a $D_f * D_f * M$ sized feature map or tensor (if that makes more sense). The computational cost is: $$ D_g * D_g * M * N * D_k * D_k $$ Let $D_g * D_g$ be the size of the output feature map. Then a standard convolution takes in a $D_f * D_f * M$ input feature map and returns a $D_g * D_g * N$ feature map as output. (*Note*: In the MobileNets paper, you may notice the above equation for computational cost uses $D_f$ instead of $D_g$. In the paper, they assume the output and input are the same spatial dimensions due to stride of 1 and padding, so doing so does not make a difference, but this would want $D_g$ for different dimensions of input and output.) ![Standard Convolution](assets/standard_conv.png) #### Depthwise Convolution A depthwise convolution acts on each input channel separately with a different kernel. $M$ input channels implies there are $M$ $D_k * D_k$ kernels. Also notice this results in $N$ being set to 1. If this doesn't make sense, think about the shape a kernel would have to be to act upon an individual channel. Computation cost: $$ D_g * D_g * M * D_k * D_k $$ ![Depthwise Convolution](assets/depthwise_conv.png) #### Pointwise Convolution A pointwise convolution performs a 1x1 convolution, it's the same as a vanilla convolution except the kernel size is $1 * 1$. Computation cost: $$ D_k * D_k * D_g * D_g * M * N = 1 * 1 * D_g * D_g * M * N = D_g * D_g * M * N $$ ![Pointwise Convolution](assets/pointwise_conv.png) Thus the total computation cost is for separable depthwise convolution: $$ D_g * D_g * M * D_k * D_k + D_g * D_g * M * N $$ which results in $\frac{1}{N} + \frac{1}{D_k^2}$ reduction in computation: $$ \frac {D_g * D_g * M * D_k * D_k + D_g * D_g * M * N} {D_g * D_g * M * N * D_k * D_k} = \frac {D_k^2 + N} {D_k^2*N} = \frac {1}{N} + \frac{1}{D_k^2} $$ *MobileNets* use a 3x3 kernel, so assuming a large enough $N$, separable depthwise convnets are ~9x more computationally efficient than vanilla convolutions! ### Width Multiplier The 2nd technique for reducing the computational cost is the "width multiplier" which is a hyperparameter inhabiting the range [0, 1] denoted here as $\alpha$. $\alpha$ reduces the number of input and output channels proportionally: $$ D_f * D_f * \alpha M * D_k * D_k + D_f * D_f * \alpha M * \alpha N $$ ### Resolution Multiplier The 3rd technique for reducing the computational cost is the "resolution multiplier" which is a hyperparameter inhabiting the range [0, 1] denoted here as $\rho$. $\rho$ reduces the size of the input feature map: $$ \rho D_f * \rho D_f * M * D_k * D_k + \rho D_f * \rho D_f * M * N $$ Combining the width and resolution multipliers results in a computational cost of: $$ \rho D_f * \rho D_f * a M * D_k * D_k + \rho D_f * \rho D_f * a M * a N $$ Training *MobileNets* with different values of $\alpha$ and $\rho$ will result in different speed vs. accuracy tradeoffs. The folks at Google have run these experiments, the result are shown in the graphic below: ![MobileNets Graphic](https://github.com/tensorflow/models/raw/master/research/slim/nets/mobilenet_v1.png) MACs (M) represents the number of multiplication-add operations in the millions. ### Exercise 1 - Implement Separable Depthwise Convolution In this exercise you'll implement a separable depthwise convolution block and compare the number of parameters to a standard convolution block. For this exercise we'll assume the width and resolution multipliers are set to 1. Docs: * [depthwise convolution](https://www.tensorflow.org/api_docs/python/tf/nn/depthwise_conv2d) ``` def vanilla_conv_block(x, kernel_size, output_channels): """ Vanilla Conv -> Batch Norm -> ReLU """ x = tf.layers.conv2d( x, output_channels, kernel_size, (2, 2), padding='SAME') x = tf.layers.batch_normalization(x) return tf.nn.relu(x) # TODO: implement MobileNet conv block def mobilenet_conv_block(x, kernel_size, output_channels): """ Depthwise Conv -> Batch Norm -> ReLU -> Pointwise Conv -> Batch Norm -> ReLU """ # assumes BHWC format input_channel_dim = x.get_shape().as_list()[-1] W = tf.Variable(tf.truncated_normal((kernel_size, kernel_size, input_channel_dim, 1))) # depthwise conv x = tf.nn.depthwise_conv2d(x, W, (1, 2, 2, 1), padding='SAME') x = tf.layers.batch_normalization(x) x = tf.nn.relu(x) # pointwise conv x = tf.layers.conv2d(x, output_channels, (1, 1), padding='SAME') x = tf.layers.batch_normalization(x) return tf.nn.relu(x) ``` **[Sample solution](./exercise-solutions/e1.py)** Let's compare the number of parameters in each block. ``` # constants but you can change them so I guess they're not so constant :) INPUT_CHANNELS = 32 OUTPUT_CHANNELS = 512 KERNEL_SIZE = 3 IMG_HEIGHT = 256 IMG_WIDTH = 256 with tf.Session(graph=tf.Graph()) as sess: # input x = tf.constant(np.random.randn(1, IMG_HEIGHT, IMG_WIDTH, INPUT_CHANNELS), dtype=tf.float32) with tf.variable_scope('vanilla'): vanilla_conv = vanilla_conv_block(x, KERNEL_SIZE, OUTPUT_CHANNELS) with tf.variable_scope('mobile'): mobilenet_conv = mobilenet_conv_block(x, KERNEL_SIZE, OUTPUT_CHANNELS) vanilla_params = [ (v.name, np.prod(v.get_shape().as_list())) for v in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'vanilla') ] mobile_params = [ (v.name, np.prod(v.get_shape().as_list())) for v in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'mobile') ] print("VANILLA CONV BLOCK") total_vanilla_params = sum([p[1] for p in vanilla_params]) for p in vanilla_params: print("Variable {0}: number of params = {1}".format(p[0], p[1])) print("Total number of params =", total_vanilla_params) print() print("MOBILENET CONV BLOCK") total_mobile_params = sum([p[1] for p in mobile_params]) for p in mobile_params: print("Variable {0}: number of params = {1}".format(p[0], p[1])) print("Total number of params =", total_mobile_params) print() print("{0:.3f}x parameter reduction".format(total_vanilla_params / total_mobile_params)) ``` Your solution should show the majority of the parameters in *MobileNet* block stem from the pointwise convolution. ## *MobileNet* SSD In this section you'll use a pretrained *MobileNet* [SSD](https://arxiv.org/abs/1512.02325) model to perform object detection. You can download the *MobileNet* SSD and other models from the [TensorFlow detection model zoo](https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md) (*note*: we'll provide links to specific models further below). [Paper](https://arxiv.org/abs/1611.10012) describing comparing several object detection models. Alright, let's get into SSD! ### Single Shot Detection (SSD) Many previous works in object detection involve more than one training phase. For example, the [Faster-RCNN](https://arxiv.org/abs/1506.01497) architecture first trains a Region Proposal Network (RPN) which decides which regions of the image are worth drawing a box around. RPN is then merged with a pretrained model for classification (classifies the regions). The image below is an RPN: ![Faster-RCNN Visual](./assets/faster-rcnn.png) The SSD architecture is a single convolutional network which learns to predict bounding box locations and classify the locations in one pass. Put differently, SSD can be trained end to end while Faster-RCNN cannot. The SSD architecture consists of a base network followed by several convolutional layers: ![SSD Visual](./assets/ssd_architecture.png) **NOTE:** In this lab the base network is a MobileNet (instead of VGG16.) #### Detecting Boxes SSD operates on feature maps to predict bounding box locations. Recall a feature map is of size $D_f * D_f * M$. For each feature map location $k$ bounding boxes are predicted. Each bounding box carries with it the following information: * 4 corner bounding box **offset** locations $(cx, cy, w, h)$ * $C$ class probabilities $(c_1, c_2, ..., c_p)$ SSD **does not** predict the shape of the box, rather just where the box is. The $k$ bounding boxes each have a predetermined shape. This is illustrated in the figure below: ![](./assets/ssd_feature_maps.png) The shapes are set prior to actual training. For example, In figure (c) in the above picture there are 4 boxes, meaning $k$ = 4. ### Exercise 2 - SSD Feature Maps It would be a good exercise to read the SSD paper prior to a answering the following questions. ***Q: Why does SSD use several differently sized feature maps to predict detections?*** A: Your answer here **[Sample answer](./exercise-solutions/e2.md)** The current approach leaves us with thousands of bounding box candidates, clearly the vast majority of them are nonsensical. ### Exercise 3 - Filtering Bounding Boxes ***Q: What are some ways which we can filter nonsensical bounding boxes?*** A: Your answer here **[Sample answer](./exercise-solutions/e3.md)** #### Loss With the final set of matched boxes we can compute the loss: $$ L = \frac {1} {N} * ( L_{class} + L_{box}) $$ where $N$ is the total number of matched boxes, $L_{class}$ is a softmax loss for classification, and $L_{box}$ is a L1 smooth loss representing the error of the matched boxes with the ground truth boxes. L1 smooth loss is a modification of L1 loss which is more robust to outliers. In the event $N$ is 0 the loss is set 0. ### SSD Summary * Starts from a base model pretrained on ImageNet. * The base model is extended by several convolutional layers. * Each feature map is used to predict bounding boxes. Diversity in feature map size allows object detection at different resolutions. * Boxes are filtered by IoU metrics and hard negative mining. * Loss is a combination of classification (softmax) and dectection (smooth L1) * Model can be trained end to end. ## Object Detection Inference In this part of the lab you'll detect objects using pretrained object detection models. You can download the latest pretrained models from the [model zoo](https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md), although do note that you may need a newer version of TensorFlow (such as v1.8) in order to use the newest models. We are providing the download links for the below noted files to ensure compatibility between the included environment file and the models. [SSD_Mobilenet 11.6.17 version](http://download.tensorflow.org/models/object_detection/ssd_mobilenet_v1_coco_11_06_2017.tar.gz) [RFCN_ResNet101 11.6.17 version](http://download.tensorflow.org/models/object_detection/rfcn_resnet101_coco_11_06_2017.tar.gz) [Faster_RCNN_Inception_ResNet 11.6.17 version](http://download.tensorflow.org/models/object_detection/faster_rcnn_inception_resnet_v2_atrous_coco_11_06_2017.tar.gz) Make sure to extract these files prior to continuing! ``` # Frozen inference graph files. NOTE: change the path to where you saved the models. SSD_GRAPH_FILE = 'assets/ssd_mobilenet_v1_coco_11_06_2017/frozen_inference_graph.pb' RFCN_GRAPH_FILE = 'assets/rfcn_resnet101_coco_11_06_2017/frozen_inference_graph.pb' FASTER_RCNN_GRAPH_FILE = 'assets/faster_rcnn_inception_resnet_v2_atrous_coco_11_06_2017/frozen_inference_graph.pb' ``` Below are utility functions. The main purpose of these is to draw the bounding boxes back onto the original image. ``` # Colors (one for each class) cmap = ImageColor.colormap print("Number of colors =", len(cmap)) COLOR_LIST = sorted([c for c in cmap.keys()]) # # Utility funcs # def filter_boxes(min_score, boxes, scores, classes): """Return boxes with a confidence >= `min_score`""" n = len(classes) idxs = [] for i in range(n): if scores[i] >= min_score: idxs.append(i) filtered_boxes = boxes[idxs, ...] filtered_scores = scores[idxs, ...] filtered_classes = classes[idxs, ...] return filtered_boxes, filtered_scores, filtered_classes def to_image_coords(boxes, height, width): """ The original box coordinate output is normalized, i.e [0, 1]. This converts it back to the original coordinate based on the image size. """ box_coords = np.zeros_like(boxes) box_coords[:, 0] = boxes[:, 0] * height box_coords[:, 1] = boxes[:, 1] * width box_coords[:, 2] = boxes[:, 2] * height box_coords[:, 3] = boxes[:, 3] * width return box_coords def draw_boxes(image, boxes, classes, thickness=4): """Draw bounding boxes on the image""" draw = ImageDraw.Draw(image) for i in range(len(boxes)): bot, left, top, right = boxes[i, ...] class_id = int(classes[i]) color = COLOR_LIST[class_id] draw.line([(left, top), (left, bot), (right, bot), (right, top), (left, top)], width=thickness, fill=color) def load_graph(graph_file): """Loads a frozen inference graph""" graph = tf.Graph() with graph.as_default(): od_graph_def = tf.GraphDef() with tf.gfile.GFile(graph_file, 'rb') as fid: serialized_graph = fid.read() od_graph_def.ParseFromString(serialized_graph) tf.import_graph_def(od_graph_def, name='') return graph ``` Below we load the graph and extract the relevant tensors using [`get_tensor_by_name`](https://www.tensorflow.org/api_docs/python/tf/Graph#get_tensor_by_name). These tensors reflect the input and outputs of the graph, or least the ones we care about for detecting objects. ``` detection_graph = load_graph(SSD_GRAPH_FILE) #detection_graph = load_graph(RFCN_GRAPH_FILE) #detection_graph = load_graph(FASTER_RCNN_GRAPH_FILE) # The input placeholder for the image. # `get_tensor_by_name` returns the Tensor with the associated name in the Graph. image_tensor = detection_graph.get_tensor_by_name('image_tensor:0') # Each box represents a part of the image where a particular object was detected. detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0') # Each score represent how level of confidence for each of the objects. # Score is shown on the result image, together with the class label. detection_scores = detection_graph.get_tensor_by_name('detection_scores:0') # The classification of the object (integer id). detection_classes = detection_graph.get_tensor_by_name('detection_classes:0') print detection_graph ``` Run detection and classification on a sample image. ``` # Load a sample image. image = Image.open('./assets/sample1.jpg') image_np = np.expand_dims(np.asarray(image, dtype=np.uint8), 0) with tf.Session(graph=detection_graph) as sess: # Actual detection. (boxes, scores, classes) = sess.run([detection_boxes, detection_scores, detection_classes], feed_dict={image_tensor: image_np}) # Remove unnecessary dimensions boxes = np.squeeze(boxes) scores = np.squeeze(scores) classes = np.squeeze(classes) confidence_cutoff = 0.8 # Filter boxes with a confidence score less than `confidence_cutoff` boxes, scores, classes = filter_boxes(confidence_cutoff, boxes, scores, classes) # The current box coordinates are normalized to a range between 0 and 1. # This converts the coordinates actual location on the image. width, height = image.size box_coords = to_image_coords(boxes, height, width) # Each class with be represented by a differently colored box draw_boxes(image, box_coords, classes) plt.figure(figsize=(12, 8)) plt.imshow(image) ``` ## Timing Detection The model zoo comes with a variety of models, each its benefits and costs. Below you'll time some of these models. The general tradeoff being sacrificing model accuracy for seconds per frame (SPF). ``` def time_detection(sess, img_height, img_width, runs=10): image_tensor = sess.graph.get_tensor_by_name('image_tensor:0') detection_boxes = sess.graph.get_tensor_by_name('detection_boxes:0') detection_scores = sess.graph.get_tensor_by_name('detection_scores:0') detection_classes = sess.graph.get_tensor_by_name('detection_classes:0') # warmup gen_image = np.uint8(np.random.randn(1, img_height, img_width, 3)) sess.run([detection_boxes, detection_scores, detection_classes], feed_dict={image_tensor: gen_image}) times = np.zeros(runs) for i in range(runs): t0 = time.time() sess.run([detection_boxes, detection_scores, detection_classes], feed_dict={image_tensor: image_np}) t1 = time.time() times[i] = (t1 - t0) * 1000 return times with tf.Session(graph=detection_graph) as sess: times = time_detection(sess, 600, 1000, runs=10) # Create a figure instance fig = plt.figure(1, figsize=(9, 6)) # Create an axes instance ax = fig.add_subplot(111) plt.title("Object Detection Timings") plt.ylabel("Time (ms)") # Create the boxplot plt.style.use('fivethirtyeight') bp = ax.boxplot(times) ``` ### Exercise 4 - Model Tradeoffs Download a few models from the [model zoo](https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md) and compare the timings. ## Detection on a Video Finally run your pipeline on [this short video](https://s3-us-west-1.amazonaws.com/udacity-selfdrivingcar/advanced_deep_learning/driving.mp4). ``` # Import everything needed to edit/save/watch video clips from moviepy.editor import VideoFileClip from IPython.display import HTML HTML(""" <video width="960" height="600" controls> <source src="{0}" type="video/mp4"> </video> """.format('driving.mp4')) ``` ### Exercise 5 - Object Detection on a Video Run an object detection pipeline on the above clip. ``` clip = VideoFileClip('driving.mp4') # TODO: Complete this function. # The input is an NumPy array. # The output should also be a NumPy array. def pipeline(img): draw_img = Image.fromarray(img) boxes, scores, classes = sess.run([detection_boxes, detection_scores, detection_classes], feed_dict={image_tensor: np.expand_dims(img, 0)}) # Remove unnecessary dimensions boxes = np.squeeze(boxes) scores = np.squeeze(scores) classes = np.squeeze(classes) confidence_cutoff = 0.8 # Filter boxes with a confidence score less than `confidence_cutoff` boxes, scores, classes = filter_boxes(confidence_cutoff, boxes, scores, classes) # The current box coordinates are normalized to a range between 0 and 1. # This converts the coordinates actual location on the image. width, height = draw_img.size box_coords = to_image_coords(boxes, height, width) # Each class with be represented by a differently colored box draw_boxes(draw_img, box_coords, classes) return np.array(draw_img) ``` **[Sample solution](./exercise-solutions/e5.py)** ``` with tf.Session(graph=detection_graph) as sess: image_tensor = sess.graph.get_tensor_by_name('image_tensor:0') detection_boxes = sess.graph.get_tensor_by_name('detection_boxes:0') detection_scores = sess.graph.get_tensor_by_name('detection_scores:0') detection_classes = sess.graph.get_tensor_by_name('detection_classes:0') new_clip = clip.fl_image(pipeline) # write to file new_clip.write_videofile('result.mp4') HTML(""" <video width="960" height="600" controls> <source src="{0}" type="video/mp4"> </video> """.format('result.mp4')) ``` ## Further Exploration Some ideas to take things further: * Finetune the model on a new dataset more relevant to autonomous vehicles. Instead of loading the frozen inference graph you'll load the checkpoint. * Optimize the model and get the FPS as low as possible. * Build your own detector. There are several base model pretrained on ImageNet you can choose from. [Keras](https://keras.io/applications/) is probably the quickest way to get setup in this regard.
github_jupyter
``` import pandas as pd from influxdb import DataFrameClient user = 'root' password = 'root' dbname = 'base47' host='localhost' port=32768 # Temporarily avoid line protocol time conversion issues #412, #426, #431. protocol = 'json' client = DataFrameClient(host, port, user, password, dbname) print("Create pandas DataFrame") df = pd.DataFrame(data=list(range(30)), index=pd.date_range(start='2017-11-16', periods=30, freq='H')) gas=pd.read_csv('data/gas_ft.csv',parse_dates=True,index_col='ts').drop('measurement_unit',axis=1) #client.create_database(dbname) client.query("show databases") #for i in range(len(gas)/500): n=5000 for i in range(5): print(i), print("Writing batch "+str(i)+" of "+str(n)+" elements to Influx | progress: "+str(round(i*100.0/(len(gas)/n),2)))+"%" client.write_points(gas[n*i:n*(i+1)], 'gas', protocol=protocol) #https://influxdb-python.readthedocs.io/en/latest/api-documentation.html#dataframeclient client.write_points(gas, 'gas', protocol=protocol, batch_size=5000) client.write_points(gas, 'gas2', protocol=protocol, tag_columns=['monitor_id'], field_columns=['measurement'], batch_size=5000) print("Write DataFrame with Tags") client.write_points(df, 'demo', {'k1': 'v1', 'k2': 'v2'}, protocol=protocol) print("Read DataFrame") client.query("select * from demo") print("Delete database: " + dbname) client.drop_database(dbname) import numpy as np import pandas as pd import time import requests url = 'http://localhost:32768/write' params = {"db": "base", "u": "root", "p": "root"} def read_data(): with open('data/gas_ft.csv') as f: return [x.split(',') for x in f.readlines()[1:]] a = read_data() a[0] #payload = "elec,id=500 value=24 2018-03-05T19:31:00.000Z\n" payload = "elec,id=500 value=24 "#+str(pd.to_datetime('2018-03-05T19:29:00.000Z\n').value // 10 ** 9) r = requests.post(url, params=params, data=payload) # -*- coding: utf-8 -*- """Tutorial how to use the class helper `SeriesHelper`.""" from influxdb import InfluxDBClient from influxdb import SeriesHelper # InfluxDB connections settings host = 'localhost' port = 8086 user = 'root' password = 'root' dbname = 'mydb' myclient = InfluxDBClient(host, port, user, password, dbname) # Uncomment the following code if the database is not yet created # myclient.create_database(dbname) # myclient.create_retention_policy('awesome_policy', '3d', 3, default=True) class MySeriesHelper(SeriesHelper): """Instantiate SeriesHelper to write points to the backend.""" class Meta: """Meta class stores time series helper configuration.""" # The client should be an instance of InfluxDBClient. client = myclient # The series name must be a string. Add dependent fields/tags # in curly brackets. series_name = 'events.stats.{server_name}' # Defines all the fields in this time series. fields = ['some_stat', 'other_stat'] # Defines all the tags for the series. tags = ['server_name'] # Defines the number of data points to store prior to writing # on the wire. bulk_size = 5 # autocommit must be set to True when using bulk_size autocommit = True # The following will create *five* (immutable) data points. # Since bulk_size is set to 5, upon the fifth construction call, *all* data # points will be written on the wire via MySeriesHelper.Meta.client. MySeriesHelper(server_name='us.east-1', some_stat=159, other_stat=10) MySeriesHelper(server_name='us.east-1', some_stat=158, other_stat=20) MySeriesHelper(server_name='us.east-1', some_stat=157, other_stat=30) MySeriesHelper(server_name='us.east-1', some_stat=156, other_stat=40) MySeriesHelper(server_name='us.east-1', some_stat=155, other_stat=50) # To manually submit data points which are not yet written, call commit: MySeriesHelper.commit() # To inspect the JSON which will be written, call _json_body_(): MySeriesHelper._json_body_() for metric in a[:]: payload = "elec,id="+str(metric[0])+" value="+str(metric[2])+" "+str(pd.to_datetime(metric[3]).value // 10 ** 9)+"\n" #payload = "water,id="+str(metric[0])+" value="+str(metric[2])+"\n" r = requests.post(url, params=params, data=payload) def read_data(): with open('data/water_ft.csv') as f: return [x.split(',') for x in f.readlines()[1:]] a = read_data() a[0] for metric in a[1000:3000]: #payload = "gas,id="+str(metric[0])+" value="+str(metric[2])+" "+str(pd.to_datetime(metric[3]).value // 10 ** 9)+"\n" payload = "water,id="+str(metric[0])+" value="+str(metric[2])+"\n" r = requests.post(url, params=params, data=payload) time.sleep(1) ```
github_jupyter
``` import numpy as np import tensorflow as tf import collections def build_dataset(words, n_words): count = [['GO', 0], ['PAD', 1], ['EOS', 2], ['UNK', 3]] count.extend(collections.Counter(words).most_common(n_words - 1)) dictionary = dict() for word, _ in count: dictionary[word] = len(dictionary) data = list() unk_count = 0 for word in words: index = dictionary.get(word, 0) if index == 0: unk_count += 1 data.append(index) count[0][1] = unk_count reversed_dictionary = dict(zip(dictionary.values(), dictionary.keys())) return data, count, dictionary, reversed_dictionary with open('english-train', 'r') as fopen: text_from = fopen.read().lower().split('\n') with open('vietnam-train', 'r') as fopen: text_to = fopen.read().lower().split('\n') print('len from: %d, len to: %d'%(len(text_from), len(text_to))) concat_from = ' '.join(text_from).split() vocabulary_size_from = len(list(set(concat_from))) data_from, count_from, dictionary_from, rev_dictionary_from = build_dataset(concat_from, vocabulary_size_from) print('vocab from size: %d'%(vocabulary_size_from)) print('Most common words', count_from[4:10]) print('Sample data', data_from[:10], [rev_dictionary_from[i] for i in data_from[:10]]) concat_to = ' '.join(text_to).split() vocabulary_size_to = len(list(set(concat_to))) data_to, count_to, dictionary_to, rev_dictionary_to = build_dataset(concat_to, vocabulary_size_to) print('vocab to size: %d'%(vocabulary_size_to)) print('Most common words', count_to[4:10]) print('Sample data', data_to[:10], [rev_dictionary_to[i] for i in data_to[:10]]) GO = dictionary_from['GO'] PAD = dictionary_from['PAD'] EOS = dictionary_from['EOS'] UNK = dictionary_from['UNK'] class Chatbot: def __init__(self, size_layer, num_layers, embedded_size, from_dict_size, to_dict_size, learning_rate, batch_size): def cells(reuse=False): return tf.nn.rnn_cell.GRUCell(size_layer,reuse=reuse) self.X = tf.placeholder(tf.int32, [None, None]) self.Y = tf.placeholder(tf.int32, [None, None]) self.X_seq_len = tf.placeholder(tf.int32, [None]) self.Y_seq_len = tf.placeholder(tf.int32, [None]) encoder_embeddings = tf.Variable(tf.random_uniform([from_dict_size, embedded_size], -1, 1)) decoder_embeddings = tf.Variable(tf.random_uniform([to_dict_size, embedded_size], -1, 1)) encoder_embedded = tf.nn.embedding_lookup(encoder_embeddings, self.X) main = tf.strided_slice(self.X, [0, 0], [batch_size, -1], [1, 1]) decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1) decoder_embedded = tf.nn.embedding_lookup(encoder_embeddings, decoder_input) rnn_cells = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)]) _, last_state = tf.nn.dynamic_rnn(rnn_cells, encoder_embedded, dtype = tf.float32) with tf.variable_scope("decoder"): rnn_cells_dec = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)]) outputs, _ = tf.nn.dynamic_rnn(rnn_cells_dec, decoder_embedded, initial_state = last_state, dtype = tf.float32) self.logits = tf.layers.dense(outputs,to_dict_size) masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32) self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.logits, targets = self.Y, weights = masks) self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost) size_layer = 128 num_layers = 2 embedded_size = 128 learning_rate = 0.001 batch_size = 32 epoch = 50 tf.reset_default_graph() sess = tf.InteractiveSession() model = Chatbot(size_layer, num_layers, embedded_size, vocabulary_size_from + 4, vocabulary_size_to + 4, learning_rate, batch_size) sess.run(tf.global_variables_initializer()) def str_idx(corpus, dic): X = [] for i in corpus: ints = [] for k in i.split(): try: ints.append(dic[k]) except Exception as e: print(e) ints.append(2) X.append(ints) return X X = str_idx(text_from, dictionary_from) Y = str_idx(text_to, dictionary_to) def pad_sentence_batch(sentence_batch, pad_int): padded_seqs = [] seq_lens = [] max_sentence_len = 120 for sentence in sentence_batch: padded_seqs.append(sentence + [pad_int] * (max_sentence_len - len(sentence))) seq_lens.append(120) return padded_seqs, seq_lens def check_accuracy(logits, Y): acc = 0 for i in range(logits.shape[0]): internal_acc = 0 for k in range(len(Y[i])): if Y[i][k] == logits[i][k]: internal_acc += 1 acc += (internal_acc / len(Y[i])) return acc / logits.shape[0] for i in range(epoch): total_loss, total_accuracy = 0, 0 for k in range(0, (len(text_from) // batch_size) * batch_size, batch_size): batch_x, seq_x = pad_sentence_batch(X[k: k+batch_size], PAD) batch_y, seq_y = pad_sentence_batch(Y[k: k+batch_size], PAD) predicted, loss, _ = sess.run([tf.argmax(model.logits,2), model.cost, model.optimizer], feed_dict={model.X:batch_x, model.Y:batch_y, model.X_seq_len:seq_x, model.Y_seq_len:seq_y}) total_loss += loss total_accuracy += check_accuracy(predicted,batch_y) total_loss /= (len(text_from) // batch_size) total_accuracy /= (len(text_from) // batch_size) print('epoch: %d, avg loss: %f, avg accuracy: %f'%(i+1, total_loss, total_accuracy)) ```
github_jupyter
# Word2Vec笔记 学习word2vec的skip-gram实现,除了skip-gram模型还有CBOW模型。 Skip-gram模式是根据中间词,预测前后词,CBOW模型刚好相反,根据前后的词,预测中间词。 那么什么是**中间词**呢?什么样的词才叫做**前后词**呢? 首先,我们需要定义一个窗口大小,在窗口里面的词,我们才有中间词和前后词的定义。一般这个窗口大小在5-10之间。 举个例子,我们设置窗口大小(window size)为2: ```bash |The|quick|brown|fox|jump| ``` 那么,`brown`就是我们的中间词,`The`、`quick`、`fox`、`jump`就是前后词。 我们知道,word2vec实际上就是一个神经网络(后面会解释),那么这样的数据,我们是以什么样的格式用来训练的呢? 看一张图,你就明白了: ![word2vec window](images/word2vec_window.png) 可以看到,我们总是以**中间词**放在第一个位置,然后跟着我们的前后相邻词。可以看到,每一对词都是一个输入和一个输出组成的数据对(X,Y)。其中,X是feature,Y是label。 所以,我们训练模型之前,需要根据语料,整理出所有的像上面这样的输入数据用来训练。 ## word2vec是一个神经网络 word2vec是一个简单的神经网络,有以下几个层组成: * 1个输入层 * 1个隐藏层 * 1个输出层 输入层输入的就是上面我们说的数据对的数字表示,输出到隐藏层。 隐藏层的神经网络单元的数量,其实就是我们所说的**embedding size**,只有为什么,我们后面简单计算一下就知道。需要注意的是,我们的隐藏层后面不需要使用激活函数。 输出层,我们使用softmax操作,得到每一个预测结果的概率。 这里有一张图,能够表示这个网络: ![skip-gram-net-arhc](images/skip_gram_net_arch.png) ### 输入层 现在问题来了,刚刚我们说,输入层的输入是我们之前准备的数据对的数字表示,那么我们该如何用数字表示文本数据呢? 好像随便一种方式都可以用来表示我们的文本啊。 看上图,我们发现,它的输入使用的是**one-hot**编码。什么是ont-hot编码呢?如图所示,假设有n个词,则每一个词可以用一个n维的向量来表示,这个n维向量只有一个位置是1,其余位置都是0。 那么为什么要用这样的编码来表示呢?答案后面揭晓。 ### 隐藏层 隐藏层的神经单元数量,代表着每一个词用向量表示的维度大小。假设我们的**hidden_size**取300,也就是我们的隐藏层有300个神经元,那么对于每一个词,我们的向量表示就是一个$1*N$的向量。 有多少个词,就有多少个这样的向量! 所以对于**输入层**和**隐藏层**之间的权值矩阵$W$,它的形状应该是`[vocab_size, hidden_size]`的矩阵, ### 输出层 那么我们的输出层,应该是什么样子的呢?从上面的图上可以看出来,输出层是一个`[vocab_size]`大小的向量,每一个值代表着输出一个词的概率。 为什么要这样输出?因为我们想要知道,对于一个输入词,它接下来的词最有可能的若干个词是哪些,换句话说,我们需要知道它接下来的词的概率分布。 你可以再看一看上面那张网络结构图。 你会看到一个很常见的函数**softmax**,为什么是softmax而不是其他函数呢?不妨先看一下softmax函数长啥样: $$ softmax(x) = \frac{e^x}{\sum_{i}^{N}e^{x_i}}$$ 很显然,它的取值范围在(0,1),并别所有的值和为1。这不就是天然的概率表示吗? 当然,softmax还有一个性质,因为它函数指数操作,如果**损失函数使用对数函数**,那么可以抵消掉指数计算。 关于更多的softmax,请看斯坦福[Softmax Regression](http://ufldl.stanford.edu/tutorial/supervised/SoftmaxRegression/) ### 整个过程的数学表示 至此,我们已经知道了整个神经网络的结构,那么我们应该怎么用数学表示出来呢? 回顾一下我们的结构图,很显然,三个层之间会有两个权值矩阵$W$,同时,两个偏置项$b$。所以我们的整个网络的构建,可以用下面的伪代码: ```python import tensorflow as tf # 假设vocab_size = 1000 VOCAB_SIZE = 1000 # 假设embedding_size = 300 EMBEDDINGS_SIZE = 300 # 输入单词x是一个[1,vocab_size]大小的矩阵。当然实际上我们一般会用一批单词作为输入,那么就是[N, vocab_size]的矩阵了 x = tf.placeholder(tf.float32, shape=(1,VOCAB_SIZE)) # W1是一个[vocab_size, embedding_size]大小的矩阵 W1 = tf.Variable(tf.random_normal([VOCAB_SIZE, EMBEDDING_SIZE])) # b1是一个[1,embedding_size]大小的矩阵 b1 = tf.Variable(tf.random_normal([EMBEDDING_SIZE])) # 简单的矩阵乘法和加法 hidden = tf.add(tf.mutmul(x,W1),b1) W2 = tf.Variable(tf.random_normal([EMBEDDING_SIZE,VOCAB_SIZE])) b2 = tf.Variable(tf.random_normal([VOCAB_SIZE])) # 输出是一个vocab_size大小的矩阵,每个值都是一个词的概率值 prediction = tf.nn.softmax(tf.add(tf.mutmul(hidden,w2),b2)) ``` ### 损失函数 网络定义好了,我们需要选一个损失函数来使用梯度下降算法优化模型。 我们的输出层,实际上就是一个softmax分类器。所以按照常规套路,损失函数就选择**交叉熵损失函数**。 哈哈,还记得交叉熵是啥吗? $$ H(p,q)=-\sum_{x}p(x)logq(x)$$ p,q是真是概率分布和估计概率分布。 ```python # 损失函数  cross_entropy_loss = tf.reduce_mean(-tf.reduce_sum(y_label * tf.log(prediction), reduction_indices=[1])) # 训练操作 train_op = tf.train.GradientDescentOptimizer(0.1).minimize(cross_entropy_loss) ``` 接下来,就可以准备号数据,开始训练啦! ### 为啥输入使用one-hot编码? 我们知道word2vec训练后会得到一个权值矩阵W1(暂时忽略b1),这个矩阵就是我们的所有词的向量表示啦!这个矩阵的每一行,就是一个词的矢量表示。如果两个矩阵相乘... ![matrix_mult_w_one_hot](images/matrix_mult_w_one_hot.png) 看到了吗?ont-hot编码的特点,**在矩阵相乘的时候,就是选取出矩阵中的某一行,而这一行就是我们输入这个词语的word2vec表示!**。 怎么样?是不是很妙? 由此,我们可以看出来,所谓的word2vec,实际上就是一个**查找表**,是一个**二维**的浮点数矩阵! 以上是word2vec的skip-gram模型的完整分析,怎么样,是不是弄清楚了word2vec的原理和细节? 完整代码请查看[word2vec](https://github.com/luozhouyang/machine-learning-notes/blob/master/word2vec/word2vec.py)
github_jupyter
``` import pandas as pd import json import numpy as np df = pd.read_csv('data/eiti-summary-company-payments.csv') df = df[df['country'] == "Myanmar"] df.head() ``` ## Clean data ``` df["company_name"].unique() companies_info_df = pd.read_csv('data/eiti_summary_companies_cleaned.csv') companies_info_df.head() df = pd.merge(df, companies_info_df, left_on='company_name', right_on='Legal name') df[df['Commodities'] == 'Gems & Jade']['name_of_revenue_stream'].unique() df[df['Commodities'] == 'Gems & Jade']['gfs_description'].unique() df['revenue_stream_short'] = df['name_of_revenue_stream'].str.split(' - ').str[1] df_gemsjade = df[df['Commodities'] == 'Gems & Jade'] df_gemsjade['type'] = 'entity' df_gemsjade['target_type'] = '' df_gemsjade.head() company_totals = df_gemsjade.pivot_table(index=['Company_name_cl'], aggfunc='sum')['value_reported'] company_totals = company_totals.to_frame() company_totals.rename(columns={'value_reported': 'total_payments'}, inplace=True) company_totals.reset_index(level=0, inplace=True) company_totals df_gemsjade = pd.merge(df_gemsjade, company_totals, on='Company_name_cl') df_gemsjade = df_gemsjade.sort_values(by=['total_payments'], ascending=False) append_dict_others = [{'Company_name_cl': 'Companies not in EITI Reconciliation', 'type': 'entity', 'revenue_stream_short': 'Royalties', 'value_reported': 111092756522 }, {'Company_name_cl': 'Companies not in EITI Reconciliation', 'type': 'entity', 'revenue_stream_short': 'Sale Split', 'value_reported': 51742994736 }, {'Company_name_cl': 'Companies not in EITI Reconciliation', 'type': 'entity', 'revenue_stream_short': 'Emporium Fees / Sale Fees', 'value_reported': 11401644588 }, {'Company_name_cl': 'Companies not in EITI Reconciliation', 'type': 'entity', 'revenue_stream_short': 'Supervision Fees', 'value_reported': 1246890624 }, {'Company_name_cl': 'Companies not in EITI Reconciliation', 'type': 'entity', 'revenue_stream_short': 'Other significant payments', 'value_reported': 2186525820 }] others_df = pd.DataFrame(append_dict_others) others_df['total_payments'] = others_df['value_reported'] df_gemsjade = pd.concat([df_gemsjade, others_df]) df_gemsjade.tail(10) df_gemsjade['revenue_stream_short'] = df_gemsjade['revenue_stream_short'].replace({'Other significant payments (&gt; 50,000 USD)': 'Other significant payments'}) ``` ## Remove negative payments for Sankey ``` df_gemsjade = df_gemsjade[df_gemsjade["value_reported"] >= 0] ``` ## Prepare Source-Target-Value dataframe ``` links = pd.DataFrame(columns=['source','target','value','type']) to_append = df_gemsjade.groupby(['revenue_stream_short'],as_index=False)['type','value_reported','value_reported_as_USD','total_payments'].sum() to_append["target"] = "Myanmar Gems Enterprise" to_append.rename(columns = {'revenue_stream_short':'source', 'value_reported' : 'value'}, inplace = True) to_append = to_append.sort_values(by=['value'], ascending = False) links = pd.concat([links,to_append]) print(to_append['value'].sum()) links append_dict_transfers = [{'source': 'Myanmar Gems Enterprise', 'type': 'entity', 'target': 'State Contribution', 'value': 48367022000 }, {'source': 'Myanmar Gems Enterprise', 'type': 'entity', 'target': 'Transfers to Other Accounts', 'value': 195516457782 }, {'source': 'Myanmar Gems Enterprise', 'type': 'entity', 'target': 'Commercial Tax', 'value': 21499000 }, {'source': 'Myanmar Gems Enterprise', 'type': 'entity', 'target': 'Corporate Income Tax', 'value': 60458777000 }, {'source': 'Myanmar Gems Enterprise', 'type': 'entity', 'target': 'Other material transfers', 'value': 119588538585 }, {'source': 'State Contribution', 'target_type': 'entity', 'target': 'Ministry of Finance', 'value': 48367022000 }, {'source': 'Corporate Income Tax', 'target': 'Internal Revenue Department', 'value': 60458777000 }, {'source': 'Commercial Tax', 'target': 'Internal Revenue Department', 'value': 21499000 }, {'source': 'Internal Revenue Department', 'type': 'entity','target_type': 'entity', 'target': 'Ministry of Finance', 'value': 60480276000 }] append_dict_transfers_df = pd.DataFrame(append_dict_transfers) links = pd.concat([links, append_dict_transfers_df]) links to_append = df_gemsjade.groupby(['revenue_stream_short','Company_name_cl','type'],as_index=False)['value_reported','value_reported_as_USD','total_payments'].sum() to_append.rename(columns = {'Company_name_cl':'source','revenue_stream_short':'target', 'value_reported' : 'value'}, inplace = True) to_append = to_append.sort_values(by=['type','total_payments','value'], ascending = False) links = pd.concat([links,to_append]) print(to_append['value'].sum()) links #to_append = df.groupby(['Payment Type','Reporting Company'],as_index=False)['Value (USD)'].sum() #to_append.rename(columns = {'Payment Type':'source','Reporting Company':'target', 'Value (USD)' : 'value'}, inplace = True) #to_append = to_append.sort_values(by=['value'], ascending = False) #links = pd.concat([links,to_append]) #print(to_append['value'].sum()) #links unique_source = links['source'].unique() unique_targets = links['target'].unique() unique_source = pd.merge(pd.DataFrame(unique_source), links, left_on=0, right_on='source', how='left') unique_source = unique_source.filter([0,'type']) unique_targets = pd.merge(pd.DataFrame(unique_targets), links, left_on=0, right_on='target', how='left') unique_targets = unique_targets.filter([0,'target_type']) unique_targets.rename(columns = {'target_type':'type'}, inplace = True) unique_list = pd.concat([unique_source[0], unique_targets[0]]).unique() unique_list = pd.merge(pd.DataFrame(unique_list), \ pd.concat([unique_source, unique_targets]), left_on=0, right_on=0, how='left') unique_list.drop_duplicates(subset=0, keep='first', inplace=True) replace_dict = {k: v for v, k in enumerate(unique_list[0])} unique_list #replace_dict links_replaced = links.replace({"source": replace_dict,"target": replace_dict}) links_replaced nodes = pd.DataFrame(unique_list) nodes.rename(columns = {0:'name'}, inplace = True) nodes_json= pd.DataFrame(nodes).to_json(orient='records') nodes_json links_json= pd.DataFrame(links_replaced).to_json(orient='records') links_json data = { 'links' : json.loads(links_json), 'nodes' : json.loads(nodes_json) } data_json = json.dumps(data) data_json = data_json.replace("\\","") #print(data_json) #with open('sankey_data.json', 'w') as outfile: # json.dump(data_json, outfile) text_file = open("sankey_data_2013-14.json", "w") text_file.write(data_json) text_file.close() ```
github_jupyter
``` import sys import cv2 as cv import os import numpy as np from PyQt5.QtWidgets import QApplication, QDialog, QFileDialog from ui import * class MainWindow(QDialog, Ui_Form): def __init__(self, parent=None): super(MainWindow, self).__init__() self.setupUi(self) # Variables for initialization statistics self.path_list = [] self.path_list_i = 0 self.count = 0 self.bias_sum = 0 # Define control parameters self.CENTER_X = 900 self.CENTER_Y = 900 self.RADIUS = 680 # Define image parameters self.THRESH = 170 self.MAXVAL = 255 # Initializing auxiliary lines self.left_line = 600 self.right_line = 1200 self.up_line = 600 self.down_line = 1200 # Initialization signal and slot connection ##Initialization open file operation button self.open_folder_button.clicked.connect(self.get_file_path) self.next_button.clicked.connect(self.press_next) self.pre_button.clicked.connect(self.press_pre) ## Initialize gray value adjustment connection self.min_spin.valueChanged.connect(self.change_min_grayscale_spin) self.max_spin.valueChanged.connect(self.change_max_grayscale_spin) self.min_slider.valueChanged.connect(self.change_min_grayscale_slider) self.max_slider.valueChanged.connect(self.change_max_grayscale_slider) ## Initialization guide line, mask connection self.left_spin.valueChanged.connect(self.change_left) self.right_spin.valueChanged.connect(self.change_right) self.up_spin.valueChanged.connect(self.change_up) self.down_spin.valueChanged.connect(self.change_down) self.center_x_spin.valueChanged.connect(self.change_center_x) self.center_y_spin.valueChanged.connect(self.change_center_y) self.r_spin.valueChanged.connect(self.change_r) ##Initialize nine offset connections self.bias_1.valueChanged.connect(self.bias_change) self.bias_2.valueChanged.connect(self.bias_change) self.bias_3.valueChanged.connect(self.bias_change) self.bias_4.valueChanged.connect(self.bias_change) self.bias_5.valueChanged.connect(self.bias_change) self.bias_6.valueChanged.connect(self.bias_change) self.bias_7.valueChanged.connect(self.bias_change) self.bias_8.valueChanged.connect(self.bias_change) self.bias_9.valueChanged.connect(self.bias_change) def get_file_path(self): dir_choose = QFileDialog.getExistingDirectory(self, "Select Folder", os.getcwd()) temp_list = os.listdir(dir_choose) for i in temp_list: self.path_list.append(dir_choose + "/" + i) self.path_list_i = 0 self.shulaibao() def press_next(self): if self.path_list_i == len(self.path_list) - 1: pass else: self.path_list_i += 1 self.shulaibao() def press_pre(self): if self.path_list_i == 0: pass else: self.path_list_i -= 1 self.shulaibao() def change_min_grayscale_slider(self): self.THRESH = self.min_slider.value() self.min_spin.setValue(self.THRESH) self.shulaibao() def change_min_grayscale_spin(self): self.THRESH = self.min_spin.value() self.min_slider.setValue(self.THRESH) self.shulaibao() def change_max_grayscale_slider(self): self.MAXVAL = self.max_slider.value() self.max_spin.setValue(self.MAXVAL) self.shulaibao() def change_max_grayscale_spin(self): self.MAXVAL = self.max_spin.value() self.max_slider.setValue(self.MAXVAL) self.shulaibao() def change_center_x(self): self.CENTER_X = self.center_x_spin.value() self.shulaibao() def change_center_y(self): self.CENTER_Y = self.center_y_spin.value() self.shulaibao() def change_r(self): self.RADIUS = self.r_spin.value() self.shulaibao() def change_left(self): self.left_line = self.left_spin.value() self.shulaibao() def change_right(self): self.right_line = self.right_spin.value() self.shulaibao() def change_down(self): self.right_line = self.right_spin.value() self.shulaibao() def change_up(self): self.right_line = self.right_spin.value() self.shulaibao() def bias_change(self): self.bias_sum = self.bias_1.value() + self.bias_2.value() + self.bias_3.value() + self.bias_4.value() + \ self.bias_5.value() + self.bias_6.value() + self.bias_7.value() + self.bias_8.value() + \ self.bias_9.value() self.count_label.setText(f"The total is:{self.count + self.bias_sum}") def shulaibao(self): cv.destroyAllWindows() img = cv.imread(self.path_list[self.path_list_i]) img_gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) img_gray = cv.blur(img_gray, (3, 3)) # The circular mask is drawn and the target image is synthesized with gray image mask = np.zeros_like(img_gray) mask = cv.circle(mask, (self.CENTER_X, self.CENTER_Y), self.RADIUS, (255, 255, 255), -1) mask = mask // 255 img_with_mask = mask * img_gray # Binarization _, img_threshold = cv.threshold(img_with_mask, self.THRESH, self.MAXVAL, cv.THRESH_BINARY) # Connect the region to get the border contours, _ = cv.findContours(img_threshold, cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE) img_1 = cv.drawContours(img, contours, -1, (0, 0, 255)) img_1 = cv.circle(img_1, (self.CENTER_X, self.CENTER_Y), self.RADIUS, (0, 255, 0), 5) img_1 = cv.putText(img_1, "{}".format(len(contours)), (100, 100), cv.FONT_HERSHEY_SIMPLEX, 2, (255, 255, 255),5) # Draw guides cv.line(img_1, (self.left_line, 0), (self.left_line, 1800), (0, 255, 0), 3, 8) cv.line(img_1, (self.right_line, 0), (self.right_line, 1800), (0, 255, 0), 3, 8) cv.line(img_1, (0, self.up_line), (1800, self.up_line), (0, 255, 0), 3, 8) cv.line(img_1, (0, self.down_line), (1800, self.down_line), (0, 255, 0), 3, 8) # Display picture, record number img_1 = cv.resize(img_1, (0, 0), fx=0.5, fy=0.5) self.count = len(contours) self.bias_change() cv.imshow("COUNT", img_1) cv.waitKey(0) if __name__ == "__main__": app = QApplication(sys.argv) w = MainWindow() w.show() app.exec_() cv.destroyAllWindows() sys.exit() ```
github_jupyter
# Regularization with SciKit-Learn ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns df = pd.read_csv('Data/Advertising.csv') df.head() X = df.drop('sales', axis=1) y = df['sales'] ``` ### Polynomial Conversion ``` from sklearn.preprocessing import PolynomialFeatures poly_converter = PolynomialFeatures(degree=3, include_bias=False) poly_features = poly_converter.fit_transform(X) poly_features.shape ``` ### Train | Test Split ``` from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(poly_features, y, test_size=0.3, random_state=101) ``` ----- # Scaling the Data ``` from sklearn.preprocessing import StandardScaler scaler = StandardScaler() # to avoid data leakage : meaning model got an idea of test data # only fit to train data set scaler.fit(X_train) # overwrite scaled data X_train = scaler.transform(X_train) X_test = scaler.transform(X_test) ``` We can see that after scaling, values has scaled down. ``` X_train[0] poly_features[0] ``` -------- ------- # Ridge Regression ``` from sklearn.linear_model import Ridge ridge_model = Ridge(alpha=10) ridge_model.fit(X_train, y_train) test_predictions = ridge_model.predict(X_test) from sklearn.metrics import mean_absolute_error, mean_squared_error MAE = mean_absolute_error(y_test, test_predictions) MAE RMSE = np.sqrt(mean_squared_error(y_test, test_predictions)) RMSE # Training Set Performance train_predictions = ridge_model.predict(X_train) MAE = mean_absolute_error(y_train, train_predictions) RMSE = np.sqrt(mean_squared_error(y_train, train_predictions)) MAE, RMSE ``` --------- ## Choosing an alpha value with Cross-Validation ``` from sklearn.linear_model import RidgeCV ridge_cv_model = RidgeCV(alphas=(0.1, 1.0, 10.0), scoring='neg_mean_absolute_error') ridge_cv_model.fit(X_train, y_train) # get the best alpha value ridge_cv_model.alpha_ ridge_cv_model.coef_ ``` As we can see from the coefficient, ridge regression is considering every features. ------ If you don't remember which key to use for `scoring metrics`, we can search like that. ``` from sklearn.metrics import SCORERS SCORERS.keys() # these are the scoring parameters that we can use. but depends on the model, use the appropriate key # for neg_mean_squared_error, etc the HIGHER the value is, the BETTER (because it is the negative value/opposite of mean squared error (the lower the bettter)) ``` ------- ``` # check performance test_predictions = ridge_cv_model.predict(X_test) MAE = mean_absolute_error(y_test, test_predictions) RMSE = np.sqrt(mean_squared_error(y_test, test_predictions)) MAE, RMSE ``` Comparing the MAE and RMSE with alpha value of 10 result (0.5774404204714166, 0.8946386461319675), the results are much better now. -------- -------- # Lasso Regression - LASSO (Least Absolute Shinkage and Selection Operator) - **the smaller `eps` value is, the wider range we are checking** ``` from sklearn.linear_model import LassoCV # lasso_cv_model = LassoCV(eps=0.001,n_alphas=100,cv=5, max_iter=1000000) #wider range because eps value is smaller lasso_cv_model = LassoCV(eps=0.1,n_alphas=100,cv=5) #narrower range lasso_cv_model.fit(X_train,y_train) # best alpha value lasso_cv_model.alpha_ test_predictions = lasso_cv_model.predict(X_test) MAE = mean_absolute_error(y_test, test_predictions) RMSE = np.sqrt(mean_squared_error(y_test, test_predictions)) MAE, RMSE ``` By comparing the previous results of Ridge Regression, this model seems like not performing well. ``` lasso_cv_model.coef_ ``` We can check the coefficient of lasso regression model. As we can see from the above, there are only 2 features that model is considering. Other features are 0 and not considered by model. But based on the context and if we want to consider only two features, Lasso may be a better choice. However we need to take note that MAE, RMSE is not performing as well as Ridge. But alphas value can be higher (expand the wider range of search) and make a more complext model. -------- ------- # Elastic Net (L1 + L2) ``` from sklearn.linear_model import ElasticNetCV elastic_cv_model = ElasticNetCV(l1_ratio=[.1, .5, .7,.9, .95, .99, 1], eps=0.001, n_alphas=100, max_iter=1000000) elastic_cv_model.fit(X_train, y_train) #best l1 ratio elastic_cv_model.l1_ratio_ elastic_cv_model.alpha_ test_predictions = elastic_cv_model.predict(X_test) MAE = mean_absolute_error(y_test, test_predictions) RMSE = np.sqrt(mean_squared_error(y_test, test_predictions)) MAE, RMSE elastic_cv_model.coef_ ```
github_jupyter
``` from chessnet.notebook_config import * dfs = { "OTB": pd.read_csv(ARTIFACTS_DIR / f"{Database.OTB}.csv"), "Portal": pd.read_csv(ARTIFACTS_DIR / f"{Database.Portal}.csv"), } games_per_player_dict = {} for i, (name, df) in enumerate(dfs.items()): players = pd.concat([ df[["White"]].dropna().rename(columns={"White": "Player"}), df[["Black"]].dropna().rename(columns={"Black": "Player"}), ]) counts = players.value_counts() games_per_player = counts.values games_per_player_dict[name] = games_per_player def plot_game_distribution(data, ax=None, **kwargs): if ax is None: _, ax = plt.subplots() ax.set_xscale("log") ax.set_yscale("log") ax.set_xlabel("Cantidad de partidas") ax.set_ylabel("Frecuencia") # Log scale bins = np.logspace(np.log10(min(data)), np.log10(max(data)+1), 20) freq, _ = np.histogram(data, bins=bins, density=True) X_log, Y_log = bins[:-1], freq Y_pred, slope, y_err = linear_regression(X_log[:-3], Y_log[:-3]) c = Y_log[5] / X_log[5]**slope #label = r'$\gamma = {{{:.2f}}}({{{:.0f}}})$'.format(slope, 100*y_err) label = r'${{{:.2f}}}({{{:.0f}}})$'.format(slope, 100*y_err) #ax.text(0.45, 0.73, label, fontsize=26, transform=ax.transAxes) ax.text(0.28, 0.5, r"$\gamma = -1.5$", fontsize=26, transform=ax.transAxes) #ax.plot( # X_log, powerlaw(X_log, slope, c), "--", color="k", zorder=10, #label=label, #) #X_powerlaw = X_log X_powerlaw = np.array([1, 10000]) ax.plot( X_powerlaw, powerlaw(X_powerlaw, -1.5, c), "--", color="k", zorder=10, #label=label, ) # Lin scale bins = range(1, max(data)+1) freq, _ = np.histogram(data, bins=bins, density=True) X_lin, Y_lin = bins[:-1], freq ax.plot( X_lin, Y_lin, ".", color="gray", alpha=0.5, fillstyle="none", label="Bineado lineal" ) color = kwargs.get("color") ax.plot( X_log, Y_log, "o", markersize=10, color=color, label="Bineado logarítmico" ) return ax ncols = 2 nrows = 1 fig, axes = plt.subplots(figsize=(8*ncols, 6*nrows), ncols=ncols, nrows=nrows) for ax in axes.flatten(): ax.set_xlim(0.5, 30000) axes[0].set_title(database_latex["OTB"], fontsize=30) axes[1].set_title(database_latex["Portal"], fontsize=30) axes[0].plot([0.3, 0.45], [0.6, 0.6], "-", color="k", transform=axes[0].transAxes) axes[0].plot([0.3, 0.3], [0.6, 0.7], "-", color="k", transform=axes[0].transAxes) axes[1].plot([0.3, 0.45], [0.6, 0.6], "-", color="k", transform=axes[1].transAxes) axes[1].plot([0.3, 0.3], [0.6, 0.7], "-", color="k", transform=axes[1].transAxes) for i, (name, df) in enumerate(dfs.items()): ax = axes[0] ax.text(0.9, 0.9, panels[i], fontsize=30, transform=ax.transAxes) games_per_player = games_per_player_dict[name] plot_game_distribution(games_per_player, ax=ax, color=f"C{i}") ax.set_xticks([1, 10, 100, 1000, 10000]) ax.set_ylim(5e-10, 1) axes[0].legend(frameon=False) axes[1].legend(frameon=False) sns.despine() plt.tight_layout() plt.savefig(FIGS_DIR / "game_distribution.pdf") plt.show() def plot_game_distribution(data, ax=None, **kwargs): if ax is None: _, ax = plt.subplots() ax.set_xscale("log") ax.set_yscale("log") ax.set_xlabel("Cantidad de partidas") ax.set_ylabel("Frecuencia") # Log scale bins = np.logspace(np.log10(min(data)), np.log10(max(data)+1), 35) freq, _ = np.histogram(data, bins=bins, density=True) X_log, Y_log = bins[:-1], freq mask = ~np.isnan(Y_log) mask = Y_log>1e-10 X_log, Y_log = X_log[mask], Y_log[mask] ax.plot( X_log, Y_log, markersize=8, color=kwargs.get("color"), label=kwargs.get("label"), marker=kwargs.get("marker"), fillstyle="none", ) return ax ncols = 1 nrows = 1 fig, ax = plt.subplots(figsize=(8*ncols, 6*nrows), ncols=ncols, nrows=nrows) ax.set_xlim(0.5, 200000) ax.text(0.9, 0.9, panels[0], fontsize=30, transform=ax.transAxes) ax.plot([0.3, 0.42], [0.6, 0.6], "-", color="k", transform=ax.transAxes) ax.plot([0.3, 0.3], [0.6, 0.7], "-", color="k", transform=ax.transAxes) for i, (name, df) in enumerate(dfs.items()): games_per_player = games_per_player_dict[name] marker = "o" if name == "OTB" else "s" plot_game_distribution(games_per_player, ax=ax, color=f"C{i}", label=name, marker=marker) X_powerlaw = np.array([1, 50000]) ax.plot( X_powerlaw, powerlaw(X_powerlaw, -1.5, 0.15), "--", color="k", zorder=10 ) #ax.text(0.28, 0.5, r"$\gamma = -1.5$", fontsize=26, transform=ax.transAxes) ax.text(0.3, 0.5, r"$-1.5$", fontsize=26, transform=ax.transAxes) ax.set_xticks([1, 10, 100, 1000, 10000, 100000]) ax.set_ylim(1e-11, 2) ax.set_yticks([1, 1e-2, 1e-4, 1e-6, 1e-8, 1e-10]) ax.legend(frameon=False, loc="lower left") sns.despine() plt.tight_layout() #plt.savefig(FIGS_DIR / "game_distribution.pdf") plt.show() ncols = 1 nrows = 1 fig, ax = plt.subplots(figsize=(8*ncols, 6*nrows), ncols=ncols, nrows=nrows) ax.set_ylabel("Cantidad de partidas") ax.set_xlabel("Índice del jugador") ax.set_xscale("log") ax.set_yscale("log") for i, (name, df) in enumerate(dfs.items()): games_per_player = games_per_player_dict[name] Y = games_per_player X = np.arange(1, len(Y)+1) ax.plot(X, Y, label=name) ax.set_xlim(0.5, 1e6) ax.set_xticks([1, 10, 100, 1000, 10000, 100000, 1e6]) ax.set_yticks([1, 10, 100, 1000, 10000, 100000]) ax.legend(frameon=False) sns.despine() plt.show() ncols = 2 nrows = 1 fig, axes = plt.subplots(figsize=(8*ncols, 6*nrows), ncols=ncols, nrows=nrows) ax = axes[0] ax.set_xlim(0.5, 200000) ax.text(0.9, 0.9, panels[0], fontsize=30, transform=ax.transAxes) ax.plot([0.3, 0.42], [0.6, 0.6], "-", color="k", transform=ax.transAxes) ax.plot([0.3, 0.3], [0.6, 0.7], "-", color="k", transform=ax.transAxes) for i, (name, df) in enumerate(dfs.items()): games_per_player = games_per_player_dict[name] marker = "o" if name == "OTB" else "s" plot_game_distribution(games_per_player, ax=ax, color=f"C{i}", label=name, marker=marker) X_powerlaw = np.array([1, 50000]) ax.plot( X_powerlaw, powerlaw(X_powerlaw, -1.5, 0.15), "--", color="k", zorder=10 ) #ax.text(0.28, 0.5, r"$\gamma = -1.5$", fontsize=26, transform=ax.transAxes) ax.text(0.3, 0.5, r"$-1.5$", fontsize=26, transform=ax.transAxes) ax.set_xticks([1, 10, 100, 1000, 10000, 100000]) ax.set_ylim(1e-11, 2) ax.set_yticks([1, 1e-2, 1e-4, 1e-6, 1e-8, 1e-10]) ax.legend(frameon=False, loc="lower left") ax = axes[1] ax.text(0.9, 0.9, panels[1], fontsize=30, transform=ax.transAxes) ax.set_ylabel("Cantidad de partidas") ax.set_xlabel("Índice del jugador") ax.set_xscale("log") ax.set_yscale("log") for i, (name, df) in enumerate(dfs.items()): games_per_player = games_per_player_dict[name] Y = games_per_player X = np.arange(1, len(Y)+1) ax.plot(X, Y, label=name) ax.set_xlim(0.5, 1e6) ax.set_xticks([1, 10, 100, 1000, 10000, 100000, 1e6]) ax.set_yticks([1, 10, 100, 1000, 10000, 100000]) ax.legend(frameon=False, loc="lower left") sns.despine() plt.tight_layout() plt.savefig(FIGS_DIR / "game_distribution.pdf") plt.show() ```
github_jupyter
``` # -- coding: utf-8 -- # This code is part of Qiskit. # # (C) Copyright IBM 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import torch from torch.autograd import Function import torch.optim as optim from qiskit import QuantumRegister,QuantumCircuit,ClassicalRegister,execute from qiskit.circuit import Parameter from qiskit import Aer import numpy as np from tqdm import tqdm from matplotlib import pyplot as plt %matplotlib inline def to_numbers(tensor_list): num_list = [] for tensor in tensor_list: num_list += [tensor.item()] return num_list class QiskitCircuit(): def __init__(self,shots): self.theta = Parameter('Theta') self.phi = Parameter('Phi') self.shots = shots def create_circuit(): qr = QuantumRegister(1,'q') cr = ClassicalRegister(1,'c') ckt = QuantumCircuit(qr,cr) ckt.h(qr[0]) # ckt.barrier() ckt.u2(self.theta,self.phi,qr[0]) ckt.barrier() ckt.measure(qr,cr) return ckt self.circuit = create_circuit() def N_qubit_expectation_Z(self,counts, shots, nr_qubits): expects = np.zeros(nr_qubits) for key in counts.keys(): perc = counts[key]/shots check = np.array([(float(key[i])-1/2)*2*perc for i in range(nr_qubits)]) expects += check return expects def bind(self, parameters): [self.theta,self.phi] = to_numbers(parameters) self.circuit.data[1][0]._params = to_numbers(parameters) def run(self, i): self.bind(i) backend = Aer.get_backend('qasm_simulator') job_sim = execute(self.circuit,backend,shots=self.shots) result_sim = job_sim.result() counts = result_sim.get_counts(self.circuit) return self.N_qubit_expectation_Z(counts,self.shots,1) class TorchCircuit(Function): @staticmethod def forward(ctx, i): if not hasattr(ctx, 'QiskitCirc'): ctx.QiskitCirc = QiskitCircuit(shots=10000) exp_value = ctx.QiskitCirc.run(i[0]) result = torch.tensor([exp_value]) ctx.save_for_backward(result, i) return result @staticmethod def backward(ctx, grad_output): eps = 0.01 forward_tensor, i = ctx.saved_tensors input_numbers = to_numbers(i[0]) gradient = [0,0] for k in range(len(input_numbers)): input_eps = input_numbers input_eps[k] = input_numbers[k] + eps exp_value = ctx.QiskitCirc.run(torch.tensor(input_eps))[0] result_eps = torch.tensor([exp_value]) gradient_result = (exp_value - forward_tensor[0][0].item())/eps gradient[k] = gradient_result # print(gradient) result = torch.tensor([gradient]) # print(result) return result.float() * grad_output.float() # x = torch.tensor([np.pi/4, np.pi/4, np.pi/4], requires_grad=True) x = torch.tensor([[0.0, 0.0]], requires_grad=True) qc = TorchCircuit.apply y1 = qc(x) y1.backward() print(x.grad) qc = TorchCircuit.apply def cost(x): target = -1 expval = qc(x) return torch.abs(qc(x) - target) ** 2, expval x = torch.tensor([[0.0, np.pi/4]], requires_grad=True) opt = torch.optim.Adam([x], lr=0.1) num_epoch = 100 loss_list = [] expval_list = [] for i in tqdm(range(num_epoch)): # for i in range(num_epoch): opt.zero_grad() loss, expval = cost(x) loss.backward() opt.step() loss_list.append(loss.item()) expval_list.append(expval.item()) # print(loss.item()) plt.plot(loss_list) # print(circuit(phi, theta)) # print(cost(x)) ``` ### MNIST in pytorch ``` import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import numpy as np import torchvision from torchvision import datasets, transforms batch_size_train = 1 batch_size_test = 1 learning_rate = 0.01 momentum = 0.5 log_interval = 10 torch.backends.cudnn.enabled = False transform=torchvision.transforms.Compose([ torchvision.transforms.ToTensor()]) mnist_trainset = datasets.MNIST(root='./data', train=True, download=True, transform=transform) labels = mnist_trainset.targets #get labels labels = labels.numpy() idx1 = np.where(labels == 0) #search all zeros idx2 = np.where(labels == 1) # search all ones idx = np.concatenate((idx1[0][0:100],idx2[0][0:100])) # concatenate their indices mnist_trainset.targets = labels[idx] mnist_trainset.data = mnist_trainset.data[idx] print(mnist_trainset) train_loader = torch.utils.data.DataLoader(mnist_trainset, batch_size=batch_size_train, shuffle=True) class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 10, kernel_size=5) self.conv2 = nn.Conv2d(10, 20, kernel_size=5) self.conv2_drop = nn.Dropout2d() self.fc1 = nn.Linear(320, 50) self.fc2 = nn.Linear(50, 2) def forward(self, x): x = F.relu(F.max_pool2d(self.conv1(x), 2)) x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2)) x = x.view(-1, 320) x = F.relu(self.fc1(x)) x = F.dropout(x, training=self.training) x = self.fc2(x) # return F.softmax(x) # x = np.pi*F.tanh(x) # print(x) x = qc(x) x = (x+1)/2 x = torch.cat((x, 1-x), -1) return x network = Net() # optimizer = optim.SGD(network.parameters(), lr=learning_rate, # momentum=momentum) optimizer = optim.Adam(network.parameters(), lr=learning_rate/10) epochs = 10 loss_list = [] for epoch in range(epochs): total_loss = [] target_list = [] for batch_idx, (data, target) in enumerate(train_loader): target_list.append(target.item()) # print(batch_idx) optimizer.zero_grad() output = network(data) # loss = F.nll_loss(output, target) loss = F.cross_entropy(output, target) # print(output) # print(output[0][1].item(), target.item()) loss.backward() optimizer.step() total_loss.append(loss.item()) loss_list.append(sum(total_loss)/len(total_loss)) print(loss_list[-1]) plt.plot(loss_list) ```
github_jupyter
``` from datascience import * path_data = '../../data/' import matplotlib matplotlib.use('Agg', warn=False) %matplotlib inline import matplotlib.pyplot as plots plots.style.use('fivethirtyeight') import numpy as np ``` ### The Monty Hall Problem ### This [problem](https://en.wikipedia.org/wiki/Monty_Hall_problem) has flummoxed many people over the years, [mathematicians included](https://web.archive.org/web/20140413131827/http://www.decisionsciences.org/DecisionLine/Vol30/30_1/vazs30_1.pdf). Let's see if we can work it out by simulation. The setting is derived from a television game show called "Let's Make a Deal". Monty Hall hosted this show in the 1960's, and it has since led to a number of spin-offs. An exciting part of the show was that while the contestants had the chance to win great prizes, they might instead end up with "zonks" that were less desirable. This is the basis for what is now known as *the Monty Hall problem*. The setting is a game show in which the contestant is faced with three closed doors. Behind one of the doors is a fancy car, and behind each of the other two there is a goat. The contestant doesn't know where the car is, and has to attempt to find it under the following rules. - The contestant makes an initial choice, but that door isn't opened. - At least one of the other two doors must have a goat behind it. Monty opens one of these doors to reveal a goat, displayed in all its glory in [Wikipedia](https://en.wikipedia.org/wiki/Monty_Hall_problem): ![Monty Hall goat](../../../images/monty_hall_goat.png) - There are two doors left, one of which was the contestant's original choice. One of the doors has the car behind it, and the other one has a goat. The contestant now gets to choose which of the two doors to open. The contestant has a decision to make. Which door should she choose to open, if she wants the car? Should she stick with her initial choice, or switch to the other door? That is the Monty Hall problem. ### The Solution ### In any problem involving chances, the assumptions about randomness are important. It's reasonable to assume that there is a 1/3 chance that the contestant's initial choice is the door that has the car behind it. The solution to the problem is quite straightforward under this assumption, though the straightforward solution doesn't convince everyone. Here it is anyway. - The chance that the car is behind the originally chosen door is 1/3. - The car is behind either the originally chosen door or the door that remains. It can't be anywhere else. - Therefore, the chance that the car is behind the door that remains is 2/3. - Therefore, the contestant should switch. That's it. End of story. Not convinced? Then let's simulate the game and see how the results turn out. ### Simulation ### The simulation will be more complex that those we have done so far. Let's break it down. ### Step 1: What to Simulate ### For each play we will simulate what's behind all three doors: - the one the contestant first picks - the one that Monty opens - the remaining door So we will be keeping track of three quantitites, not just one. ### Step 2: Simulating One Play ### The bulk of our work consists of simulating one play of the game. This involves several pieces. #### The Goats #### We start by setting up an array `goats` that contains unimaginative names for the two goats. ``` goats = make_array('first goat', 'second goat') ``` To help Monty conduct the game, we are going to have to identify which goat is selected and which one is revealed behind the open door. The function `other_goat` takes one goat and returns the other. ``` def other_goat(x): if x == 'first goat': return 'second goat' elif x == 'second goat': return 'first goat' ``` Let's confirm that the function works. ``` other_goat('first goat'), other_goat('second goat'), other_goat('watermelon') ``` The string `'watermelon'` is not the name of one of the goats, so when `'watermelon'` is the input then `other_goat` does nothing. #### The Options #### The array `hidden_behind_doors` contains the set of things that could be behind the doors. ``` hidden_behind_doors = make_array('car', 'first goat', 'second goat') ``` We are now ready to simulate one play. To do this, we will define a function `monty_hall_game` that takes no arguments. When the function is called, it plays Monty's game once and returns a list consisting of: - the contestant's guess - what Monty reveals when he opens a door - what remains behind the other door The game starts with the contestant choosing one door at random. In doing so, the contestant makes a random choice from among the car, the first goat, and the second goat. If the contestant happens to pick one of the goats, then the other goat is revealed and the car is behind the remaining door. If the contestant happens to pick the car, then Monty reveals one of the goats and the other goat is behind the remaining door. ``` def monty_hall_game(): """Return [contestant's guess, what Monty reveals, what remains behind the other door]""" contestant_guess = np.random.choice(hidden_behind_doors) if contestant_guess == 'first goat': return [contestant_guess, 'second goat', 'car'] if contestant_guess == 'second goat': return [contestant_guess, 'first goat', 'car'] if contestant_guess == 'car': revealed = np.random.choice(goats) return [contestant_guess, revealed, other_goat(revealed)] ``` Let's play! Run the cell several times and see how the results change. ``` monty_hall_game() ``` ### Step 3: Number of Repetitions ### To gauge the frequency with which the different results occur, we have to play the game many times and collect the results. Let's run 10,000 repetitions. ### Step 4: Coding the Simulation ### It's time to run the whole simulation. We will play the game 10,000 times and collect the results in a table. Each row of the table will contain the result of one play. One way to grow a table by adding a new row is to use the `append` method. If `my_table` is a table and `new_row` is a list containing the entries in a new row, then `my_table.append(new_row)` adds the new row to the bottom of `my_table`. Note that `append` does not create a new table. It changes `my_table` to have one more row than it did before. First let's create a table `games` that has three empty columns. We can do this by just specifying a list of the column labels, as follows. ``` games = Table(['Guess', 'Revealed', 'Remaining']) ``` Notice that we have chosen the order of the columns to be the same as the order in which `monty_hall_game` returns the result of one game. Now we can add 10,000 rows to `trials`. Each row will represent the result of one play of Monty's game. ``` # Play the game 10000 times and # record the results in the table games for i in np.arange(10000): games.append(monty_hall_game()) ``` The simulation is done. Notice how short the code is. The majority of the work was done in simulating the outcome of one game. ### Visualization ### To see whether the contestant should stick with her original choice or switch, let's see how frequently the car is behind each of her two options. ``` original_choice = games.group('Guess') original_choice remaining_door = games.group('Remaining') remaining_door ``` As our earlier solution said, the car is behind the remaining door two-thirds of the time, to a pretty good approximation. The contestant is twice as likely to get the car if she switches than if she sticks with her original choice. To see this graphically, we can join the two tables above and draw overlaid bar charts. ``` joined = original_choice.join('Guess', remaining_door, 'Remaining') combined = joined.relabeled(0, 'Item').relabeled(1, 'Original Door').relabeled(2, 'Remaining Door') combined combined.barh(0) ``` Notice how the three blue bars are almost equal – the original choice is equally likely to be any of the three available items. But the gold bar corresponding to `Car` is twice as long as the blue. The simulation confirms that the contestant is twice as likely to win if she switches.
github_jupyter
--- # Langages de script - Python ## Cours 9 — Pip et virtualenv ### M2 Ingénierie Multilingue - INaLCO --- - Loïc Grobol <loic.grobol@gmail.com> - Yoann Dupont <yoa.dupont@gmail.com> # Les modules sont vos amis Rappel des épisodes précédents ## Ils cachent vos implémentations - Quand on code une interface, on a pas envie de voir le code fonctionnel - Et vice-versa Ce qu'on fait quand on code proprement (ou presque) ```python # malib.py import re def tokenize(s): return re.split(r"\s+", s) ``` ```python # moninterface.py import sys import malib if __name__ == "__main__": path = sys.argv[1] with open(path) as in_stream: for l in in_stream: print("_".join(list(malib.tokenize(l)))) ``` Comme ça quand je code mon interface, je n'ai pas besoin de me souvenir ou même de voir comment est codé `tokenize` ## Il y en a déjà plein ``` help("modules") ``` ## Ils vous simplifient la vie ``` import pathlib p = pathlib.Path(".").resolve() display(p) display(list(p.glob("*.ipynb"))) projet = p.parent / "assignments" display(list(exos.glob("*"))) ``` # `stdlib` ne suffit plus Parfois la bibliothèque standard est trop limitée Je veux repérer dans un texte toutes les occurences de « omelette » qui ne sont pas précédées par « une » ``` text = """oui très bien maintenant il reste plus que quelques petites questions pour sit- oui c' était les c' était la dernière chose que je voulais vous demander les Anglais prétendent que même dans les moindres choses y a des différences entre euh la façon de vivre des Français et des Anglais et euh c' est pourquoi euh ils demandent euh ils se demandaient comment en France par exemple on faisait une omelette et s' il y avait des différences entre euh la façon française de faire une omelette et la façon anglaise alors si vous pouviez décrire comment vous vous faites une omelette ? tout d' abord on m- on casse les oeufs dans un saladier euh on mélange le le blanc et le jaune et puis on on bat avec soit avec une fourchette soit avec un appareil parce qu' il existe des appareils pour battre les oeufs euh vous prenez une poêle vous y mettez du beurre et quand il est fondu euh vous versez l' omelette par dessus euh t- j' ai oublié de dire qu' on mettait du sel et du poivre dans dans les oeufs hm hm ? et quand euh vous avez versé le les oeufs dans la dans la poêle euh vous euh vous quand ça prend consistance vous retournez votre omelette en faisant attention de euh de la retourner comme il faut évidemment qu' elle ne se mette pas en miettes et vous la faites cuire de l' autre côté et pour la présenter on la plie en deux maintenant on peut mettre aussi dans le dans le dans les oeufs euh des fines herbes""" import re pattern = r"(?<!une )omelette" re.findall(pattern, text) ``` Mais je veux pouvoir le faire même s'il y a plusieurs espaces ``` pattern = r"(?<!une\s+)omelette" re.findall(pattern, text) ``` `re` ne permet pas de faire ce genre de choses (un *lookbehind* de taille variable) mais [`regex`](https://pypi.org/project/regex) oui ``` import regex pattern = r"(?<!une\s+)omelette" regex.findall(pattern, text) ``` ## `pip`, le gestionnaire [`pip`](https://pip.pypa.io) est le gestionnaire de paquets intégré à python (sauf sous Debian 😠). Comme tout bon gestionnaire de paquet il sait - Installer un paquet `pip install regex` - Donner des infos `pip show regex` - Le mettre à jour `pip install -U regex` - Le désinstaller `pip uninstall regex` ## Pypi, le *cheeseshop* Situé à https://pypi.org, Pypi liste les paquets tiers — conçus et maintenus par la communauté — pour Python. Quand vous demandez à `pip` d'installer un paquet, c'est là qu'il va le chercher par défaut. ``` !pip search regex ``` Vous pouvez aussi le parcourir dans l'inteface web, c'est un bon point de départ pour éviter de réinventer la roue. Le moteur de pypi est libre et rien ne vous empêche d'héberger votre propre instance, il suffira alors d'utiliser pip avec l'option `--index-url <url>` `pip` sait faire plein d'autres choses et installer depuis beaucoup de sources. Par exemple un dépôt git ``` !pip install --force-reinstall git+https://github.com/psf/requests.git ``` # Les choses désagréables Il y a des choses pour lesquelles `pip` n'est pas bon ## Résoudre des conflits de dépendances ``` !pip install -U --force-reinstall botocore==1.13.9 python-dateutil>=2.1 ``` [Mais plus pour longtemps !](https://github.com/pypa/pip/issues/988) ## Checker ses privilèges ```bash $ pip install regex ERROR: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/usr/local/lib/python2.7/dist-packages/ ``` Un remède simple : n'installer que pour soi ```bash $ pip install --user regex Successfully installed regex-2019.11.1 ``` ## Répondre quand on l'appelle Ou plutôt c'est python qui a un souci ```bash $ pip install --user regex Successfully installed regex-2019.11.1 $ python3 -c "import regex;print(regex.__version__)" ModuleNotFoundError: No module named 'regex ``` ```bash $ pip --version pip 19.3.1 from /home/lgrobol/.local/lib/python3.8/site-packages/pip (python 3.8) $ python3 --version Python 3.7.5rc1 ``` La solution : exiger le bon python ```bash $ python3 -m pip install --user regex Successfully installed regex-2019.11.1 $ python3 -c "import regex;print(regex.__version__)" 2.5.65 ``` # Freeze! Une fonction importante de `pip` est la capacité de geler les versions des paquets installés et de les restorer ``` !pip freeze ``` (Traditionellement, pour les sauvegarder: `pip freeze > requirements.txt`) Il est **fortement** recommandé de le faire quand on lance une expérience pour pouvoir la reproduire dans les mêmes conditions si besoin. Pour restorer les mêmes versions ```bash pip install -r requirements.txt ``` (éventuellement avec `-U` et `--force-reinstall` en plus et bien sûr `--user`) On peut aussi écrire des `requirements.txt` à la main pour préciser les dépendances d'un projet ``` !cat ../requirements.txt ``` # `virtualenv` À force d'installer tout et n'importe quoi, il finit fatalement par arriver que - Des paquets que vous utilisez dans des projets séparés aient des conflits de version - Vous passiez votre temps à installer depuis des `requirements.txt` - Vos `requirements.txt` soient soit incomplets soit trop complets Et arrive la conclusion **En fait il me faudrait une installation différente de python pour chaque projet !** Et c'est précisément ce qu'on va faire ``` !pip install virtualenv ``` ## Comment ? - Placez-vous dans un répertoire vide ```bash mkdir -p ~/tmp/python-im-test/cours-9 && cd ~/tmp/python-im-test/cours-9 ``` - Entrez ```bash python3 -m virtualenv .virtenv ``` - Vous avez créé un environnement virtuel \o/ activez-le ```bash source .virtenv/bin/activate ``` ## Et alors ? ```bash $ pip list Package Version ---------- ------- pip 19.3.1 setuptools 41.6.0 wheel 0.33.6 ``` Alors vous avez ici une installation isolée du reste ! ```bash wget https://raw.githubusercontent.com/LoicGrobol/python-im-2/master/requirements.txt pip install -r requirements.txt ``` Et maintenant vous avez tous les paquets utilisés dans ce cours. En bonus - `pip` est le bon `pip` - `python` est le bon `python` - Tout ce que vous faites avec python n'agira que sur `.virtenv`, votre système reste propre ! En particulier, si rien ne va plus, il suffit de supprimer `.virtenv` ## `virtualenv` vs `venv` Il existe dans la distribution standard (sauf pour Debian 🙃) le module `venv` et un module tiers `virtualenv`. `venv` est essentiellement une version minimale de `virtualenv` avec uniquement les fonctionalités strictement nécéssaires. En pratique on a rarement besoin de plus **sauf** quand on veut installer plusieurs versions de python en parallèle. # Comment travailler proprement À partir de maintenant vous pouvez (et je vous recommande de) - **Toujours** travailler dans un virtualenv - **Toujours** lister vos dépendances tierces dans un requirements.txt - **Toujours** `pip freeze`er les versions exactes pour vos expés (dans un `frozen-requirements.txt` par exemple. - **Dès qu'un test se transforme en projet** en faire un dépôt git Si vous travaillez avec `git` et `virtualenv` dans le même dossier pensez à ajouter le nom du dossier de votre environnement dans un `.gitignore` ```gitignore # .gitignore .virtenv __pycache__/ … ``` (Les gens de github ont des .gitingore tout faits, [celui pour Python](https://github.com/github/gitignore/blob/master/Python.gitignore) utilise `.venv` mais c'est moyen d'utiliser le nom d'un module pour un dossier) **Maintenant allez-y, faites ça dans vos dossiers de projets !**
github_jupyter
<h1>Optimized analysis of WMLs using MRI</h1> ``` %%HTML <h1>Imports</h1> #coding=utf-8 #matplotlib.use('Agg') from numpy import * import numpy import numpy as np import matplotlib import matplotlib.pyplot as plt from skimage import color import dicom from io import StringIO import sys import glob, urllib, os from ia636 import iaconv, ianormalize, iamosaic, iagshow,iaimginfo, iaffine from ia870 import iagradm, iaareaopen, iaareaclose, ialabel, iadist, iasedisk, iasecross, iasubm, iadil, iaero from skimage.feature import local_binary_pattern from sklearn.feature_extraction import image from sklearn.metrics import accuracy_score, confusion_matrix from sklearn import svm,neighbors,preprocessing from sklearn import metrics from skimage import exposure import skimage.transform from joblib import Parallel, delayed import multiprocessing from sklearn.ensemble import BaggingClassifier, RandomForestClassifier from sklearn.multiclass import OneVsRestClassifier from sklearn.svm import SVC from sklearn import linear_model from sklearn.neural_network import MLPClassifier from sklearn.preprocessing import StandardScaler from sklearn.svm import LinearSVC from sklearn.calibration import CalibratedClassifierCV from sklearn.model_selection import cross_val_score from sklearn.grid_search import GridSearchCV from sklearn import decomposition from sklearn.decomposition import PCA,IncrementalPCA import time import timeit import warnings import datetime from time import gmtime, strftime from copy import deepcopy warnings.filterwarnings("ignore") %%HTML <h1>Support Functions</h1> def write(msg): print msg execution_log.write(msg + "\n") def write_table(msg): execution_results.write(msg + "\n") def write_double(msg): write(msg) write_table(msg) def write_double_fim(): msg = ("-------------------" * 3) write_double(msg) def write_line(msg): print (msg + "\n" + line) execution_log.write(msg + "\n" + line + "\n") def write_double_line(msg): print (line + "\n" + msg + "\n" + line) execution_log.write(line + "\n" + msg + "\n" + line + "\n") def write_line_fim(msg): print (msg + "\n" + line + "\n" + line) execution_log.write(msg + "\n" + line + "\n" + big_line + "\n" + line + "\n" + "\n" + "\n") execution_results.write(msg + "\n" + line + "\n" + big_line + "\n" + line + "\n" + "\n" + "\n") def write_results(results): write_double("Result for each user ID:") separate("-", 86) for result in results: write_double("|id: " + str(format(result[0], "02d")) + "|Acuracy: " + str(format(result[1], "5.3f")) + "| Dice without post-processing: " + str(format(result[2], "5.3f")) + "|std: " + str(format(result[3], "5.3f")) + "| Dice with post-processing: " + str(format(result[4], "5.3f")) + "|std: " + str(format(result[5], "5.3f")) + "|") separate("-",86) def close_files(): execution_log.close() execution_results.close() def separate(separator, n): msg = str(separator * n) write(msg) write_table(msg) %%HTML <h1>Program Functions</h1> #################################################### #################################################### #Function: gradimg (from local_texture) #Goal: generate gradient of an image #Input: image f #Output: gradient of image f #################################################### #################################################### def gradimg(f): if len(f.shape) == 2: # 2D case h1 = array([[0,1,0], # Defining the horizontal mask [0,0,0], [0,-1,0]]) h2 = array([[0,0,0], # Defining the vertical mask [1,0,-1], [0,0,0]]) aux1 = iaconv(f,h1)[1:-1,1:-1].astype(int) # Make the convolution between horizontal mask and image aux2 = iaconv(f,h2)[1:-1,1:-1].astype(int) # Make the convolution between vertical mask and image g = sqrt(aux1**2 + aux2**2) # Use the equation to compute the gradient of an image return g else: # 3D case h1 = array([[[0,0,0], # Defining the horizontal mask [0,0,0], [0,0,0]], [[0,1,0], [0,0,0], [0,-1,0]], [[0,0,0], [0,0,0], [0,0,0]]]) h2 = array([[[0,0,0], # Defining the vertical mask [0,0,0], [0,0,0]], [[0,0,0], [1,0,-1], [0,0,0]], [[0,0,0], [0,0,0], [0,0,0]]]) h3 = array([[[0,0,0], # Defining the depth mask [0,1,0], [0,0,0]], [[0,0,0], [0,0,0], [0,0,0]], [[0,0,0], [0,-1,0], [0,0,0]]]) aux1 = iaconv(f,h1)[1:-1,1:-1,1:-1].astype(int) # Make the convolution between horizontal mask and image aux2 = iaconv(f,h2)[1:-1,1:-1,1:-1].astype(int) # Make the convolution between vertical mask and image aux3 = iaconv(f,h3)[1:-1,1:-1,1:-1].astype(int) # Make the convolution between depth mask and image grad = sqrt(aux1**2 + aux2**2 + aux3**2) # Use the equation to compute the gradient of an image return grad #################################################### #################################################### #Function: resize #Goal: changes the dimension of the images #Input: img, slices #Output: img (imagem redimensionada) #################################################### #################################################### def resize(img, slices): if (img.shape[1] > size_slice and img.shape[2] > size_slice): return skimage.transform.resize(img, (slices,size_slice,size_slice)) elif (img.shape[1] == size_slice and img.shape[2] == size_slice): return img else: sys.exit(1) ##################################################### ##################################################### #Function: generate_images_pre_processing #Goal: performs pre-processing of the images #Input: img_org, img_wm, img_wml #Output: img_org, img_wm, img_wml ##################################################### ##################################################### def generate_images_pre_processing(img_org, img_wm, img_wml): #resize slices = img_org.shape[0] img_org = resize(img_org, slices) img_wm = resize(img_wm, slices) img_wml = resize(img_wml, slices) #normalize the image img_org = ianormalize(img_org) return (img_org, img_wm, img_wml) #################################################### #################################################### #Function: print_infos_start_program #Goal: print information about the program #Input: - #Output: - #################################################### #################################################### def print_infos_start_program(): execution_log.write(line + "\n") print line write_double("Start of the program") print line data_local = time.localtime() year = str(data_local[0]) month = data_local[1] day = data_local[2] hour = data_local[3] minute = data_local[4] second = data_local[5] current_date = (str(format(day, "02d")) + "/" + str(format(month, "02d")) + "/" + str(year)) current_time = (str(format(hour, "02d")) + ":" + str(format(minute, "02d")) + ":" + str(format(second, "02d"))) #Prints date and time write_line("Day: " + str(current_date)) write_line("Time: " + str(current_time)) #prints the number of processors write_line("Num CPUs: " + str(num_cores)) ############################################################### ############################################################### #Function: print_lists_patients_training_and_test #Goal: prints list of patients for training and testing #Input: list of patients for training and testing #Output: - ############################################################### ############################################################### def print_lists_patients_training_and_test(id_list_training, id_list_testing): #IDs for training num_elements_training=len(id_list_training) write_double("Number of elements for training: " + str(num_elements_training)) write_double("IDs for training:") for id in id_list_training: print id, execution_log.write(str(id) + " ") execution_results.write(str(id) + " ") write_double("\n" + line) #IDs for testing num_elements_testing=len(id_list_testing) write_double("Number of elements for testing: " + str(num_elements_testing)) write_double("IDs for testing:") for id in id_list_testing: print id, execution_log.write(str(id) + " ") execution_results.write(str(id) + " ") write_double("\n" + line) ################################################### ################################################### #Function: boxplot #Goal: prints boxplot of the testing patients #Input: dice_total_testing, labels=list_testing_wml #Output: - ################################################### ################################################### def boxplot(dice_total_testing, list_testing_wml): plt.xlabel('Testing Patients') plt.ylabel('Dice Coefficient') plt.ylim([0.0, 1.0]) plt.boxplot(dice_total_testing, labels=list_testing_wml) plt.title("Boxplot") plt.savefig(path_box_plot_folder) plt.show(dice_total_testing) ########################################################################### ########################################################################### #Function: generate_mosaics #Goal: creates 3D Mosaics of the testing patients #Input: user_id, img_wml, prediction_matrix_without_post_processing, prediction_matrix_with_post_processing #Output: - ############################################################################ ############################################################################ def generate_mosaics(user_id, img_wml, prediction_matrix_without_post_processing, prediction_matrix_with_post_processing): #3D mosaic img_wml1 img_temp = img_wml[0:50,:,:] img_wml1 = ianormalize(iamosaic(img_temp,5)) #3D mosaic img_wml2 img_temp = img_wml[50:100,:,:] img_wml2 = ianormalize(iamosaic(img_temp,5)) #3D mosaic img_wml3 img_temp = img_wml[100:,:,:] img_wml3 = ianormalize(iamosaic(img_temp,5)) #3D mosaic img_prediction1 img_temp = prediction_matrix_without_post_processing[0:50,:,:] img_prediction1 = ianormalize(iamosaic(img_temp,5)) #3D mosaic img_prediction2 img_temp = prediction_matrix_without_post_processing[50:100,:,:] img_prediction2 = ianormalize(iamosaic(img_temp,5)) #3D mosaic img_prediction3 img_temp = prediction_matrix_without_post_processing[100:,:,:] img_prediction3 = ianormalize(iamosaic(img_temp,5)) #3D mosaic img_prediction_pos1 img_temp = prediction_matrix_with_post_processing[0:50,:,:] img_prediction_pos1 = ianormalize(iamosaic(img_temp,5)) #3D mosaic img_prediction_pos2 img_temp = prediction_matrix_with_post_processing[50:100,:,:] img_prediction_pos2 = ianormalize(iamosaic(img_temp,5)) #3D mosaic img_prediction_pos3 img_temp = prediction_matrix_with_post_processing[100:,:,:] img_prediction_pos3 = ianormalize(iamosaic(img_temp,5)) plt.imshow(img_wml1, cmap='Greys_r') plt.title(" id "+str(user_id)+" | wml1 0-50") plt.savefig(path_mosaics_folder+str(user_id)+"/1)wml_0_50") plt.imshow(img_prediction1, cmap='Greys_r') plt.title(" id " +str(user_id)+ " | img prediction 1 without post-processing 1 0-50") plt.savefig(path_mosaics_folder+str(user_id)+"/2)prediction_without_post_0_50") plt.imshow(img_prediction_pos1, cmap='Greys_r') plt.title(" id " +str(user_id)+ " | img prediction 1 with post-processing 0-50") plt.savefig(path_mosaics_folder+str(user_id)+"/3)prediction_with_post_0_50") plt.imshow(img_wml2, cmap='Greys_r') plt.title(" id " +str(user_id)+ " | wml2 50-100") plt.savefig(path_mosaics_folder+str(user_id)+"/4)wml_50_100") plt.imshow(img_prediction2, cmap='Greys_r') plt.title(" id " +str(user_id)+ " | img prediction 2 without post-processing 50-100") plt.savefig(path_mosaics_folder+str(user_id)+"/5)prediction_without_post_50_100") plt.imshow(img_prediction_pos2, cmap='Greys_r') plt.title(" id " +str(user_id)+ " | img prediction 2 with post-processing 50-100") plt.savefig(path_mosaics_folder+str(user_id)+"/6)prediction_with_post_50_100") plt.imshow(img_wml3, cmap='Greys_r') plt.title(" id " +str(user_id)+ " | wml3 100-154") plt.savefig(path_mosaics_folder+str(user_id)+"/7)wml_100_154") plt.imshow(img_prediction3, cmap='Greys_r') plt.title(" id " +str(user_id)+ " | img prediction 3 without post-processing 100-154") plt.savefig(path_mosaics_folder+str(user_id)+"/8)rediction_without_post_100_154") plt.imshow(img_prediction_pos3, cmap='Greys_r') plt.title(" id " +str(user_id)+ " | img prediction 3 with post-processing 100-154") plt.savefig(path_mosaics_folder+str(user_id)+"/9)prediction_with_post_100_154") ###################################################################################################################################### ###################################################################################################################################### #Function: generate_color_maps #Goal: generates color map of the desired slice of a patient #Input: user_id, img_org, img_wml, prediction_probability_matrix, prediction_matrix_without_post_processing, prediction_matrix_with_post_processing, desired_slice #Output: - ####################################################################################################################################### ####################################################################################################################################### def generate_color_maps(user_id, img_org, img_wml, prediction_probability_matrix, prediction_matrix_without_post_processing, prediction_matrix_with_post_processing, desired_slice): plt.imshow(img_org[desired_slice], cmap='Greys_r') plt.title("Original Image") plt.savefig(path_color_maps_folder+str(user_id)+"/"+str(desired_slice)+"/Original Image") plt.imshow(img_wml[desired_slice], cmap='Greys_r') plt.title("WML Image") plt.savefig(path_color_maps_folder+str(user_id)+"/"+str(desired_slice)+"/WML Image") plt.imshow(prediction_matrix_without_post_processing[desired_slice], cmap='Greys_r') plt.title("Prediction without post-processing") plt.savefig(path_color_maps_folder+str(user_id)+"/"+str(desired_slice)+"/Prediction without post-processing") plt.imshow(prediction_matrix_with_post_processing[desired_slice], cmap='Greys_r') plt.title("Prediction with post-processing") plt.savefig(path_color_maps_folder+str(user_id)+"/"+str(desired_slice)+"/Prediction with post-processing") plt.imshow(1.0*prediction_probability_matrix[desired_slice]/prediction_probability_matrix[desired_slice].max()) plt.colorbar() plt.title("Color Probability") plt.savefig(path_color_maps_folder+str(user_id)+"/"+str(desired_slice)+"/Color Probability") ###################################################################### ###################################################################### #Function: generate_slice_post_processing #Goal: performs post-processing on a slice of the prediction matrix #Input: prediction_slice_matrix #Output: slice_prediction_matrix_with_post_processing ###################################################################### ###################################################################### def generate_slice_post_processing(prediction_slice_matrix): #copies slice slice_prediction_matrix_with_post_processing = prediction_slice_matrix #connects regions disconnected by a maximum amount of the specified number of pixels slice_prediction_matrix_with_post_processing = iaareaclose(slice_prediction_matrix_with_post_processing,size_closed_area) #the method ignores regions with less than a specified number of pixels of lesion slice_prediction_matrix_with_post_processing = iaareaopen(slice_prediction_matrix_with_post_processing,size_opened_area) #the method ignores regions that do not fit on a unitary radius disk prob_mask_pred = slice_prediction_matrix_with_post_processing mask_pred_label = ialabel(slice_prediction_matrix_with_post_processing) # separate lesions nrois = len(np.unique(mask_pred_label))-1 # background for id_les in arange(0,nrois): roi = zeros_like(slice_prediction_matrix_with_post_processing) roi[mask_pred_label==id_les+1] = 1 prob_mask_pred[roi>0] = prob_mask_pred[roi>0].mean() #if it fits on a unitary radius disk if iadist(roi>0,iasedisk(1),'EUCLIDEAN').max()<2: slice_prediction_matrix_with_post_processing[roi]=0 return slice_prediction_matrix_with_post_processing ################################################################################# ################################################################################# #Function: read_dcm #Goal: reads and returns Dicom images (original, wm mask and wml mask) #Input: user_id (id do paciente) #Output: img_org, img_wm, img_wml ################################################################################# ################################################################################# def read_dcm(user_id): filename_img = ("%s/%d/FLAIR.dcm" % (path_miccai_images_folder, user_id)) #3D original image dataset_img = dicom.read_file(filename_img) img_org = dataset_img.pixel_array.astype(float) filename_wml = ("%s/%d/WML.dcm" % (path_miccai_images_folder, user_id)) #3D image with lesions dataset_wml = dicom.read_file(filename_wml) img_wml = dataset_wml.pixel_array.astype(bool) img_wm = (np.zeros_like(img_org)).astype(bool) for current_slice in range (img_wm.shape[0]): filename_wm = ("%s/%d/WM-mask/IM-0001-%04d.dcm" % (path_miccai_images_folder, user_id, (current_slice+1))) dataset_wm = dicom.read_file(filename_wm) img_wm[current_slice] = dataset_wm.pixel_array.astype(bool) return (img_org, img_wm, img_wml) ############################################################################################################## ############################################################################################################## #Function: extract_attributes_slice #Goal: extract attributes of a given slice of a given patient #Input: user_id, flag_training_or_testing, img_org, img_wm, slice_wml, current_slice, slices #Output: data_userid_slice, n_pixels_wml_slice, n_pixels_used_wm_not_wml_slice, n_total_pixels_wm_slice ############################################################################################################## ############################################################################################################## def extract_attributes_slice (user_id, flag_training_or_testing, img_org, img_wm, slice_wml, current_slice, slices): #initialize variables data_userid_slice = [] n_pixels_wml_slice=0 n_pixels_used_wm_not_wml_slice=0 n_total_pixels_wm_slice=0 #analyse an individual slices slice_org = img_org[current_slice] slice_maskwm = img_wm[current_slice] #features lbp_img = local_binary_pattern(slice_org, n_points, radius, method) grad_img = gradimg(slice_org) mgrad_img = iagradm(slice_org) #training if (flag_training_or_testing == 0): #pre-processing #ignores pixels where intensity<wmmean #ignores pixels where there are less than "method_threshold" concatenated pixels mean_wm = slice_org[slice_maskwm==1].mean() slice_maskwm2 = logical_and(iaareaopen((slice_org>mean_wm),method_threshold),slice_maskwm) #pre-processing to possibly reduce the number of wm_nao_wml pixels #Modo 0 ou 1 if (operation_mode == 0 or operation_mode == 1): wm_nao_wml = slice_maskwm2 #mode 2 elif (operation_mode == 2): #dilation of wml using a cross of size 2 cross2 = iasecross(size_cross_2) wm_nao_wml = iasubm(slice_maskwm2, iadil(slice_wml>0,cross2)) #mode 3 elif (operation_mode == 3): #erosion of wml using a cross of size 1 cross1 = iasecross(size_cross_1) wm_nao_wml = iaero(slice_maskwm2,cross1) #mode 4 elif (operation_mode == 4): #dilation of wml using a cross of size 2 #erosion of wml using a cross of size 1 cross2 = iasecross(size_cross_2) cross1 = iasecross(size_cross_1) wm_nao_wml = iasubm(iaero(slice_maskwm2,cross1), iadil(slice_wml>0,cross2)) #creates a list with wm pixels after pre-processing ind_class = argwhere(slice_maskwm2 == 1) for ind_mask in xrange(len(ind_class)): x = ind_class[ind_mask,0] #coordeinate x of the pixels in the mask of wm validated y = ind_class[ind_mask,1] #coordinate y of the pixels in the mask of wml validated #total number of pixels wm n_total_pixels_wm_slice+=1 #data paremeters: #[user id, current_slice, x, y, intensity, inferior slice intensity, superior slice intensity, lbp, grad, mgrad, average] #if the pixel represents a lesion if (slice_wml[x,y] > 0.5): n_pixels_wml_slice+=1 #number of lesions #inferior slice if (current_slice==0): data_userid_slice.append([user_id,current_slice,x,y,slice_org[x,y],slice_org[x,y],img_org[current_slice+1,x,y],lbp_img[x,y],grad_img[x,y],mgrad_img[x,y],mean_wm,1]) #superior slice elif (current_slice==(slices-1)): data_userid_slice.append([user_id,current_slice,x,y,slice_org[x,y],img_org[current_slice-1,x,y],slice_org[x,y],lbp_img[x,y],grad_img[x,y],mgrad_img[x,y],mean_wm,1]) else: data_userid_slice.append([user_id,current_slice,x,y,slice_org[x,y],img_org[current_slice-1,x,y],img_org[current_slice+1,x,y],lbp_img[x,y],grad_img[x,y],mgrad_img[x,y],mean_wm,1]) #if the pixel does not represents a lesion else: #it only considers the pixel if it is in the area defined by wm_nao_wml if (wm_nao_wml[x,y]): n_pixels_used_wm_not_wml_slice+=1 #inferior slice if (current_slice==0): data_userid_slice.append([user_id,current_slice,x,y,slice_org[x,y],slice_org[x,y],img_org[current_slice+1,x,y],lbp_img[x,y],grad_img[x,y],mgrad_img[x,y],mean_wm,1]) #superior slice elif (current_slice==(slices-1)): data_userid_slice.append([user_id,current_slice,x,y,slice_org[x,y],img_org[current_slice-1,x,y],slice_org[x,y],lbp_img[x,y],grad_img[x,y],mgrad_img[x,y],mean_wm,0]) else: data_userid_slice.append([user_id,current_slice,x,y,slice_org[x,y],img_org[current_slice-1,x,y],img_org[current_slice+1,x,y],lbp_img[x,y],grad_img[x,y],mgrad_img[x,y],mean_wm,0]) return (data_userid_slice, n_pixels_wml_slice, n_pixels_used_wm_not_wml_slice, n_total_pixels_wm_slice) elif (flag_training_or_testing == 1): #pre-processing #eliminates pixels where intensity<wmmean #eliminates regions where there are less than 10 concatenated pixels mean_wm = slice_org[slice_maskwm==1].mean() slice_maskwm2 = logical_and(iaareaopen(slice_org,method_threshold),slice_maskwm) #creates a list of wm pixels after the pre-processing ind_class = argwhere(slice_maskwm2 == 1) for ind_mask in xrange(len(ind_class)): x = ind_class[ind_mask,0] #x coordinate of the do pixel na máscara de wm válidos y = ind_class[ind_mask,1] #y coordinate of the y do pixel na máscara de wm válidos #number of wm pixels n_total_pixels_wm_slice+=1 #data parameters: #[user id, current_slice, x, y, intensity, inferior slice intensity, superior slice intensity, lbp, grad, mgrad, average] #se o pixel for lesão if (slice_wml[x,y] > 0.5): n_pixels_wml_slice+=1 #number of lesions #slice de baixo if (current_slice==0): data_userid_slice.append([user_id,current_slice,x,y,slice_org[x,y],slice_org[x,y],img_org[slice+1,x,y],lbp_img[x,y],grad_img[x,y],mgrad_img[x,y],mean_wm,1]) #slice de cima elif (current_slice==(slices-1)): data_userid_slice.append([user_id,current_slice,x,y,slice_org[x,y],img_org[current_slice-1,x,y],slice_org[x,y],lbp_img[x,y],grad_img[x,y],mgrad_img[x,y],mean_wm,1]) else: data_userid_slice.append([user_id,current_slice,x,y,slice_org[x,y],img_org[current_slice-1,x,y],img_org[current_slice+1,x,y],lbp_img[x,y],grad_img[x,y],mgrad_img[x,y],mean_wm,1]) #se o pixel não for lesão else: n_pixels_used_wm_not_wml_slice+=1 #slice de baixo if (current_slice==0): data_userid_slice.append([user_id,current_slice,x,y,slice_org[x,y],slice_org[x,y],img_org[slice+1,x,y],lbp_img[x,y],grad_img[x,y],mgrad_img[x,y],mean_wm,1]) #slice de cima elif (current_slice==(slices-1)): data_userid_slice.append([user_id,current_slice,x,y,slice_org[x,y],img_org[current_slice-1,x,y],slice_org[x,y],lbp_img[x,y],grad_img[x,y],mgrad_img[x,y],mean_wm,0]) else: data_userid_slice.append([user_id,current_slice,x,y,slice_org[x,y],img_org[current_slice-1,x,y],img_org[current_slice+1,x,y],lbp_img[x,y],grad_img[x,y],mgrad_img[x,y],mean_wm,0]) return (data_userid_slice, n_pixels_wml_slice, n_pixels_used_wm_not_wml_slice, n_total_pixels_wm_slice) else: sys.exit(1) ########################################################## ########################################################## #Function: calculate_dice_slice #Goal: calculates the dice coefficient for a given slice #Input: img_wml_slice, prediction_slice_matrix #Output: ds (dice of a slice) ########################################################## ########################################################## def calculate_dice_slice(img_wml_slice, prediction_slice_matrix): #calculates dividend and divider using the standard dice formula dividend = (1.0*(logical_and(img_wml_slice,(prediction_slice_matrix)).sum())) divider = (1.0*((img_wml_slice.sum()+(prediction_slice_matrix).sum()))) if (divider == 0): ds = 0.0 else: ds = 2.0*(dividend/divider) #print "%s" % (ds) return ds ############################################# ############################################# #Function: extract_attributes_training #Goal: extract attributes for a patient #Input: user_id #Output: data_userid ############################################# ############################################# def extract_attributes_training(user_id): img_org, img_wm, img_wml = read_dcm(user_id) slices = img_org.shape[0] #training flag_training_or_testing = 0 #initialize variables n_pixels_wml = 0 n_pixels_used_wm_not_wml = 0 n_total_pixels_wm = 0 #user_id data data_userid = [] img_org, img_wm, img_wml = generate_images_pre_processing(img_org, img_wm, img_wml) for current_slice in xrange(slices): #ignores regions with less than a specified number of pixels of lesion (prediction_matrix) slice_wml = iaareaopen(img_wml[current_slice],method_threshold) #ignores regions that do not fit on a unitary radius disk prob_mask_pred = slice_wml mask_pred_label = ialabel(slice_wml) # mask with lesions nrois = len(np.unique(mask_pred_label))-1 # background for id_les in arange(0,nrois): roi = zeros_like(slice_wml) roi[mask_pred_label==id_les+1] = 1 prob_mask_pred[roi>0] = prob_mask_pred[roi>0].mean() if iadist(roi>0,iasedisk(1),'EUCLIDEAN').max()<2: # se cabe um disco de raio unitário slice_wml[roi]=0 #updates slice img_wml[current_slice] = slice_wml #if there are lesion pixels if (slice_wml.sum() > 0): data_userid_slice, n_pixels_wml_slice, n_pixels_used_wm_not_wml_slice, n_total_pixels_wm_slice = extract_attributes_slice (user_id, flag_training_or_testing, img_org, img_wm, slice_wml, current_slice, slices) if (len(data_userid_slice) != 0): data_userid += data_userid_slice n_pixels_wml += n_pixels_wml_slice n_pixels_used_wm_not_wml += n_pixels_used_wm_not_wml_slice n_total_pixels_wm += n_total_pixels_wm_slice #prints data about the pixels write_line("Patient ID: " + str(user_id)) write("Number of wml Pixels: " + str(n_pixels_wml)) write("Number of wm and not wml Pixels: " + str(n_pixels_used_wm_not_wml)) write("Number of wm Pixels: " + str(n_total_pixels_wm)) write_line("Number of Pixels in the image: " + str(slices*size_slice*size_slice)) #adds user id data to total data return data_userid ########################################################### ########################################################### #Function: perform_parallel_training #Goal: extracts data for the patients in the training set #Input: id_list #Output: data (lista 2D (Nx12) contendo atributos) ########################################################### ########################################################### def perform_parallel_training(id_list): #prints operation mode (flag) write_line("Operation mode: " + str(operation_mode)) data_array_return = Parallel(n_jobs=num_cores)(delayed(extract_attributes_training)(user_id) for user_id in id_list) data = [] for data_element in data_array_return: data = data + data_element #total number of wm pixels and wml pixels data = np.array(data) data_wml = data[data[:,-1]==1] data_nao_wml = data[data[:,-1]==0] n_pixels_wml = len(data_wml) n_pixels_used_wm_not_wml = len(data_nao_wml) #if the mode is not 0 #randomly reduces the set of pixels to fit the model if (operation_mode != 0): #if the number of wml pixels is less than the desired amount if (n_pixels_used_wm_not_wml > number_times_wm_greater_than_wml*n_pixels_wml): number_desired_pixels_wm_and_not_wml = (number_times_wm_greater_than_wml * n_pixels_wml) data_nao_wml_randomized = random.permutation(data_nao_wml) data_nao_wml = data_nao_wml_randomized[0:number_desired_pixels_wm_and_not_wml] n_pixels_wml = len(data_wml) data = concatenate((data_wml,data_nao_wml), axis=0) data = data.tolist() #end of data processing #prints the results of the used pixels write_line("End of the training:") write("Total number of pixels wml: " + str(n_pixels_wml)) write_line("Total number of pixels wm and not wml: " + str(n_pixels_used_wm_not_wml)) #transform the date into a numpy array data = np.array(data) #prints the size of the data write("Size of data: " + str(data.shape)) #returns the data return data ################################################################################ ################################################################################ #Function: extract_attributes_testing #Goal: extracts data for the patients in the training set #Input: id_list #Output: slices, img_org, img_wml, data (lista 2D (Nx12) contendo atributos) ################################################################################ ################################################################################ def extract_attributes_testing(id_list): data = [] #testing flag_training_or_testing = 1 for user_id in id_list: img_org, img_wm, img_wml = read_dcm(user_id) slices = img_org.shape[0] #initialize variables n_pixels_wml = 0 n_pixels_used_wm_not_wml = 0 n_total_pixels_wm = 0 #analyse an individual slices data_userid = [] img_org, img_wm, img_wml = generate_images_pre_processing(img_org, img_wm, img_wml) for current_slice in xrange(slices): #the method ignores regions with less than a specified number of pixels of lesion (prediction_matrix) slice_wml = iaareaopen(img_wml[current_slice],method_threshold) #the method ignores regions that do not fit on a unitary radius disk prob_mask_pred = slice_wml mask_pred_label = ialabel(slice_wml) # mask with lesions nrois = len(np.unique(mask_pred_label))-1 # background for id_les in arange(0,nrois): roi = zeros_like(slice_wml) roi[mask_pred_label==id_les+1] = 1 prob_mask_pred[roi>0] = prob_mask_pred[roi>0].mean() if iadist(roi>0,iasedisk(1),'EUCLIDEAN').max()<2: # se cabe um disco de raio unitário slice_wml[roi]=0 #updates slice img_wml[current_slice] = slice_wml #if there are lesion pixels if (slice_wml.sum() > 0): data_userid_slice, n_pixels_wml_slice, n_pixels_used_wm_not_wml_slice, n_total_pixels_wm_slice = extract_attributes_slice (user_id, flag_training_or_testing, img_org, img_wm, slice_wml, current_slice, slices) if (len(data_userid_slice) != 0): data_userid += data_userid_slice n_pixels_wml += n_pixels_wml_slice n_pixels_used_wm_not_wml += n_pixels_used_wm_not_wml_slice n_total_pixels_wm += n_total_pixels_wm_slice if (len(data_userid) == 0): write_line("ID " + str(user_id) + ": There are no wml pixels after the pre-processing") data.append("nan") else: #prints data about the pixels write_line("Patient ID: " + str(user_id)) write("Number of wml Pixels: " + str(n_pixels_wml)) write("Number of wm and not wml Pixels: " + str(n_pixels_used_wm_not_wml)) write("Number of wm Pixels: " + str(n_total_pixels_wm)) write_line("Number of Pixels in the image: " + str(slices*size_slice*size_slice)) #adds user id data to total data data = data + data_userid #end of data processing #prints the results of all pixels write_line("End of testing for ID: " + str(user_id)) write("Total of wml Pixels: " + str(n_pixels_wml)) write_line("Total of wm and not wml Pixels: " + str(n_pixels_used_wm_not_wml)) #transform the data in a numpy array data = np.array(data) #prints the size of the matrix write("Size of data: " + str(data.shape)) #returns the data return (slices, img_org, img_wml, data) ###################################################################################################################################### ###################################################################################################################################### #Function: perform_parallel_testing #Goal: extract features, calculates accuracy, calculates dice with and without pos-processing and calls support functions #Input: user_id, clf #Output: user_id, accuracy, average_dice_without_post, dice_std_sem_pos, average_dice_with_post, dice_std_com_pos ###################################################################################################################################### ###################################################################################################################################### def perform_parallel_testing(user_id, clf1, clf2, clf3, algorithm): list_user_id_testing = [user_id] #extract features slices, img_org, img_wml, data_testing = extract_attributes_testing(list_user_id_testing) if (data_testing[0] == "nan"): write_line("User ID: " + str(user_id) + " | There are no wml Pixels after the pre-processment") return (user_id, "nan", "nan", "nan", "nan", "nan", "nan", "nan", "nan", "nan", "nan") else: if (algorithm == 0): x_testing = data_testing[:,4:-1] y_testing = data_testing[:,-1].astype(int) #classifying the testing set write_line("Classifying using SVM...") y_prediction1 = clf1.predict_proba(x_testing) #array with the final prediction (0 or 1) prediction_size = len(y_prediction1) y_prediction_final = (np.zeros(prediction_size)).astype(bool) #determines what is lesion and what is not lesion based on the threshold of the classifier for i in xrange(prediction_size): if (y_prediction1[i][1] >= threshold_lesion_SVM): y_prediction_final[i]=1 else: y_prediction_final[i]=0 elif (algorithm == 1): x_testing = data_testing[:,4:-1] y_testing = data_testing[:,-1].astype(int) #classifying the testing set write_line("Classifying using Random Forest...") y_prediction1 = clf1.predict_proba(x_testing) #array with the final prediction (0 or 1) prediction_size = len(y_prediction1) y_prediction_final = (np.zeros(prediction_size)).astype(bool) #determines what is lesion and what is not lesion based on the threshold of the classifier for i in xrange(prediction_size): if (y_prediction1[i][1] >= threshold_lesion_RF): y_prediction_final[i]=1 else: y_prediction_final[i]=0 elif (algorithm == 2): x_testing = data_testing[:,4:-1] x_testing_normalized = preprocessing.normalize(x_testing) y_testing = data_testing[:,-1].astype(int) #classifying the testing set write_line("Classifying using kNN...") y_prediction1 = clf1.predict_proba(x_testing_normalized) #array with the final prediction (0 or 1) prediction_size = len(y_prediction1) y_prediction_final = (np.zeros(prediction_size)).astype(bool) #determines what is lesion and what is not lesion based on the threshold of the classifier for i in xrange(prediction_size): if (y_prediction1[i][1] >= threshold_lesion_kNN): y_prediction_final[i]=1 else: y_prediction_final[i]=0 elif (algorithm == 3): #normalizes the testing set #[user id, slice, x, y, intensity, inferior slice intensity, superior slice intensity, lbp, grad, mgrad, average] x_testing = data_testing[:,4:-1] x_testing_normalized = preprocessing.normalize(x_testing) y_testing = data_testing[:,-1].astype(int) #predictions write_line("Classifying using SVM...") y_prediction1 = clf1.predict_proba(x_testing) write_line("Classifying using RF...") y_prediction2 = clf2.predict_proba(x_testing) write_line("Classifying using kNN...") y_prediction3 = clf3.predict_proba(x_testing_normalized) #array with the final prediction (0 or 1) prediction_size = len(y_prediction1) y_prediction_final = (np.zeros(prediction_size)).astype(bool) #determines what is lesion and what is not lesion based on the threshold of the classifier for i in xrange(prediction_size): if (y_prediction1[i][1] >= 0.7 or (y_prediction1[i][1] >= 0.65 and y_prediction2[i][1] >= 0.45 and y_prediction3[i][1] >= 0.45) or (y_prediction1[i][1] >= 0.5 and y_prediction2[i][1] >= 0.5 and y_prediction3[i][1] >= 0.5)): y_prediction_final[i]=1 else: y_prediction_final[i]=0 #array with prediction probabilities using SVM results y_prediction_final_probabilidade = (np.zeros(prediction_size)).astype(float) for i in xrange(prediction_size): y_prediction_final_probabilidade[i]=y_prediction1[i][1].astype(float) #confusion matrix cm = confusion_matrix(y_testing, y_prediction_final) write("Confusion Matrix:") print cm print line execution_log.write("["+ str(cm[0][0]) + " " +str(cm[0][1]) + "]"+"\n"+"[" + str(cm[1][0]) + " " + str(cm[1][1]) + "]"+"\n" + line + "\n") write("Result for ID " + str(user_id) + ":") write("True Negatives: " + str(cm[0][0])) #true negative write("False Positives: " + str(cm[0][1])) #false positive write("False Negatives: " + str(cm[1][0])) #false negative write("True Positives: " + str(cm[1][1])) #true positive write_double_line("Total of evaluated pixels: " + str(len(y_testing))) #Information obtained using the confusion matrix total_cm = ((cm[0][0] + cm[1][1] + cm[1][0] + cm[0][1])*1.0) trueNegatives = (cm[0][0]*1.0) falsePositives = (cm[0][1]*1.0) falseNegatives = (cm[1][0]*1.0) truePositives = (cm[1][1]*1.0) #Accuracy accuracy = ((trueNegatives + truePositives)/total_cm) write_line("User ID: " + str(user_id) + " | Acurácia: " + str(format(accuracy, "5.3f"))) write_line("Error rate: " + str(format(((falseNegatives+falsePositives)/total_cm), "5.3f"))) #sensibility (true positive rate) write_line("Sensibility: " + str(format((truePositives/(truePositives+falseNegatives)), "5.3f"))) #specificity (true negative rate) write_line("Specificity: " + str(format((trueNegatives/(trueNegatives+falsePositives)), "5.3f"))) #precision (true positive rate) write_line("Precision: " + str(format((truePositives/(truePositives+falsePositives)), "5.3f"))) #prevalence (true positive rate) write_line("Prevalence: " + str(format(((falseNegatives+truePositives)/total_cm), "5.3f"))) ################################################ #BINARY LESION MATRIX AND PROBABILITY MATRIX ################################################ #matrix where pixels with a lesion have "1" and pixels without a lesion have value "0" prediction_matrix = (np.zeros_like(img_wml)).astype(bool) #matrix with probability of a pixel being a lesion (between 0 and 1) prediction_probability_matrix = (np.zeros_like(img_wml)).astype(float) line_prediction = 0 for line_data in data_testing: arg1 = line_data[1].astype(uint8) arg2 = line_data[2].astype(uint8) arg3 = line_data[3].astype(uint8) prediction_probability_matrix[arg1][arg2][arg3] = y_prediction_final_probabilidade[line_prediction] if (y_prediction_final[line_prediction] == 1): prediction_matrix[arg1][arg2][arg3] = 1 line_prediction+=1 prediction_matrix_without_post_processing = prediction_matrix #Dice #Calculates the dice using the prediction image and the original image print "Calculating dice..." print line dice = [] for current_slice in xrange(slices): #The operation requires that there are lesion pixels in the slices if (img_wml[current_slice].sum() > 0): ds = calculate_dice_slice(img_wml[current_slice], prediction_matrix[current_slice]) dice.append(ds) dice = np.asarray(dice) average_dice_without_post = dice.mean() dice_std_sem_pos = dice.std() write_line("User ID: " + str(user_id) + " | Dice: " + str(format(average_dice_without_post, "5.3f"))) print "Calculating dice with post-processing..." print line dice = [] prediction_matrix_with_post_processing = (np.zeros_like(prediction_matrix)).astype(bool) for current_slice in xrange(slices): #The operation requires that there are lesion pixels in the slices if (img_wml[current_slice].sum() > 0): #applies post-processing algorithms to the prediction matrix slice_prediction_matrix_with_post_processing = generate_slice_post_processing(prediction_matrix[current_slice]) prediction_matrix_with_post_processing[current_slice] = slice_prediction_matrix_with_post_processing ds = calculate_dice_slice(img_wml[current_slice], slice_prediction_matrix_with_post_processing) dice.append(ds) dice_array = dice dice = np.asarray(dice) average_dice_with_post = dice.mean() dice_std_com_pos = dice.std() ############### #3D Mosaics ############### if (bool_generate_mosaics == 1): generate_mosaics(user_id, img_wml, prediction_matrix_without_post_processing, prediction_matrix_with_post_processing) ################ #Color Maps ################ if (bool_generate_color_maps == 1): #Color Maps with probabilities if (user_id == desired_user_id1): generate_color_maps(user_id, img_org, img_wml, prediction_probability_matrix, prediction_matrix_without_post_processing, prediction_matrix_with_post_processing, desired_slice1) if (user_id == desired_user_id2): generate_color_maps(user_id, img_org, img_wml, prediction_probability_matrix, prediction_matrix_without_post_processing, prediction_matrix_with_post_processing, desired_slice2) write_line("User ID: " + str(user_id) + " | Dice with post-processing: " + str(format(average_dice_with_post, "5.3f")) + " | std: " + str(format(dice_std_com_pos, "5.3f"))) return (user_id, accuracy, average_dice_without_post, dice_std_sem_pos, average_dice_with_post, dice_std_com_pos, dice_array, cm[0][0], cm[0][1], cm[1][0], cm[1][1]) ####################################################################### ####################################################################### #Function: return_data_training #Goal: returns features and results fot the data in the training set #Input: data_training,percentage_data #Output: x_training, y_training ####################################################################### ####################################################################### def return_data_training(data_training,percentage_data): size_data = (percentage_data*1.0/100) fim = (int) (data_training.shape[0]*size_data) #permutes data to select the desired amount of samples data_training = random.permutation(data_training) x_training = data_training[0:fim,4:-1] y_training = data_training[0:fim,-1].astype(int) return (x_training, y_training) ################################################# ################################################# #Function: return_classifier #Goal: returns the classifying function #Input: x_training, y_training, algorithm #Output: clf1, clf2, clf3 ################################################# ################################################# def return_classifier(x_training, y_training, algorithm): if (algorithm==0): #SVM #Training the classifier write_double_line("Training the classifier using SVM...") #time time_classifier = timeit.default_timer() svc = LinearSVC(C=10) clf = CalibratedClassifierCV(svc, cv=10) clf.fit(x_training, y_training) deltaTime = (timeit.default_timer() - time_classifier) write_double("Training using SVM finished in " + str(format(deltaTime, "5.2f")) + " seconds") return (clf, 0, 0) elif (algorithm==1): #Random Forest #Training the classifier write_double_line("Training the classifier using Random Forest...") #time time_classifier = timeit.default_timer() clf = RandomForestClassifier(n_jobs=-1) clf.fit(x_training, y_training) deltaTime = (timeit.default_timer() - time_classifier) write_double("TTraining using Random Forest finished in " + str(format(deltaTime, "5.2f")) + " seconds") return (clf, 0, 0) ''' importances = clf.feature_importances_ index = np.argsort(importances)[::-1] #feature ranking print("Feature ranking:") for f in range(x_training.shape[1]): print("%d. feature %d (%f)" % (f + 1, index[f], importances[index[f]])) ''' elif (algorithm==2): #kNN #Training the classifier write_double_line("Training the classifier using kNN...") #time time_classifier = timeit.default_timer() k=21 #number of neighbors #normalized data x_training_normalized = preprocessing.normalize(x_training) clf = neighbors.KNeighborsClassifier(n_neighbors=k, weights='distance',n_jobs=-1) clf.fit(x_training_normalized, y_training) deltaTime = (timeit.default_timer() - tempo) write_double("Training using kNN finished in " + str(format(deltaTime, "5.2f")) + " seconds") return (clf, 0, 0) elif (algorithm==3): #SVM #Training the classifier write_double_line("Training the classifier using SVM...") #time time_classifier = timeit.default_timer() svc = LinearSVC(C=10) clf1 = CalibratedClassifierCV(svc, cv=10) clf1.fit(x_training, y_training) deltaTime = (timeit.default_timer() - time_classifier) write_double("Training using SVM finished in " + str(format(deltaTime, "5.2f")) + " seconds") #Random Forest #Training the classifier write_double_line("Training the classifier using Random Forest..") #time time_classifier = timeit.default_timer() clf2 = RandomForestClassifier(n_jobs=-1) clf2.fit(x_training, y_training) deltaTime = (timeit.default_timer() - time_classifier) write_double("Training using Random Forest finished in " + str(format(deltaTime, "5.2f")) + " seconds") #kNN #Training the classifier write_double_line("Training the classifier using kNN...") #time time_classifier = timeit.default_timer() k=21 #number of neighbors #data normalized x_training_normalized = preprocessing.normalize(x_training) clf3 = neighbors.KNeighborsClassifier(n_neighbors=k, weights='distance',n_jobs=-1) clf3.fit(x_training_normalized, y_training) deltaTime = (timeit.default_timer() - time_classifier) write_double("Training using kNN finished in " + str(format(deltaTime, "5.2f")) + " seconds") return (clf1, clf2, clf3) else: sys.exit(1) %%HTML <h1>Global Variables</h1> #lines line = "-------------" big_line = "------------------------------" msg = "" #counts the number of CPUs in the computer num_cores = multiprocessing.cpu_count() #parameters of the attribute extracion function radius = 5 #raio do lbp n_points = (5*radius) method = 'nri_uniform' size_cross_1 = 1 size_cross_2 = 2 #number of times the number of wm pixels can be grater than the number of wml pixels number_times_wm_greater_than_wml = 1 #size of the slice size_slice = 230 possible_algorithms = [0,1,2,3] possible_operation_modes = [0,1,2,3,4] %%HTML <h1>File Paths</h1> #folders path_miccai_images_folder = "miccai_images" path_color_maps_folder = "results/color_map/" path_box_plot_folder = "results/boxplot/Boxplot" path_mosaics_folder = "results/imagens_wml/" #files path_execution_log = "results/execution_log.txt" path_execution_results = "results/execution_results.txt" %%HTML <h1>User Defined Variables</h1> #operation mode operation_mode = 4 #operation_mode = 0 -> uses all the pixels "wml" and "wm not wml" pixels #operation_mode = 1 -> uses the same number of "wml" pixels and "wm not wml" pixel #operation_mode = 2 -> dilation of "wml" and uses the same number of "wml" pixels and "wm not wml" pixels #operation_mode = 3 -> erosion of "wm not wml" pixels and uses the same number of "wml" pixels and "wm not wml" pixels #operation_mode = 4 -> dilation of "wml" and erosion of "wm not wml" pixels and uses the same number of "wml" pixels and "wm not wml" pixels #chosen algorithm algorithm = 3 #algorithm 0: SVM #algorithm 1: Random Forest #algorithm 2: kNN #algorithm 3: usa os 3 algorithms #threshold for the lesions threshold_lesion_SVM = 0.55 threshold_lesion_RF = 0.9 threshold_lesion_kNN = 0.73 #method threshold method_threshold = 10 #colormap parameters desired_user_id1 = 3 desired_slice1 = 77 desired_user_id2 = 20 desired_slice2 = 26 #number of "data" samples used for training percentage_data = 20 #boolean variables to call output functions #0: do not call the function #1: call the function bool_generate_mosaics = 1 bool_generate_boxplot = 1 bool_generate_color_maps = 1 bool_generate_color_maps_show = 1 %%HTML <h1>Main</h1> #open files execution_log = open(path_execution_log, 'a') execution_results = open(path_execution_results, 'a') #program starts startTime = timeit.default_timer() print_infos_start_program() #initial setup total_confusion_matrix = np.array([[0,0],[0,0]]) dice_medio = 0.0 average_accuracy=0.0 #tests if the algorithm exists if (algorithm not in possible_algorithms): #algorithm inválido print "Erro, invalid algorithm" #suspends the program execution sys.exit(1) #tests if the operation mode exists if (operation_mode not in possible_operation_modes): #invalid mode print "Error, invalid operation mode" #suspends the program execution sys.exit(1) if (algorithm == 0): size_closed_area = 30 size_opened_area = 50 elif (algorithm == 1): size_closed_area = 30 size_opened_area = 50 elif (algorithm == 2): size_closed_area = 30 size_opened_area = 50 elif (algorithm == 3): size_closed_area = 30 size_opened_area = 50 #Training #list of possible ids id_list_training_mode1 = [8,10,11,12,13,16,17,18,19,21,22,24,26] id_list_testing_mode1 = [1,2,3,4,5,6,7,9,14,15,20,23,25,28] #id_list_training_mode1 = [8] #id_list_testing_mode1 = [1] list_modes = [] list_modes.append([id_list_training_mode1, id_list_testing_mode1]) #user_ids for training id_list_training = list_modes[0][0] id_list_testing = list_modes[0][1] #prints the list of patients for training and for testing print_lists_patients_training_and_test(id_list_training, id_list_testing) #start of the training write_line("Start of the training") #extract attributes from the training set data_training = perform_parallel_training(id_list_training) #returns features and results for the training data x_training, y_training = return_data_training(data_training,percentage_data) #trains the classifier using the especified algorithm clf1, clf2, clf3 = return_classifier(x_training, y_training, algorithm) #start of the testings msg = "Start of the testings" write_line(msg) dice_total_testing = [] #calculates the result of the testings in parallel results = Parallel(n_jobs=num_cores)(delayed(perform_parallel_testing)(user_id, clf1, clf2, clf3, algorithm) for user_id in id_list_testing) #eixo 0: user_id #eixo 1: accuracy #eixo 2: average dice without post-processing #eixo 3: standard deviation of the dice without post-processing #eixo 4: average dice with post-processing #eixo 5: standard deviation of the dice with post-processing #eixo 6: dice_array #number of patients in test with at least one wml num_elements_testing=0 #list of elements with at least one wml list_testing_wml = [] #eliminates the results with "nan" (low amount of wml pixels) results_final = [] for result in results: if (result[1] != "nan"): result_line = [result[0], result[1], result[2], result[3], result[4], result[5]] results_final.append(result_line) dice_total_testing.append(result[6]) list_testing_wml.append(result[0]) total_confusion_matrix[0][0] += result[7] total_confusion_matrix[0][1] += result[8] total_confusion_matrix[1][0] += result[9] total_confusion_matrix[1][1] += result[10] num_elements_testing+=1 #results of the testings for each patient #accuracy and dice with post-processing write_results(results_final) sum_results_testing = np.sum(results_final, axis=0) average_accuracy = (1.0*sum_results_testing[1]/num_elements_testing) average_dice_without_post = (1.0*sum_results_testing[2]/num_elements_testing) average_dice_with_post = (1.0*sum_results_testing[4]/num_elements_testing) write_double("Number of elements: " + str(num_elements_testing)) write_double("Average Accuracy of the testing set: " + str(format(average_accuracy, "5.3f"))) write_double("Average Dice of the testing set without pos-processing: " + str(format(average_dice_without_post, "5.3f"))) write_double("Average Dice of the testing set with pos-processing: " + str(format(average_dice_with_post, "5.3f"))) write_double(line) write_double("Complete Confusion Matrix:") write_double(line) write_double("["+ str(total_confusion_matrix[0][0]) + " " +str(total_confusion_matrix[0][1]) + "]"+"\n"+"[" + str(total_confusion_matrix[1][0]) + " " + str(total_confusion_matrix[1][1]) + "]"+"\n" + line) #Information obtained using the confusion matrix total_cm = ((total_confusion_matrix[0][0] + total_confusion_matrix[1][1] + total_confusion_matrix[1][0] + total_confusion_matrix[0][1])*1.0) trueNegatives = (total_confusion_matrix[0][0]*1.0) falsePositives = (total_confusion_matrix[0][1]*1.0) falseNegatives = (total_confusion_matrix[1][0]*1.0) truePositives = (total_confusion_matrix[1][1]*1.0) #accuracy accuracy = ((trueNegatives + truePositives)/total_cm) write_double("Final Accuracy: " + str(format(accuracy, "5.3f"))) write_double("Error rate: " + str(format(((falseNegatives+falsePositives)/total_cm), "5.3f"))) #sensibility (true positive rate) write_double("Sensibility: " + str(format((truePositives/(truePositives+falseNegatives)), "5.3f"))) #specificity (true negative rate) write_double("Specificity: " + str(format((trueNegatives/(trueNegatives+falsePositives)), "5.3f"))) #precision (true positive rate) write_double("Precision: " + str(format((truePositives/(truePositives+falsePositives)), "5.3f"))) #prevalence (true positive rate) write_double("Prevalence: " + str(format(((falseNegatives+truePositives)/total_cm), "5.3f"))) %%HTML <h1>Boxplot</h1> if (bool_generate_boxplot == 1): boxplot(dice_total_testing, list_testing_wml) %%HTML <h1>Color Maps</h1> if (bool_generate_color_maps_show == 1 and bool_generate_color_maps == 1): path1 = (path_color_maps_folder+str(desired_user_id1)+"/"+str(desired_slice1)) path2 = (path_color_maps_folder+str(desired_user_id2)+"/"+str(desired_slice2)) path_color_map1 = (path1+"/Original Image.png") img_color_map1 = matplotlib.image.imread(path_color_map1) plt.title("Original Image | Patient: "+str(desired_user_id1)+" | Slice: "+str(desired_slice1)) plt.imshow(img_color_map1) plt.show() path_color_map1 = (path1+"/WML Image.png") img_color_map1 = matplotlib.image.imread(path_color_map1) plt.title("WML Image | Patient: "+str(desired_user_id1)+" | Slice: "+str(desired_slice1)) plt.imshow(img_color_map1) plt.show() path_color_map1 = (path1+"/Prediction without post-processing.png") img_color_map1 = matplotlib.image.imread(path_color_map1) plt.title("Prediction without post-processing Image | Patient: "+str(desired_user_id1)+" | Slice: "+str(desired_slice1)) plt.imshow(img_color_map1) plt.show() path_color_map1 = (path1+"/Prediction with post-processing.png") img_color_map1 = matplotlib.image.imread(path_color_map1) plt.title("Prediction with post-processing Image | Patient: "+str(desired_user_id1)+" | Slice: "+str(desired_slice1)) plt.imshow(img_color_map1) plt.show() path_color_map1 = (path1+"/Color Probability.png") img_color_map1 = matplotlib.image.imread(path_color_map1) plt.imshow(img_color_map1) plt.title("Color Probability Image | Patient: "+str(desired_user_id1)+" | Slice: "+str(desired_slice1)) plt.show() if (bool_generate_color_maps_show == 1 and bool_generate_color_maps == 1): path2 = (path_color_maps_folder+str(desired_user_id2)+"/"+str(desired_slice2)) path_color_map2 = (path2+"/Original Image.png") img_color_map2 = matplotlib.image.imread(path_color_map2) plt.title("Original Image | Patient: "+str(desired_user_id2)+" | Slice: "+str(desired_slice2)) plt.imshow(img_color_map2) plt.show() path_color_map2 = (path2+"/WML Image.png") img_color_map2 = matplotlib.image.imread(path_color_map2) plt.title("WML Image | Patient: "+str(desired_user_id2)+" | Slice: "+str(desired_slice2)) plt.imshow(img_color_map2) plt.show() path_color_map2 = (path2+"/Prediction without post-processing.png") img_color_map2 = matplotlib.image.imread(path_color_map2) plt.title("Prediction without post-processing Image | Patient: "+str(desired_user_id2)+" | Slice: "+str(desired_slice2)) plt.imshow(img_color_map2) plt.show() path_color_map2 = (path2+"/Prediction with post-processing.png") img_color_map2 = matplotlib.image.imread(path_color_map1) plt.title("Prediction with post-processing Image | Patient: "+str(desired_user_id2)+" | Slice: "+str(desired_slice2)) plt.imshow(img_color_map1) plt.show() path_color_map2 = (path1+"/Color Probability.png") img_color_map2 = matplotlib.image.imread(path_color_map2) plt.imshow(img_color_map1) plt.title("Color Probability Image | Patient: "+str(desired_user_id2)+" | Slice: "+str(desired_slice2)) plt.show() %%HTML <h1>End of the Program</h1> write_double_fim() write_line("End of the program") deltaTime = (timeit.default_timer() - startTime) write_line_fim("Execution time: " + str(format(deltaTime, "5.3f")) + " seconds") close_files() ```
github_jupyter
# Ungraded Lab Part 2 - Consuming a Machine Learning Model Welcome to the second part of this ungraded lab! **Before going forward check that the server from part 1 is still running.** In this notebook you will code a minimal client that uses Python's `requests` library to interact with your running server. ``` import os import io import cv2 import requests import numpy as np from IPython.display import Image, display ``` ## Understanding the URL ### Breaking down the URL After experimenting with the fastAPI's client you may have noticed that we made all requests by pointing to a specific URL and appending some parameters to it. More concretely: 1. The server is hosted in the URL [http://localhost:8000/](http://localhost:8000/). 2. The endpoint that serves your model is the `/predict` endpoint. Also you can specify the model to use: `yolov3` or`yolov3-tiny`. Let's stick to the tiny version for computational efficiency. Let's get started by putting in place all this information. ``` base_url = 'http://localhost:8000' endpoint = '/predict' model = 'yolov3-tiny' confidence = 0.1 ``` To consume your model, you append the endpoint to the base URL to get the full URL. Notice that the parameters are absent for now. ``` url_with_endpoint_no_params = base_url + endpoint url_with_endpoint_no_params ``` To set any of the expected parameters, the syntax is to add a "?" character followed by the name of the parameter and its value. Let's do it and check how the final URL looks like: ``` full_url = url_with_endpoint_no_params + "?model=" + model + '&confidence=' + str(confidence) full_url ``` This endpoint expects both a model's name and an image. But since the image is more complex it is not passed within the URL. Instead we leverage the `requests` library to handle this process. # Sending a request to your server ### Coding the response_from_server function As a reminder, this endpoint expects a POST HTTP request. The `post` function is part of the requests library. To pass the file along with the request, you need to create a dictionary indicating the name of the file ('file' in this case) and the actual file. `status code` is a handy command to check the status of the response the request triggered. **A status code of 200 means that everything went well.** ``` def response_from_server(url, image_file, verbose=True): """Makes a POST request to the server and returns the response. Args: url (str): URL that the request is sent to. image_file (_io.BufferedReader): File to upload, should be an image. verbose (bool): True if the status of the response should be printed. False otherwise. Returns: requests.models.Response: Response from the server. """ files = {'file': image_file} response = requests.post(url, files=files) status_code = response.status_code if verbose: msg = "Everything went well!" if status_code == 200 else "There was an error when handling the request." print(msg) return response ``` To test this function, open a file in your filesystem and pass it as a parameter alongside the URL: ``` with open("images/clock2.jpg", "rb") as image_file: prediction = response_from_server(full_url, image_file) ``` Great news! The request was successful. However, you are not getting any information about the objects in the image. To get the image with the bounding boxes and labels, you need to parse the content of the response into an appropriate format. This process looks very similar to how you read raw images into a cv2 image on the server. To handle this step, let's create a directory called `images_predicted` to save the image to: ``` dir_name = "images_predicted" if not os.path.exists(dir_name): os.mkdir(dir_name) ``` ### Creating the display_image_from_response function ``` def display_image_from_response(response): """Display image within server's response. Args: response (requests.models.Response): The response from the server after object detection. """ image_stream = io.BytesIO(response.content) image_stream.seek(0) file_bytes = np.asarray(bytearray(image_stream.read()), dtype=np.uint8) image = cv2.imdecode(file_bytes, cv2.IMREAD_COLOR) filename = "image_with_objects.jpeg" cv2.imwrite(f'images_predicted/{filename}', image) display(Image(f'images_predicted/{filename}')) display_image_from_response(prediction) ``` Now you are ready to consume your object detection model through your own client! Let's test it out on some other images: ``` image_files = [ 'car2.jpg', 'clock3.jpg', 'apples.jpg' ] for image_file in image_files: with open(f"images/{image_file}", "rb") as image_file: prediction = response_from_server(full_url, image_file, verbose=False) display_image_from_response(prediction) ``` **Congratulations on finishing this ungraded lab!** Real life clients and servers have a lot more going on in terms of security and performance. However, the code you just experienced is close to what you see in real production environments. Hopefully, this lab served the purpose of increasing your familiarity with the process of deploying a Deep Learning model, and consuming from it. **Keep it up!** # ## Optional Challenge - Adding the confidence level to the request Let's expand on what you have learned so far. The next logical step is to extend the server and the client so that they can accommodate an additional parameter: the level of confidence of the prediction. **To test your extended implementation you must perform the following steps:** - Stop the server by interrupting the Kernel. - Extend the `prediction` function in the server. - Re run the cell containing your server code. - Re launch the server. - Extend your client. - Test it with some images (either with your client or fastAPI's one). Here are some hints that can help you out throughout the process: #### Server side: - The `prediction` function that handles the `/predict` endpoint needs an additional parameter to accept the confidence level. Add this new parameter before the `File` parameter. This is necessary because `File` has a default value and must be specified last. - `cv.detect_common_objects` accepts the `confidence` parameter, which is a floating point number (type `float`in Python). #### Client side: - You can add a new parameter to the URL by extending it with an `&` followed by the name of the parameter and its value. The name of this new parameter must be equal to the name used within the `prediction` function in the server. An example would look like this: `myawesomemodel.com/predict?model=yolov3-tiny&newParam=value` **You can do it!**
github_jupyter
TSG028 - Restart node manager on all storage pool nodes ======================================================= Description ----------- ### Parameters ``` container='hadoop' command=f'supervisorctl restart nodemanager' ``` ### Instantiate Kubernetes client ``` # Instantiate the Python Kubernetes client into 'api' variable import os try: from kubernetes import client, config from kubernetes.stream import stream if "KUBERNETES_SERVICE_PORT" in os.environ and "KUBERNETES_SERVICE_HOST" in os.environ: config.load_incluster_config() else: config.load_kube_config() api = client.CoreV1Api() print('Kubernetes client instantiated') except ImportError: from IPython.display import Markdown display(Markdown(f'HINT: Use [SOP059 - Install Kubernetes Python module](../install/sop059-install-kubernetes-module.ipynb) to resolve this issue.')) raise ``` ### Get the namespace for the big data cluster Get the namespace of the big data cluster from the Kuberenetes API. NOTE: If there is more than one big data cluster in the target Kubernetes cluster, then set \[0\] to the correct value for the big data cluster. ``` # Place Kubernetes namespace name for BDC into 'namespace' variable try: namespace = api.list_namespace(label_selector='MSSQL_CLUSTER').items[0].metadata.name except IndexError: from IPython.display import Markdown display(Markdown(f'HINT: Use [TSG081 - Get namespaces (Kubernetes)](../monitor-k8s/tsg081-get-kubernetes-namespaces.ipynb) to resolve this issue.')) display(Markdown(f'HINT: Use [TSG010 - Get configuration contexts](../monitor-k8s/tsg010-get-kubernetes-contexts.ipynb) to resolve this issue.')) display(Markdown(f'HINT: Use [SOP011 - Set kubernetes configuration context](../common/sop011-set-kubernetes-context.ipynb) to resolve this issue.')) raise print('The kubernetes namespace for your big data cluster is: ' + namespace) ``` ### Run command in containers ``` pod_list = api.list_namespaced_pod(namespace) for pod in pod_list.items: container_names = [container.name for container in pod.spec.containers] for container_name in container_names: if container_name == container: print (f"Pod: {pod.metadata.name} / Container: {container}:") try: output=stream(api.connect_get_namespaced_pod_exec, pod.metadata.name, namespace, command=['/bin/sh', '-c', command], container=container, stderr=True, stdout=True) print (output) except Exception: print (f"Failed to run {command} in container: {container} for pod: {pod.metadata.name}") print('Notebook execution complete.') ```
github_jupyter
``` # Notebook for ner results table import pandas as pd import numpy as np import json raw_path = '/notebook/ue/uncertainty-estimation/workdir/run_calc_ues_metrics/electra-metric/' #reg_path = '/data/gkuzmin/uncertainty-estimation/workdir/run_calc_ues_metrics/conll2003_electra_reg_01_fix/' ues = ['last', 'all', 'dpp', 'dpp_with_ood'] ues_names = ['MC', 'MC', 'DPP_on_masks', 'DPP_with_ood'] ues_layers = ['last', 'all', 'last', 'last'] metrics = ['rejection-curve-auc', 'rcc-auc', 'rpp'] metric_names = ['rejection-curve-auc', 'rcc-auc', 'rpp'] types = ['mrpc', 'cola', 'sst2'] types_names = ['MRPC', 'CoLA', 'SST2 (10%)'] ue_methods = ['max_prob', 'bald', 'sampled_max_prob', 'variance'] perc_metrics = ['rejection-curve-auc', 'rpp'] diff_metrics = ['rejection-curve-auc', 'roc-auc'] def get_df(raw_path, reg_type, baselines_dict={}, baselines=None): raw_dict = {} df_dict = {} for ue, ue_name in zip(ues, ues): #ue_path = raw_path + ue + '/' # enter row level raw_dict[ue_name] = {} df_dict[ue_name] = {} for ue_type in types: raw_dict[ue_name][ue_type] = {} for metric in metrics: ue_path = raw_path + ue_type + '/' + ue + '/' fname = ue_path + f'metrics_{metric}.json' with open(fname, 'r') as f: curr_metrics = json.loads(f.read()) metric_results = {} for ue_method in ue_methods: mean, std = np.mean(list(curr_metrics[ue_method].values())), np.std(list(curr_metrics[ue_method].values())) if metric in perc_metrics: mean, std = mean * 100, std * 100 if ue_method == 'max_prob': baseline = mean if baselines is None: baselines_dict[ue_type + metric + ue_method] = baseline else: baseline = baselines_dict[ue_type + metric + ue_method] if metric in diff_metrics and ue_method != 'max_prob': mean = mean - baseline value = '{:.{prec}f}'.format(mean, prec=2) + '$\\pm$' + '{:.{prec}f}'.format(std, prec=2) metric_results[ue_method] = value # so we obtained two dict for one metric raw_dict[ue_name][ue_type][metric] = metric_results # make buf dataframe type_df = pd.DataFrame.from_dict(raw_dict[ue_name][ue_type]) df_dict[ue_name][ue_type] = type_df dataset_dfs = [pd.concat([df_dict[ue][ue_type] for ue in ues]) for ue_type in types] # make multiindex for idx, df in enumerate(dataset_dfs): df.columns = pd.MultiIndex.from_tuples([(types_names[idx], metric) for metric in metrics]) dataset_dfs[idx] = df #token_df.columns = pd.MultiIndex.from_tuples([('CoNNL-2003 (10%, token level)', metric) for metric in metrics]) #seq_df.columns = pd.MultiIndex.from_tuples([('CoNNL-2003 (10%, sequence level)', metric) for metric in metrics]) raw_df = pd.concat(dataset_dfs, axis=1) # after rename max_prob column to baseline and drop all max_prob columns max_prob_rows = raw_df.loc['max_prob'] if len(max_prob_rows) != len(metrics) * len(types_names) or len(types_names) == 1: buf_max_prob = raw_df.loc['max_prob'].drop_duplicates().loc['max_prob'] else: buf_max_prob = raw_df.loc['max_prob'] raw_df.drop('max_prob', inplace=True) raw_df.loc['max_prob'] = buf_max_prob names_df = pd.DataFrame() methods = [] for ue in ues_names: methods += [ue] * (len(ue_methods) - 1) methods += ['Baseline'] layers = [] for ue in ues_layers: layers += [ue] * (len(ue_methods) - 1) layers += ['-'] reg_type = [reg_type] * len(raw_df) names_df['Method'] = methods names_df['Reg. Type'] = reg_type # names_df['Dropout Layers'] = layers names_df['UE Score'] = raw_df.index names_df.index = raw_df.index raw_df = pd.concat([names_df, raw_df], axis=1) return raw_df, baselines_dict ``` # Final tables ``` raw_path = '/home/jovyan/uncertainty-estimation/workdir/run_calc_ues_metrics/mixup_electra/' #reg_path = '/data/gkuzmin/uncertainty-estimation/workdir/run_calc_ues_metrics/conll2003_electra_reg_01_fix/' ues = ['msd/all', 'msd/last'] ues_names = ['MSD|all', 'MSD|last'] ues_layers = ['all', 'last', 'last'] metrics = ['rcc-auc', 'rpp'] metric_names = ['rcc-auc', 'rpp'] types = ['mrpc', 'cola', 'sst2'] types_names = ['MRPC', 'CoLA', 'SST2 (10%)'] ue_methods = ['max_prob', 'mixup'] perc_metrics = ['rejection-curve-auc', 'rpp'] diff_metrics = ['rejection-curve-auc', 'roc-auc'] # copied from table baselines_dict = {'mrpcrejection-curve-aucmax_prob': 0.9208435457516339 * 100, 'mrpcrcc-aucmax_prob': 23.279293481630972, 'mrpcrppmax_prob': 0.026788574907087016 * 100, 'colarejection-curve-aucmax_prob': 0.9203619367209971 * 100, 'colarcc-aucmax_prob': 59.03726591032054, 'colarppmax_prob': 0.02631936969193335 * 100, 'sst2rejection-curve-aucmax_prob': 0.9379778287461774 * 100, 'sst2rcc-aucmax_prob': 18.067838464295736, 'sst2rppmax_prob': 0.012349462026204303 * 100} raw_df, baselines_dict = get_df(raw_path, 'MSD', baselines_dict, True) miscl_df = raw_df miscl_df.reset_index(inplace=True, drop=True) latex_table = miscl_df.to_latex(bold_rows=False, index=False) latex_table = latex_table.replace('\\$\\textbackslash pm\\$', '$\pm$') latex_table = latex_table.replace('variance', 'PV') latex_table = latex_table.replace('var\_ratio', 'VR') latex_table = latex_table.replace('sampled\_entropy', 'SE') latex_table = latex_table.replace('sampled\_max\_prob', 'SMP') latex_table = latex_table.replace('mahalanobis\_distance', 'MD') latex_table = latex_table.replace('max\_prob', 'MP') latex_table = latex_table.replace('bald', 'BALD') print(latex_table) raw_path = '/notebook/ue/uncertainty-estimation/workdir/run_calc_ues_metrics/metric_opt_electra_3hyp/' #reg_path = '/data/gkuzmin/uncertainty-estimation/workdir/run_calc_ues_metrics/conll2003_electra_reg_01_fix/' ues = ['maha_mc'] ues_names = ['MD'] ues_layers = ['-'] metrics = ['rejection-curve-auc', 'rcc-auc', 'rpp'] metric_names = ['rejection-curve-auc', 'rcc-auc', 'rpp'] types = ['cola']#['mrpc', 'sst2']#['mrpc', 'cola', 'sst2'] types_names = ['cola']#['MRPC', 'SST2 (10%)']#['MRPC', 'CoLA', 'SST2 (10%)'] ue_methods = ['max_prob', 'mahalanobis_distance', 'sampled_mahalanobis_distance'] perc_metrics = ['rejection-curve-auc', 'rpp'] diff_metrics = ['rejection-curve-auc', 'roc-auc'] # copied from table baselines_dict = {'mrpcrejection-curve-aucmax_prob': 0.9208435457516339 * 100, 'mrpcrcc-aucmax_prob': 23.279293481630972, 'mrpcrppmax_prob': 0.026788574907087016 * 100, 'colarejection-curve-aucmax_prob': 0.9203619367209971 * 100, 'colarcc-aucmax_prob': 59.03726591032054, 'colarppmax_prob': 0.02631936969193335 * 100, 'sst2rejection-curve-aucmax_prob': 0.9379778287461774 * 100, 'sst2rcc-aucmax_prob': 18.067838464295736, 'sst2rppmax_prob': 0.012349462026204303 * 100} raw_df, baselines_dict = get_df(raw_path, 'metric', baselines_dict, True) miscl_df = raw_df miscl_df.reset_index(inplace=True, drop=True) latex_table = miscl_df.to_latex(bold_rows=False, index=False) latex_table = latex_table.replace('\\$\\textbackslash pm\\$', '$\pm$') latex_table = latex_table.replace('variance', 'PV') latex_table = latex_table.replace('var\_ratio', 'VR') latex_table = latex_table.replace('sampled\_entropy', 'SE') latex_table = latex_table.replace('sampled\_max\_prob', 'SMP') latex_table = latex_table.replace('mahalanobis\_distance', 'MD') latex_table = latex_table.replace('sampled\_MD', 'SMD') latex_table = latex_table.replace('max\_prob', 'MP') latex_table = latex_table.replace('bald', 'BALD') print(latex_table) raw_path = '/notebook/ue/uncertainty-estimation/workdir/run_calc_ues_metrics/metric_opt_electra_3hyp/' #reg_path = '/data/gkuzmin/uncertainty-estimation/workdir/run_calc_ues_metrics/conll2003_electra_reg_01_fix/' ues = ['maha_sn_mc'] ues_names = ['MD SN (Ours)'] ues_layers = ['-'] metrics = ['rejection-curve-auc', 'rcc-auc', 'rpp'] metric_names = ['rejection-curve-auc', 'rcc-auc', 'rpp'] types = ['cola']#['mrpc', 'sst2']#['mrpc', 'cola', 'sst2'] types_names = ['CoLA']#['MRPC', 'SST2 (10%)']#['MRPC', 'CoLA', 'SST2 (10%)'] ue_methods = ['max_prob', 'mahalanobis_distance', 'sampled_mahalanobis_distance'] perc_metrics = ['rejection-curve-auc', 'rpp'] diff_metrics = ['rejection-curve-auc', 'roc-auc'] # copied from table baselines_dict = {'mrpcrejection-curve-aucmax_prob': 0.9208435457516339 * 100, 'mrpcrcc-aucmax_prob': 23.279293481630972, 'mrpcrppmax_prob': 0.026788574907087016 * 100, 'colarejection-curve-aucmax_prob': 0.9203619367209971 * 100, 'colarcc-aucmax_prob': 59.03726591032054, 'colarppmax_prob': 0.02631936969193335 * 100, 'sst2rejection-curve-aucmax_prob': 0.9379778287461774 * 100, 'sst2rcc-aucmax_prob': 18.067838464295736, 'sst2rppmax_prob': 0.012349462026204303 * 100} raw_df, baselines_dict = get_df(raw_path, 'metric', baselines_dict, True) miscl_df = raw_df miscl_df.reset_index(inplace=True, drop=True) latex_table = miscl_df.to_latex(bold_rows=False, index=False) latex_table = latex_table.replace('\\$\\textbackslash pm\\$', '$\pm$') latex_table = latex_table.replace('variance', 'PV') latex_table = latex_table.replace('var\_ratio', 'VR') latex_table = latex_table.replace('sampled\_entropy', 'SE') latex_table = latex_table.replace('sampled\_max\_prob', 'SMP') latex_table = latex_table.replace('mahalanobis\_distance', 'MD') latex_table = latex_table.replace('sampled\_MD', 'SMD') latex_table = latex_table.replace('max\_prob', 'MP') latex_table = latex_table.replace('bald', 'BALD') print(latex_table) # MRPC with new pars, maha raw_path = '/notebook/ue/uncertainty-estimation/workdir/run_calc_ues_metrics/metric_opt_electra_fix/' #reg_path = '/data/gkuzmin/uncertainty-estimation/workdir/run_calc_ues_metrics/conll2003_electra_reg_01_fix/' ues = ['maha_mc'] ues_names = ['MD'] ues_layers = ['-'] metrics = ['rejection-curve-auc', 'rcc-auc', 'rpp'] metric_names = ['rejection-curve-auc', 'rcc-auc', 'rpp'] types = ['mrpc'] types_names = ['MRPC'] ue_methods = ['max_prob', 'mahalanobis_distance', 'sampled_mahalanobis_distance'] perc_metrics = ['rejection-curve-auc', 'rpp'] diff_metrics = ['rejection-curve-auc', 'roc-auc'] # copied from table baselines_dict = {'mrpcrejection-curve-aucmax_prob': 0.9208435457516339 * 100, 'mrpcrcc-aucmax_prob': 23.279293481630972, 'mrpcrppmax_prob': 0.026788574907087016 * 100, 'colarejection-curve-aucmax_prob': 0.9203619367209971 * 100, 'colarcc-aucmax_prob': 59.03726591032054, 'colarppmax_prob': 0.02631936969193335 * 100, 'sst2rejection-curve-aucmax_prob': 0.9379778287461774 * 100, 'sst2rcc-aucmax_prob': 18.067838464295736, 'sst2rppmax_prob': 0.012349462026204303 * 100} raw_df, baselines_dict = get_df(raw_path, 'metric', baselines_dict, True) miscl_df = raw_df miscl_df.reset_index(inplace=True, drop=True) latex_table = miscl_df.to_latex(bold_rows=False, index=False) latex_table = latex_table.replace('\\$\\textbackslash pm\\$', '$\pm$') latex_table = latex_table.replace('variance', 'PV') latex_table = latex_table.replace('var\_ratio', 'VR') latex_table = latex_table.replace('sampled\_entropy', 'SE') latex_table = latex_table.replace('sampled\_max\_prob', 'SMP') latex_table = latex_table.replace('mahalanobis\_distance', 'MD') latex_table = latex_table.replace('sampled\_MD', 'SMD') latex_table = latex_table.replace('max\_prob', 'MP') latex_table = latex_table.replace('bald', 'BALD') print(latex_table) # MRPC with new pars, maha raw_path = '/notebook/ue/uncertainty-estimation/workdir/run_calc_ues_metrics/metric_opt_electra_fix6/' #reg_path = '/data/gkuzmin/uncertainty-estimation/workdir/run_calc_ues_metrics/conll2003_electra_reg_01_fix/' ues = ['maha_mc'] ues_names = ['MD'] ues_layers = ['-'] metrics = ['rejection-curve-auc', 'rcc-auc', 'rpp'] metric_names = ['rejection-curve-auc', 'rcc-auc', 'rpp'] types = ['mrpc'] types_names = ['MRPC'] ue_methods = ['max_prob', 'mahalanobis_distance', 'sampled_mahalanobis_distance'] perc_metrics = ['rejection-curve-auc', 'rpp'] diff_metrics = ['rejection-curve-auc', 'roc-auc'] # copied from table baselines_dict = {'mrpcrejection-curve-aucmax_prob': 0.9208435457516339 * 100, 'mrpcrcc-aucmax_prob': 23.279293481630972, 'mrpcrppmax_prob': 0.026788574907087016 * 100, 'colarejection-curve-aucmax_prob': 0.9203619367209971 * 100, 'colarcc-aucmax_prob': 59.03726591032054, 'colarppmax_prob': 0.02631936969193335 * 100, 'sst2rejection-curve-aucmax_prob': 0.9379778287461774 * 100, 'sst2rcc-aucmax_prob': 18.067838464295736, 'sst2rppmax_prob': 0.012349462026204303 * 100} raw_df, baselines_dict = get_df(raw_path, 'metric', baselines_dict, True) miscl_df = raw_df miscl_df.reset_index(inplace=True, drop=True) latex_table = miscl_df.to_latex(bold_rows=False, index=False) latex_table = latex_table.replace('\\$\\textbackslash pm\\$', '$\pm$') latex_table = latex_table.replace('variance', 'PV') latex_table = latex_table.replace('var\_ratio', 'VR') latex_table = latex_table.replace('sampled\_entropy', 'SE') latex_table = latex_table.replace('sampled\_max\_prob', 'SMP') latex_table = latex_table.replace('mahalanobis\_distance', 'MD') latex_table = latex_table.replace('sampled\_MD', 'SMD') latex_table = latex_table.replace('max\_prob', 'MP') latex_table = latex_table.replace('bald', 'BALD') print(latex_table) # New table for MRPC raw_path = '/notebook/ue/uncertainty-estimation/workdir/run_calc_ues_metrics/metric_opt_electra_fix6/' #reg_path = '/data/gkuzmin/uncertainty-estimation/workdir/run_calc_ues_metrics/conll2003_electra_reg_01_fix/' ues = ['all', 'dpp', 'dpp_with_ood'] ues_names = ['MC', 'DDPP (+DPP) (Ours)', 'DDPP (+OOD) (Ours)'] ues_layers = ['all', 'last', 'last'] metrics = ['rejection-curve-auc', 'rcc-auc', 'rpp'] metric_names = ['rejection-curve-auc', 'rcc-auc', 'rpp'] types = ['mrpc'] types_names = ['MRPC'] ue_methods = ['max_prob', 'bald', 'sampled_max_prob', 'variance'] perc_metrics = ['rejection-curve-auc', 'rpp'] diff_metrics = ['rejection-curve-auc', 'roc-auc'] # copied from table baselines_dict = {'mrpcrejection-curve-aucmax_prob': 0.9208435457516339 * 100, 'mrpcrcc-aucmax_prob': 23.279293481630972, 'mrpcrppmax_prob': 0.026788574907087016 * 100, 'colarejection-curve-aucmax_prob': 0.9203619367209971 * 100, 'colarcc-aucmax_prob': 59.03726591032054, 'colarppmax_prob': 0.02631936969193335 * 100, 'sst2rejection-curve-aucmax_prob': 0.9379778287461774 * 100, 'sst2rcc-aucmax_prob': 18.067838464295736, 'sst2rppmax_prob': 0.012349462026204303 * 100} raw_df, baselines_dict = get_df(raw_path, 'metric', baselines_dict, True) miscl_df = raw_df miscl_df.reset_index(inplace=True, drop=True) latex_table = miscl_df.to_latex(bold_rows=False, index=False) latex_table = latex_table.replace('\\$\\textbackslash pm\\$', '$\pm$') latex_table = latex_table.replace('variance', 'PV') latex_table = latex_table.replace('var\_ratio', 'VR') latex_table = latex_table.replace('sampled\_entropy', 'SE') latex_table = latex_table.replace('sampled\_max\_prob', 'SMP') latex_table = latex_table.replace('mahalanobis\_distance', 'MD') latex_table = latex_table.replace('max\_prob', 'MP') latex_table = latex_table.replace('bald', 'BALD') print(latex_table) import torch labels = torch.tensor([-100, 0, 1, 2, -100]) num_labels = 3 padding_ids = labels == -100 labels[padding_ids] = 0 labels one_hot = torch.nn.functional.one_hot(labels, num_classes=num_labels) one_hot one_hot[padding_ids] = 0 one_hot ```
github_jupyter
``` import sys import os sys.path.append(os.path.abspath("../..")) from pythonbacktest.datafeed import CSVDataFeed from pythonbacktest.backtestengine import BasicBackTestEngine from pythonbacktest.strategy import import_strategy from pythonbacktest.broker import BackTestBroker from pythonbacktest.tradelog import MemoryTradeLog from pythonbacktest.charting import BokehChartRenderer from pythonbacktest.indicator import IndicatorHistory from pythonbacktest.animation import IndicatorsHistoryAnimation from bokeh.io import output_notebook from datetime import date from IPython.display import HTML, display # need this to set a playground for bokeh output_notebook() TEST_DATA_PATH = os.path.abspath("../testdata/ACME") INITIAL_BUDGET = 100000 DATE_TO_ANALYSIS = date(2016,1,2) csv_data_feed = CSVDataFeed() csv_data_feed.load_data(TEST_DATA_PATH) trade_log = MemoryTradeLog() broker = BackTestBroker(INITIAL_BUDGET, trade_log=trade_log, commision=1.0) indicator_history = IndicatorHistory() strategy_module = import_strategy( "basicSMAstrategy", os.path.abspath("basicsmastrategy.py")) strategy = strategy_module.BasicSMAStrategy() back_test_engine = BasicBackTestEngine(csv_data_feed, strategy, broker, indicator_history) back_test_engine.start() # testing done - let's display the final budget print "Free cash: %s\n" % broker.free_cash # print 5 last transactions for transaction in trade_log.all_transactions[-6:-1]: print "[%s] - %s@%s, remaining cash: %s" % \ (transaction.timestamp, transaction.transaction_type, transaction.transaction_price_per_share, transaction.cash_after) all_indicators = back_test_engine.all_indicators_per_day indicators_per_day = all_indicators[DATE_TO_ANALYSIS] indicators_to_display = [('close', 'gray'), ('SMA200', 'blue'), ('SMA50', 'orange')] volume_indicators = [('volume', 'red')] bokeh_renderer = BokehChartRenderer() bokeh_renderer.render_indicators(indicators_per_day, ['trade_buy', 'trade_sell'], indicators_to_display, volume_indicators) # let's introduce an animation indicators_animation = IndicatorsHistoryAnimation(indicator_history, DATE_TO_ANALYSIS, canvassize=(10,10), markers=['trade_buy', 'trade_sell'], indicators=[indicators_to_display, volume_indicators]) indicators_animation.start_animation() ```
github_jupyter
# Full Adder Below is a Logisim diagram of a Full Adder circuit implementation. ![](./images/full_adder_logisim.png) First we begin by importing magma. We will use the prefix `m` to distinguish between magma functions and native Python. ``` import magma as m ``` The following information was taken from the Lattice data sheet describing the ice40 architecture. The `SB_LUT4` is a 4-input lookup table that we will configure to implement logic functions. ![](./images/SB_LUT4_diagram.png) ![](./images/SB_LUT4_verilog.png) We can use `m.DeclareCircuit` to declare a circuit corresponding to the `SB_LUT4` primitive. We use `m.In` and `m.Out` to specify the directionality of a port. All the inputs and outputs are a single `m.Bit`. We also include the values `A0, A1, A2, A3` that enable us to conveniently specify the lookup table (LUT) initialization values. For example, to implement `I0 & I1 ^ I2 | I3`, we can compute the LUT initialization value as `A0 & A1 ^ A2 | A3`. ``` SB_LUT4 = m.DeclareCircuit("SB_LUT4", "I0", m.In(m.Bit), "I1", m.In(m.Bit), "I2", m.In(m.Bit), "I3", m.In(m.Bit), "O", m.Out(m.Bit)) A0 = 0xAAAA A1 = 0xCCCC A2 = 0xF0F0 A3 = 0xFF00 ``` Based on our logisim diagram, we will need to define 3 logic gates: * 2-bit and * 3-bit or * 3-bit xor ``` class And2(m.Circuit): name = "And2" IO = ["I0", m.In(m.Bit), "I1", m.In(m.Bit), "O", m.Out(m.Bit)] @classmethod def definition(io): lut = SB_LUT4(LUT_INIT=(A0&A1, 16)) m.wire(io.I0, lut.I0) m.wire(io.I1, lut.I1) m.wire(0, lut.I2) m.wire(0, lut.I3) m.wire(lut.O, io.O) class Or3(m.Circuit): name = "Or3" IO = ["I0", m.In(m.Bit), "I1", m.In(m.Bit), "I2", m.In(m.Bit), "O", m.Out(m.Bit)] @classmethod def definition(io): lut = SB_LUT4(LUT_INIT=(A0|A1|A3, 16)) m.wire(io.I0, lut.I0) m.wire(io.I1, lut.I1) m.wire(io.I2, lut.I2) m.wire(0, lut.I3) m.wire(lut.O, io.O) class Xor3(m.Circuit): name = "Xor3" IO = ["I0", m.In(m.Bit), "I1", m.In(m.Bit), "I2", m.In(m.Bit), "O", m.Out(m.Bit)] @classmethod def definition(io): lut = SB_LUT4(LUT_INIT=(A0^A1^A3, 16)) m.wire(io.I0, lut.I0) m.wire(io.I1, lut.I1) m.wire(io.I2, lut.I2) m.wire(0, lut.I3) m.wire(lut.O, io.O) ``` We can define standard Python functions to instance, wire up inputs, and return the output of our logic gates. * `And2()` returns an instance of the And2 circuit * `and2_instance(a, b)` wires `a` and `b` to the inputs of `and2_instance` and returns the output `O` ``` def and2(a, b): and2_instance = And2() return and2_instance(a, b) def or3(a, b, c): return Or3()(a, b, c) def xor3(a, b, c): return Xor3()(a, b, c) ``` Finally, we can define a circuit to implement a Full Adder using our previously defined logic gates. ``` class FullAdder(m.Circuit): name = "FullAdder" IO = ["a", m.In(m.Bit), "b", m.In(m.Bit), "cin", m.In(m.Bit), "out", m.Out(m.Bit), "cout", m.Out(m.Bit)] @classmethod def definition(io): # Generate the sum out = xor3(io.a, io.b, io.cin) m.wire(out, io.out) # Generate the carry a_and_b = and2(io.a, io.b) b_and_cin = and2(io.b, io.cin) a_and_cin = and2(io.a, io.cin) cout = or3(a_and_b, b_and_cin, a_and_cin) m.wire(cout, io.cout) ``` We can import magma's verilog backend to view the verilog definition corresponding to our FullAdder circuit. Notice the logic gates defined in terms of the `SB_LUT4` primitive. ``` from magma.backend.verilog import compile as compile_verilog print(compile_verilog(FullAdder)) ``` We will test our circuit on the icestick by wiring the outputs to the `D1` and `D2` leds. We begin by importing the `IceStick` module from `loam`. With an instance of the `IceStick`, we turn on the clock, D1, and D2 pins. We then define a `main` function by calling `icestick.main()`, instancing our FullAdder, and wiring up the ports. ``` from loam.boards.icestick import IceStick icestick = IceStick() icestick.Clock.on() icestick.D1.on() icestick.D2.on() main = icestick.main() adder = FullAdder() m.wire(0, adder.a) m.wire(1, adder.b) m.wire(1, adder.cin) m.wire(adder.out, main.D1) m.wire(adder.cout, main.D2) ``` We use magma's `m.compile` function to generate verilog and pcf files for the icestick ``` m.compile("build/ice_full_adder", main) ``` Finally, we use the yosys, arachne-pnr, and the icestorm tools to flash our circuit onto the icestick ``` %%bash cd build yosys -q -p 'synth_ice40 -top main -blif ice_full_adder.blif' ice_full_adder.v arachne-pnr -q -d 1k -o ice_full_adder.txt -p ice_full_adder.pcf ice_full_adder.blif icepack ice_full_adder.txt ice_full_adder.bin iceprog ice_full_adder.bin ```
github_jupyter
# Developing an AI application Going forward, AI algorithms will be incorporated into more and more everyday applications. For example, you might want to include an image classifier in a smart phone app. To do this, you'd use a deep learning model trained on hundreds of thousands of images as part of the overall application architecture. A large part of software development in the future will be using these types of models as common parts of applications. In this project, you'll train an image classifier to recognize different species of flowers. You can imagine using something like this in a phone app that tells you the name of the flower your camera is looking at. In practice you'd train this classifier, then export it for use in your application. We'll be using [this dataset](http://www.robots.ox.ac.uk/~vgg/data/flowers/102/index.html) of 102 flower categories, you can see a few examples below. <img src='assets/Flowers.png' width=500px> The project is broken down into multiple steps: * Load and preprocess the image dataset * Train the image classifier on your dataset * Use the trained classifier to predict image content We'll lead you through each part which you'll implement in Python. When you've completed this project, you'll have an application that can be trained on any set of labeled images. Here your network will be learning about flowers and end up as a command line application. But, what you do with your new skills depends on your imagination and effort in building a dataset. For example, imagine an app where you take a picture of a car, it tells you what the make and model is, then looks up information about it. Go build your own dataset and make something new. First up is importing the packages you'll need. It's good practice to keep all the imports at the beginning of your code. As you work through this notebook and find you need to import a package, make sure to add the import up here. ``` # Imports here %matplotlib inline %config InlineBackend.figure_format = 'retina' import matplotlib.pyplot as plt import torch import numpy as np from torch import nn from torch import optim import torch.nn.functional as F from torchvision import datasets, transforms, models from PIL import Image from matplotlib.pyplot import imshow import seaborn as sns import json from collections import OrderedDict ``` ## Load the data Here you'll use `torchvision` to load the data ([documentation](http://pytorch.org/docs/0.3.0/torchvision/index.html)). The data should be included alongside this notebook, otherwise you can [download it here](https://s3.amazonaws.com/content.udacity-data.com/nd089/flower_data.tar.gz). The dataset is split into three parts, training, validation, and testing. For the training, you'll want to apply transformations such as random scaling, cropping, and flipping. This will help the network generalize leading to better performance. You'll also need to make sure the input data is resized to 224x224 pixels as required by the pre-trained networks. The validation and testing sets are used to measure the model's performance on data it hasn't seen yet. For this you don't want any scaling or rotation transformations, but you'll need to resize then crop the images to the appropriate size. The pre-trained networks you'll use were trained on the ImageNet dataset where each color channel was normalized separately. For all three sets you'll need to normalize the means and standard deviations of the images to what the network expects. For the means, it's `[0.485, 0.456, 0.406]` and for the standard deviations `[0.229, 0.224, 0.225]`, calculated from the ImageNet images. These values will shift each color channel to be centered at 0 and range from -1 to 1. ``` data_dir = 'flowers' train_dir = data_dir + '/train' valid_dir = data_dir + '/valid' test_dir = data_dir + '/test' # TODO: Define your transforms for the training, validation, and testing sets data_transforms = transforms.Compose([transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) train_transforms = transforms.Compose([transforms.RandomRotation(30), transforms.RandomResizedCrop(224), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) validation_transforms = transforms.Compose([transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) test_transforms = transforms.Compose([transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) # TODO: Load the datasets with ImageFolder image_datasets = datasets.ImageFolder(data_dir, transform=data_transforms) train_data = datasets.ImageFolder(train_dir, transform=train_transforms) validation_data = datasets.ImageFolder(valid_dir, transform=test_transforms) test_data = datasets.ImageFolder(test_dir, transform=test_transforms) # TODO: Using the image datasets and the trainforms, define the dataloaders dataloaders = torch.utils.data.DataLoader(image_datasets, batch_size=64, shuffle=True) trainloader = torch.utils.data.DataLoader(train_data, batch_size=64, shuffle=True) validloader = torch.utils.data.DataLoader(validation_data, batch_size=32) testloader = torch.utils.data.DataLoader(test_data, batch_size=32) ``` ### Label mapping You'll also need to load in a mapping from category label to category name. You can find this in the file `cat_to_name.json`. It's a JSON object which you can read in with the [`json` module](https://docs.python.org/2/library/json.html). This will give you a dictionary mapping the integer encoded categories to the actual names of the flowers. ``` with open('cat_to_name.json', 'r') as f: cat_to_name = json.load(f) len(cat_to_name) cat_to_name ``` # Building and training the classifier Now that the data is ready, it's time to build and train the classifier. As usual, you should use one of the pretrained models from `torchvision.models` to get the image features. Build and train a new feed-forward classifier using those features. We're going to leave this part up to you. If you want to talk through it with someone, chat with your fellow students! You can also ask questions on the forums or join the instructors in office hours. Refer to [the rubric](https://review.udacity.com/#!/rubrics/1663/view) for guidance on successfully completing this section. Things you'll need to do: * Load a [pre-trained network](http://pytorch.org/docs/master/torchvision/models.html) (If you need a starting point, the VGG networks work great and are straightforward to use) * Define a new, untrained feed-forward network as a classifier, using ReLU activations and dropout * Train the classifier layers using backpropagation using the pre-trained network to get the features * Track the loss and accuracy on the validation set to determine the best hyperparameters We've left a cell open for you below, but use as many as you need. Our advice is to break the problem up into smaller parts you can run separately. Check that each part is doing what you expect, then move on to the next. You'll likely find that as you work through each part, you'll need to go back and modify your previous code. This is totally normal! When training make sure you're updating only the weights of the feed-forward network. You should be able to get the validation accuracy above 70% if you build everything right. Make sure to try different hyperparameters (learning rate, units in the classifier, epochs, etc) to find the best model. Save those hyperparameters to use as default values in the next part of the project. ### Build and train your network ``` model = models.vgg16(pretrained=True) model # Freeze parameters so we don't backprop through them for param in model.parameters(): param.requires_grad = False # Hyperparameters for our network input_size = 25088 hidden_sizes = [400] output_size = 102 drop_p = 0.2 training_rate= 0.001 classifier = nn.Sequential(OrderedDict([ ('fc1', nn.Linear(input_size, hidden_sizes[0])), ('relu1', nn.ReLU()), ('Dropout1', nn.Dropout(p=drop_p)), ('output', nn.Linear(hidden_sizes[0], output_size)), ('softmax', nn.LogSoftmax(dim=1))])) model.classifier = classifier model # TODO: Train a model with a pre-trained network criterion = nn.NLLLoss() optimizer = optim.Adam(model.classifier.parameters(), lr=training_rate) # Implement a function for the validation pass def validation(model, validloader, criterion): test_loss = 0 accuracy = 0 model.to('cuda') for images, labels in validloader: images, labels = images.to('cuda'), labels.to('cuda') output = model.forward(images) test_loss += criterion(output, labels).item() ps = torch.exp(output) equality = (labels.data == ps.max(dim=1)[1]) accuracy += equality.type(torch.FloatTensor).mean() return test_loss, accuracy # Implement a function for the training pass def do_deep_learning(model, trainloader, epochs, print_every, criterion, optimizer, device='cpu'): epochs = epochs print_every = print_every steps = 0 running_loss = 0 # change to cuda model.to('cuda') for e in range(epochs): model.train() for ii, (inputs, labels) in enumerate(trainloader): steps += 1 inputs, labels = inputs.to('cuda'), labels.to('cuda') optimizer.zero_grad() # Forward and backward passes outputs = model.forward(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step() running_loss += loss.item() if steps % print_every == 0: # Make sure network is in eval mode for inference model.eval() # Turn off gradients for validation, saves memory and computations with torch.no_grad(): valid_loss, valid_accuracy = validation(model, validloader, criterion) print("Epoch: {}/{}.. ".format(e+1, epochs), "Training Loss: {:.3f}.. ".format(running_loss/print_every), "valid_loss: {:.3f}.. ".format(valid_loss/len(validloader)), "valid_accuracy: {:.3f}".format(valid_accuracy/len(validloader))) running_loss = 0 # Make sure training is back on model.train() do_deep_learning(model, trainloader, 3, 40, criterion, optimizer, 'gpu') ``` ## Testing your network It's good practice to test your trained network on test data, images the network has never seen either in training or validation. This will give you a good estimate for the model's performance on completely new images. Run the test images through the network and measure the accuracy, the same way you did validation. You should be able to reach around 70% accuracy on the test set if the model has been trained well. ``` # TODO: Do validation on the test set def check_accuracy_on_test(testloader): correct = 0 total = 0 model.to('cuda') with torch.no_grad(): for data in testloader: images, labels = data images, labels = images.to('cuda'), labels.to('cuda') outputs = model(images) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels).sum().item() print('Accuracy of the network on the test images: %d %%' % (100 * correct / total)) check_accuracy_on_test(testloader) ``` ## Save the checkpoint Now that your network is trained, save the model so you can load it later for making predictions. You probably want to save other things such as the mapping of classes to indices which you get from one of the image datasets: `image_datasets['train'].class_to_idx`. You can attach this to the model as an attribute which makes inference easier later on. ```model.class_to_idx = image_datasets['train'].class_to_idx``` Remember that you'll want to completely rebuild the model later so you can use it for inference. Make sure to include any information you need in the checkpoint. If you want to load the model and keep training, you'll want to save the number of epochs as well as the optimizer state, `optimizer.state_dict`. You'll likely want to use this trained model in the next part of the project, so best to save it now. ``` model.class_to_idx = train_data.class_to_idx model.class_to_idx # TODO: Save the checkpoint #model.class_to_idx = image_datasets['train'].class_to_idx checkpoint = {'input_size': input_size, 'output_size': output_size, 'hidden_sizes': hidden_sizes, 'state_dict': model.state_dict(), 'classifier': model.classifier, 'optimizer.state_dict' : optimizer.state_dict, 'optimizer' : optimizer, 'cat_to_name' : cat_to_name, 'arch' : 'vgg16', 'epochs' : 3, 'training_rate' : 0.001, 'drop_p' : drop_p, 'class_to_idx' : model.class_to_idx} torch.save(checkpoint, 'checkpoint.pth') ``` ## Loading the checkpoint At this point it's good to write a function that can load a checkpoint and rebuild the model. That way you can come back to this project and keep working on it without having to retrain the network. ``` # TODO: Write a function that loads a checkpoint and rebuilds the model def load_checkpoint(filepath): checkpoint = torch.load(filepath) model = getattr(models, checkpoint['arch'])(pretrained=True) # Freeze parameters so we don't backprop through them for param in model.parameters(): param.requires_grad = False model.classifier = checkpoint['classifier'] model.load_state_dict(checkpoint['state_dict']) model.class_to_idx = checkpoint['class_to_idx'] #model.optimizer = checkpoint('optimizer') return model loaded_model = load_checkpoint('checkpoint.pth') loaded_model loaded_model.classifier.state_dict() loaded_model.class_to_idx ``` # Inference for classification Now you'll write a function to use a trained network for inference. That is, you'll pass an image into the network and predict the class of the flower in the image. Write a function called `predict` that takes an image and a model, then returns the top $K$ most likely classes along with the probabilities. It should look like ```python probs, classes = predict(image_path, model) print(probs) print(classes) > [ 0.01558163 0.01541934 0.01452626 0.01443549 0.01407339] > ['70', '3', '45', '62', '55'] ``` First you'll need to handle processing the input image such that it can be used in your network. ## Image Preprocessing You'll want to use `PIL` to load the image ([documentation](https://pillow.readthedocs.io/en/latest/reference/Image.html)). It's best to write a function that preprocesses the image so it can be used as input for the model. This function should process the images in the same manner used for training. First, resize the images where the shortest side is 256 pixels, keeping the aspect ratio. This can be done with the [`thumbnail`](http://pillow.readthedocs.io/en/3.1.x/reference/Image.html#PIL.Image.Image.thumbnail) or [`resize`](http://pillow.readthedocs.io/en/3.1.x/reference/Image.html#PIL.Image.Image.thumbnail) methods. Then you'll need to crop out the center 224x224 portion of the image. Color channels of images are typically encoded as integers 0-255, but the model expected floats 0-1. You'll need to convert the values. It's easiest with a Numpy array, which you can get from a PIL image like so `np_image = np.array(pil_image)`. As before, the network expects the images to be normalized in a specific way. For the means, it's `[0.485, 0.456, 0.406]` and for the standard deviations `[0.229, 0.224, 0.225]`. You'll want to subtract the means from each color channel, then divide by the standard deviation. And finally, PyTorch expects the color channel to be the first dimension but it's the third dimension in the PIL image and Numpy array. You can reorder dimensions using [`ndarray.transpose`](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.ndarray.transpose.html). The color channel needs to be first and retain the order of the other two dimensions. ``` img_label = '10' img_path = test_dir + '/' + img_label +'/image_07090.jpg' def process_image(image_path): ''' Scales, crops, and normalizes a PIL image for a PyTorch model, returns an Numpy array ''' # Open the image from PIL import Image img = Image.open(image_path) # Resize if img.size[0] > img.size[1]: img.thumbnail((10000, 256)) else: img.thumbnail((256, 10000)) # Crop left_margin = (img.width-224)/2 bottom_margin = (img.height-224)/2 right_margin = left_margin + 224 top_margin = bottom_margin + 224 img = img.crop((left_margin, bottom_margin, right_margin, top_margin)) # Normalize img = np.array(img)/255 mean = np.array([0.485, 0.456, 0.406]) #provided mean std = np.array([0.229, 0.224, 0.225]) #provided std img = (img - mean)/std # Move color channels to first dimension as expected by PyTorch img = img.transpose((2, 0, 1)) return img def imshow(image, ax=None, title=None): if ax is None: fig, ax = plt.subplots() if title: plt.title(title) # PyTorch tensors assume the color channel is first # but matplotlib assumes is the third dimension image = image.transpose((1, 2, 0)) # Undo preprocessing mean = np.array([0.485, 0.456, 0.406]) std = np.array([0.229, 0.224, 0.225]) image = std * image + mean # Image needs to be clipped between 0 and 1 image = np.clip(image, 0, 1) ax.imshow(image) return ax img = process_image(img_path) imshow(img) ``` ## Class Prediction Once you can get images in the correct format, it's time to write a function for making predictions with your model. A common practice is to predict the top 5 or so (usually called top-$K$) most probable classes. You'll want to calculate the class probabilities then find the $K$ largest values. To get the top $K$ largest values in a tensor use [`x.topk(k)`](http://pytorch.org/docs/master/torch.html#torch.topk). This method returns both the highest `k` probabilities and the indices of those probabilities corresponding to the classes. You need to convert from these indices to the actual class labels using `class_to_idx` which hopefully you added to the model or from an `ImageFolder` you used to load the data ([see here](#Save-the-checkpoint)). Make sure to invert the dictionary so you get a mapping from index to class as well. Again, this method should take a path to an image and a model checkpoint, then return the probabilities and classes. ```python probs, classes = predict(image_path, model) print(probs) print(classes) > [ 0.01558163 0.01541934 0.01452626 0.01443549 0.01407339] > ['70', '3', '45', '62', '55'] ``` ``` def predict(image_path, model, top_num=5): # Process image img = process_image(image_path) # Numpy -> Tensor image_tensor = torch.from_numpy(img).type(torch.FloatTensor) # Add batch of size 1 to image model_input = image_tensor.unsqueeze(0) model.to('cuda') img_tensor = model_input.to('cuda') output = loaded_model(img_tensor) ps = torch.exp(output) probs = ps.to('cpu') # Top probs top_probs, top_labs = probs.topk(top_num) top_probs = top_probs.detach().numpy().tolist()[0] top_labs = top_labs.detach().numpy().tolist()[0] # Convert indices to classes idx_to_class = {val: key for key, val in model.class_to_idx.items()} top_labels = [idx_to_class[lab] for lab in top_labs] top_flowers = [cat_to_name[idx_to_class[lab]] for lab in top_labs] return top_probs, top_labels, top_flowers probs, labs, flowers = predict(img_path, loaded_model) print('probs = ',probs) print('labs = ',labs) print('flowers = ',flowers) ``` ## Sanity Checking Now that you can use a trained model for predictions, check to make sure it makes sense. Even if the testing accuracy is high, it's always good to check that there aren't obvious bugs. Use `matplotlib` to plot the probabilities for the top 5 classes as a bar graph, along with the input image. It should look like this: <img src='assets/inference_example.png' width=300px> You can convert from the class integer encoding to actual flower names with the `cat_to_name.json` file (should have been loaded earlier in the notebook). To show a PyTorch tensor as an image, use the `imshow` function defined above. ``` # TODO: Display an image along with the top 5 classes def plot_solution(image_path, model): # Set up plot plt.figure(figsize = (6,10)) ax = plt.subplot(2,1,1) # Set up title flower_num = image_path.split(test_dir + '/')[1].split('/')[0] title_ = cat_to_name[flower_num] # Plot flower img = process_image(image_path) imshow(img, ax, title = title_); # Make prediction probs, labs, flowers = predict(image_path, model) # Plot bar chart plt.subplot(2,1,2) sns.barplot(x=probs, y=flowers, color=sns.color_palette()[0]); plt.show() plot_solution(img_path, loaded_model) ```
github_jupyter
``` import pandas as pd pd.set_option("display.max_columns", 500) pd.set_option("display.max_rows", 500) ``` ## Table description generation Enter the following info: - Table name - Location - Separator - Encoding (optional) - Decimal mark (optional) ``` table = "MX_COTIZ_ALL.tsv" location = "../../data/raw" sep = '\t' encoding = 'latin1' decimal = ',' ``` ### Make a first view of the dataset to check most interesting columns **Run this if it's a big file** ``` for chunk in pd.read_csv(f"{location}/{table}", sep=sep, encoding=encoding, decimal=decimal, chunksize=1000000): df = chunk break ``` **Run this if it's a relatively small file** ``` df = pd.read_csv(f"{location}/{table}", sep=separator, encoding=encoding, decimal=decimal) df.head(15) df.dtypes df.columns ``` *Based on last output, fill this list to mark most relevant columns* ``` to_use = ['NRO_PRESUP', 'CIF_ID', 'COD_CIA', 'COD_SECC', 'COD_RAMO', 'FECHA_EQUIPO', 'FECHA_SOLIC', 'COD_AGENCIA_PRESU', 'COD_AGENCIA_SOLIC', 'COD_INICIADOR', 'ESTADO', 'COD_MARCA', 'COD_MOD', 'COD_PLAN', 'SUMA_ASEG', 'TIPO_COMBUSTIBLE', 'GRUPO_COMBUSTIBLE', 'ORIGEN', 'FOR_COBRO', 'NEGOCIO', 'COD_PROD', 'COD_POSTAL', 'AGRUPADOR_DIRECTO', 'COD_AGENCIA_GES', 'FECHA_COTIZ_ANT', 'CANAL_ORIGEN', 'ORIGEN_DESC', 'REGION', 'NOM_ORIGEN_PRESU', 'SOLICITA_MISMO_AUTO', 'NUM_SECU_POL', 'EDAD', 'SEXO', 'ESTADO_CIVIL', 'BANCO', 'MARCA_MODELO', 'PUERTAS', 'LOCALIDAD', 'PROVINCIA', 'MARCA', 'VERSION', 'NACIONAL_IMPORT', 'TRACCION', 'TIPO', 'MCA_0KM', 'REC_TR_REAL', 'REC_TC_REAL', 'REC_RC_REAL', 'COMPRO_PLAN', 'COMPRO_PACK', 'REC_TC_VIGENTE', 'REC2_1', 'REDU_TIPO'] ``` ### Now write the file **If it was a big file, read it completely with this line** ``` chunks = pd.read_csv(f"{location}/{table}", sep=sep, encoding=encoding, decimal=decimal, chunksize=1000000) df = pd.concat(chunks) f = open(f'../../docs/{table} feature description.csv','w') f.write('Column;Used;Null Rate; Type; Unique values; Values\n') for column in df.columns: null_rate = round(df[column].isna().mean()*100,2) unique_vals = df[column].nunique() if (column in to_use) and null_rate < .5 and unique_vals > 1: used = 'X' else: used='' dtype = df[column].dtype if(dtype == 'object'): values = f"Top 10:\n{df[column].value_counts(dropna=False).head(10).to_string()}" else: values = f'[{df[column].min()};{df[column].max()}]' f.write(f'{column};{used};{null_rate};{dtype};{unique_vals};"{values}"\n') f.close() ```
github_jupyter
A notebook that contains evaluation timeseries and correlation plots that compare data from the King County mooring at Twanoh in Hood Canal to the model data. The data used are daily averages of the modeled and observed data. ``` import sys sys.path.append('/ocean/kflanaga/MEOPAR/analysis-keegan/notebooks/Tools') import numpy as np import matplotlib.pyplot as plt import os import pandas as pd import netCDF4 as nc import datetime as dt from salishsea_tools import evaltools as et, viz_tools, places, geo_tools import gsw import pickle import matplotlib.gridspec as gridspec import matplotlib as mpl import matplotlib.dates as mdates import cmocean as cmo from matplotlib.colors import LogNorm import Keegan_eval_tools as ket #import scipy.io as so choosepoint=False if choosepoint==True: with nc.Dataset('/data/eolson/results/MEOPAR/NEMO-forcing-new/grid/bathymetry_201702.nc') as bathy: navlat=bathy.variables['nav_lat'][:,:] navlon=bathy.variables['nav_lon'][:,:] with nc.Dataset('/data/eolson/results/MEOPAR/NEMO-forcing-new/grid/mesh_mask201702.nc') as mesh: tmask=mesh.variables['tmask'][0,:,:,:] indj,indi=geo_tools.find_closest_model_point(-123.93,49.75,navlon,navlat,land_mask=np.abs(tmask[0,:,:]-1)) print(indj,indi) fig,ax=plt.subplots(1,1,figsize=(3,4)) ax.pcolormesh(tmask[0,:,:]) ax.plot(282,598,'r*') ax.set_ylim(550,700) ax.set_xlim(150,300) viz_tools.set_aspect(ax) fig,ax=plt.subplots(1,1,figsize=(3,2)) ax.pcolormesh(tmask[:,598,:]) ax.set_ylim(40,0) ax.plot(282,0,'r*') #ax.set_ylim(550,700) ax.set_xlim(150,300) #viz_tools.set_aspect(ax) else: indj,indi=places.PLACES['Egmont']['NEMO grid ji'] year=2015 chlToN=1.8 indk=0 mooring='Dockton' saveloc='/ocean/kflanaga/MEOPAR/savedData/King_CountyData' # Parameters saveloc = "/ocean/kflanaga/MEOPAR/savedData/King_CountyData" chlToN = 1.8 indk = 0 year = 2016 Mooring = "Dockton" datelims=(dt.datetime(year,1,1),dt.datetime(year,12,31)) start_date=datelims[0] end_date=datelims[1] citez=1.0 ##### Loading in pickle file data with open(os.path.join(saveloc,f'daily_data_{mooring}_{year}.pkl'),'rb') as hh: df0=pickle.load(hh) Lat=df0.Lat.unique()[0] Lon=df0.Lon.unique()[0] ii,jj=geo_tools.get_ij_coordinates(Lat,Lon, grid_loc='/ocean/kflanaga/MEOPAR/grid/grid_from_lat_lon_mask999.nc') PATH= '/results2/SalishSea/nowcast-green.201905/' start_date = df0['dtUTC'].iloc[0] end_date = df0['dtUTC'].iloc[-1]+dt.timedelta(days=1) flen=1 namfmt='nowcast' filemap={'diatoms':'ptrc_T','ciliates':'ptrc_T','flagellates':'ptrc_T', 'vosaline':'grid_T','votemper':'grid_T'} fdict={'ptrc_T':1,'grid_T':1} df0['i']=ii df0['j']=jj df0['k']=3 # note: I only ran the first 365 data points to save time df=et.matchData(df0,filemap,fdict,start_date,end_date,namfmt,PATH,1,preIndexed=True); df['mod_chl']=chlToN*(df['mod_diatoms']+df['mod_ciliates']+df['mod_flagellates']) df['log_mod_chl']=ket.logt(df['mod_chl']) df['log_chl']=ket.logt(df['Chl']) def quick_ts(obsvar,modvar): ps=[] fig,ax=plt.subplots(1,1,figsize=(12,8)) #Plotting the data p0,=ax.plot(df['dtUTC'],df[obsvar],'r.',label='Obs') ps.append(p0) p0,=ax.plot(df['dtUTC'],df[modvar],'c-',label='Mod') ps.append(p0) #altering the labels. ax.set_xlabel(f'Date',fontsize=20) ax.set_ylabel(f'{obsvar}',fontsize=20) ax.set_title(str(2007), fontsize=20) ax.xaxis.set_tick_params(labelsize=16) ax.yaxis.set_tick_params(labelsize=16) legend = plt.legend(handles=ps,bbox_to_anchor=[1,.6,0,0]) plt.setp(ax.get_xticklabels(), rotation=30, horizontalalignment='right') M = 11 xticks = mpl.ticker.MaxNLocator(M) ax.xaxis.set_major_locator(xticks) plt.gca().add_artist(legend) yearsFmt = mdates.DateFormatter('%y %d %b') ax.xaxis.set_major_formatter(yearsFmt) return ps, ax def quick_varvar(ax,df,obsvar,modvar,lims): ps=et.varvarPlot(ax,df,obsvar,modvar) ax.set_xlabel('Obs',fontsize=20) ax.set_ylabel('Model',fontsize=20) ax.plot(lims,lims,'k-',alpha=.5) ax.set_xlim(lims) ax.set_ylim(lims) ax.set_aspect(1) return ps ``` # Chlorophyll ``` obsvar='Chl' modvar='mod_chl' ps,ax=quick_ts(obsvar,modvar) ax.set_title('Observed vs Modeled Chlorophyll',fontsize=20) obsvar='Chl' modvar='mod_chl' lims=(0,60) fig,ax=plt.subplots(1,1,figsize=(8,8)) ps=quick_varvar(ax,df,obsvar,modvar,lims) ax.set_title('Observed vs model Chlorophyll',fontsize=20) ``` # Log Transformed Chlorophyll ``` obsvar='log_chl' modvar='log_mod_chl' ps,ax=quick_ts(obsvar,modvar) ax.set_title('Observed vs Modeled log10[Chlorophyll]',fontsize=20) obsvar='log_chl' modvar='log_mod_chl' lims=(-2,6) fig,ax=plt.subplots(1,1,figsize=(8,8)) ps=quick_varvar(ax,df,obsvar,modvar,lims) ax.set_title('Observed vs model log10[Chlorophyll]',fontsize=20) ax.set_ylim(-2,3) ``` # Salinity ``` obsvar='SA' modvar='mod_vosaline' ps,ax=quick_ts(obsvar,modvar) ax.set_title('Observed vs Modeled Salinity',fontsize=20) obsvar='SA' modvar='mod_vosaline' lims=(0,40) fig,ax=plt.subplots(1,1,figsize=(8,8)) ps=quick_varvar(ax,df,obsvar,modvar,lims) ax.set_title('Observed vs model Salinity',fontsize=20) ``` # Temperature ``` obsvar='CT' modvar='mod_votemper' ps,ax=quick_ts(obsvar,modvar) ax.set_title('Observed vs Modeled Temperature',fontsize=20) obsvar='CT' modvar='mod_votemper' lims=(0,40) fig,ax=plt.subplots(1,1,figsize=(8,8)) ps=quick_varvar(ax,df,obsvar,modvar,lims) ax.set_title('Observed vs model Temperature',fontsize=20) ```
github_jupyter
# ASTE Release 1: Accessing the output with xmitgcm's llcreader module The Arctic Subpolar gyre sTate Estimate (ASTE) is a medium resolution, dynamically consistent, data constrained simulation of the ocean and sea ice state in the Arctic and subpolar gyre, spanning 2002-2017. See details on Release 1 in [Nguyen et al, 2020]. This notebook serves as an example for accessing the output from this state estimate using xmitgcm's [llcreader module](https://xmitgcm.readthedocs.io/en/latest/llcreader.html) to get the output in an [xarray](http://xarray.pydata.org/en/stable/) dataset. These capabilities heavily rely on [dask](https://dask.org/) to lazily grab the data as we need it. Users are strongly encouraged to check out [dask's best practices](https://docs.dask.org/en/latest/best-practices.html) regarding memory management before performing more advanced calculations. Any problems due to connections with the server can be reported as a [GitHub Issue](https://docs.github.com/en/free-pro-team@latest/github/managing-your-work-on-github/creating-an-issue) on the [ASTE repo](https://github.com/crios-ut/aste). Finally, we are grateful to the Texas Advanced Computing Center (TACC) for providing storage on Amazon Web Services (AWS) through cloud services integration on Frontera [Stanzione et al, 2020]. --- --- Nguyen, An T., Ocaña, V., Pillar, H., Bigdeli, A., Smith, T. A., & Heimbach, P. (2021). The Arctic Subpolar gyre sTate Estimate: a data-constrained and dynamically consistent ocean-sea ice estimate for 2002–2017. Submitted to Journal of Advances in Modeling Earth Systems. Dan Stanzione, John West, R. Todd Evans, Tommy Minyard, Omar Ghattas, and Dhabaleswar K. Panda. 2020. Frontera: The Evolution of Leadership Computing at the National Science Foundation. In Practice and Experience in Advanced Research Computing (PEARC ’20), July 26–30, 2020, Portland, OR, USA. ACM, New York, NY, USA, 11 pages. https://doi.org/10.1145/3311790.3396656 ``` import numpy as np import warnings import matplotlib.pyplot as plt import xarray as xr import cmocean from dask.distributed import Client from xmitgcm import llcreader import ecco_v4_py ``` ## Get an xarray dataset with *all* ASTE_R1 variables, depth levels, and time steps The function `get_dataset` by default grabs all available output, at all depth levels and all time steps, where each time step represents a monthly mean for that field. This may be suboptimal when operating on a machine with limited memory, for instance on a laptop. See the [llcreader documentation](https://xmitgcm.readthedocs.io/en/latest/llcreader.html) for more examples on how to subset the data with the [get_dataset method](https://xmitgcm.readthedocs.io/en/latest/llcreader.html#api-documentation), including how to grab specific variables, vertical slices, or time steps. ``` aste = llcreader.CRIOSPortalASTE270Model() ds = aste.get_dataset() ``` ### Grab a single monthly average Here we subset the dataset to show the ASTE ocean state during a single month, September 2012. Alternatively, one can provide the corresponding iteration to the `iters` option in `get_dataset` to achieve the same behavior. ``` ds = ds.sel(time='2012-09') ``` We are grabbing a single time slice to make this demo quick. Of course, [xarray](http://xarray.pydata.org/en/stable/) makes it easy to compute full time mean quantities, for example SST averaged from 2006 through 2017: ``` sst = ds['THETA'].sel(k=0,time=slice('2006','2017')).mean(dim='time') ``` but note that this will take longer than the plots below because `llcreader` has to grab all of the 2006-2017 data from the cloud. ### Some house keeping - rename the `faces` dimension to `tiles` (shown and discussed below) - split the coordinate and data variables to speed things up a bit ``` ds = ds.rename({'face':'tile'}) cds = ds.coords.to_dataset().reset_coords() ds = ds.reset_coords(drop=True) ``` #### A list of all the data variables ``` ncols=10 for i,f in enumerate(list(ds.data_vars),start=1): end = '\n' if i%ncols==0 else ', ' print(f,end=end) ``` #### and all the variables describing the underlying grid ``` ncols=10 for i,f in enumerate(list(cds.data_vars),start=1): end = '\n' if i%ncols==0 else ', ' print(f,end=end) ``` and we can get some nice meta data to explain what this means thanks to `xmitgcm`+`xarray` ``` ds.ADVx_TH ``` ### A quick plot This is just a sanity check - we have the output! ``` %%time ds.THETA.sel(k=0).plot(col='tile',col_wrap=3) ``` ## Use ECCOv4-py to make a nicer plot: average SST and SSS during September, 2012 The plot above shows the "tiled" LLC grid topology of ASTE, which can be cumbersome to work with. This grid is familiar to anyone used to the global ECCO state estimate, which [ecco_v4_py](https://github.com/ECCO-GROUP/ECCOv4-py) is designed to deal with. As of `ecco_v4_py` version 1.3.0, we can now use all the same functions with ASTE as well. See below for an example of a nicer plot. See [here](https://ecco-v4-python-tutorial.readthedocs.io/fields.html#geographical-layout) to read more about the LLC grid. ``` sst = ds['THETA'].sel(k=0) sss = ds['SALT'].sel(k=0) %%time fig = plt.figure(figsize=(18,6)) for i,(fld,cmap,cmin,cmax) in enumerate(zip([sst,sss], ['cmo.thermal','cmo.haline'], [-1,30],[30,38]),start=1): with warnings.catch_warnings(): warnings.simplefilter('ignore') fig,ax,p,cbar,*_=ecco_v4_py.plot_proj_to_latlon_grid(cds.XC,cds.YC,fld, show_colorbar=True, projection_type='ortho', user_lon_0=-45,user_lat_0=50, subplot_grid=[1,2,i], cmap=cmap,cmin=cmin,cmax=cmax); ``` ## Use ECCOv4-py to get velocities in the "expected" direction The first plot showed how the rotated fields in the ASTE domain can be difficult to visualize. This is especially true for any vector field (e.g. zonal, meridional velocity), where the vector components are also rotated with each "tile". In order to visualize vector components, we can use the [vector_calc](https://github.com/ECCO-GROUP/ECCOv4-py/blob/master/ecco_v4_py/vector_calc.py) module to perform the necessary interpolation and rotation operations. Note that these routines are essentially simple wrappers around [xgcm](https://xgcm.readthedocs.io/en/latest/) Grid operations, which make all of this possible while working with [xarray](http://xarray.pydata.org/en/stable/) and [dask](https://dask.org/). ``` # get an xgcm Grid object grid = ecco_v4_py.get_llc_grid(cds,domain='aste') %%time uvel,vvel = ecco_v4_py.vector_calc.UEVNfromUXVY(ds['UVELMASS'].sel(k=0), ds['VVELMASS'].sel(k=0), coords=cds, grid=grid) uvel.attrs = ds.UVELMASS.attrs vvel.attrs = ds.VVELMASS.attrs %%time fig = plt.figure(figsize=(18,6)) vmax = .6 for i,(fld,cmap,cmin,cmax) in enumerate(zip([uvel,vvel], ['cmo.balance','cmo.balance'], [-vmax]*2,[vmax]*2),start=1): with warnings.catch_warnings(): warnings.simplefilter('ignore') fig,ax,p,cbar,*_=ecco_v4_py.plot_proj_to_latlon_grid(cds.XC,cds.YC,fld, show_colorbar=True, projection_type='ortho', user_lon_0=-45,user_lat_0=50, subplot_grid=[1,2,i], cmap=cmap,cmin=cmin,cmax=cmax); ``` ## Use ECCOv4-py to compute volumetric transports: Fram Strait example Compare to Fig. 14 of [Nguyen et al., 2020], showing the time mean: - inflow of Atlantic waters to the Arctic = 6.2$\pm$2.3 Sv - outflow of modified waters = -8.3$\pm$2.5 Sv where positive indicates "toward the Arctic". Again, we compute this quantity for a single time slice as a quick example, but this can be easily extended to compute for example the time series of volumetric transport. ``` fsW = ecco_v4_py.calc_section_vol_trsp(ds,grid=grid,pt1=[-18.5,80.37],pt2=[1,80.14],coords=cds) fsE = ecco_v4_py.calc_section_vol_trsp(ds,grid=grid,pt1=[1,80.14],pt2=[11.39,79.49],coords=cds) fsW = fsW.swap_dims({'k':'Z'}) fsE = fsE.swap_dims({'k':'Z'}) plt.rcParams.update({'font.size':14}) fig,ax = plt.subplots(1,1,figsize=(6,8),constrained_layout=True) for vds,lbl in zip([fsW,fsE],['Outflow','Inflow']): mylbl = f'Total {lbl} %2.2f {vds.vol_trsp.units}' % vds.vol_trsp.values vds.vol_trsp_z.plot(y='Z',ax=ax,label=mylbl) ax.grid(True) ax.set(ylim=[-3000,0], xlabel=f'Volumetric Transport [{fsW.vol_trsp.units}]', title=f'Fram Strait Volumetric Transport, Sep. 2012\nPositive into Arctic [{vds.vol_trsp.units}]') ax.legend() ```
github_jupyter
# Multi-Layer Perceptron, MNIST --- In this notebook, we will train an MLP to classify images from the [MNIST database](http://yann.lecun.com/exdb/mnist/) hand-written digit database. The process will be broken down into the following steps: >1. Load and visualize the data 2. Define a neural network 3. Train the model 4. Evaluate the performance of our trained model on a test dataset! Before we begin, we have to import the necessary libraries for working with data and PyTorch. ``` # import libraries import torch import numpy as np ``` --- ## Load and Visualize the [Data](http://pytorch.org/docs/stable/torchvision/datasets.html) Downloading may take a few moments, and you should see your progress as the data is loading. You may also choose to change the `batch_size` if you want to load more data at a time. This cell will create DataLoaders for each of our datasets. ``` from torchvision import datasets import torchvision.transforms as transforms # number of subprocesses to use for data loading num_workers = 0 # how many samples per batch to load batch_size = 20 # convert data to torch.FloatTensor transform = transforms.ToTensor() # choose the training and test datasets train_data = datasets.MNIST(root='data', train=True, download=True, transform=transform) test_data = datasets.MNIST(root='data', train=False, download=True, transform=transform) # prepare data loaders train_loader = torch.utils.data.DataLoader(train_data, batch_size=batch_size, num_workers=num_workers) test_loader = torch.utils.data.DataLoader(test_data, batch_size=batch_size, num_workers=num_workers) ``` ### Visualize a Batch of Training Data The first step in a classification task is to take a look at the data, make sure it is loaded in correctly, then make any initial observations about patterns in that data. ``` import matplotlib.pyplot as plt %matplotlib inline # obtain one batch of training images dataiter = iter(train_loader) images, labels = dataiter.next() images = images.numpy() # plot the images in the batch, along with the corresponding labels fig = plt.figure(figsize=(25, 4)) for idx in np.arange(20): ax = fig.add_subplot(2, 20/2, idx+1, xticks=[], yticks=[]) ax.imshow(np.squeeze(images[idx]), cmap='gray') # print out the correct label for each image # .item() gets the value contained in a Tensor ax.set_title(str(labels[idx].item())) ``` ### View an Image in More Detail ``` img = np.squeeze(images[1]) fig = plt.figure(figsize = (12,12)) ax = fig.add_subplot(111) ax.imshow(img, cmap='gray') width, height = img.shape thresh = img.max()/2.5 for x in range(width): for y in range(height): val = round(img[x][y],2) if img[x][y] !=0 else 0 ax.annotate(str(val), xy=(y,x), horizontalalignment='center', verticalalignment='center', color='white' if img[x][y]<thresh else 'black') ``` --- ## Define the Network [Architecture](http://pytorch.org/docs/stable/nn.html) The architecture will be responsible for seeing as input a 784-dim Tensor of pixel values for each image, and producing a Tensor of length 10 (our number of classes) that indicates the class scores for an input image. This particular example uses two hidden layers and dropout to avoid overfitting. ``` import torch.nn as nn import torch.nn.functional as F ## TODO: Define the NN architecture class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.fc1 = nn.Linear(28 * 28, 256) self.fc2 = nn.Linear(256, 64) self.fc3 = nn.Linear(64, 10) def forward(self, x): # flatten image input x = x.view(-1, 28 * 28) # add hidden layer, with relu activation function x = F.dropout(F.relu(self.fc1(x)), p=0.2) x = F.dropout(F.relu(self.fc2(x)), p=0.2) x = self.fc3(x) return x # initialize the NN model = Net() print(model) ``` ### Specify [Loss Function](http://pytorch.org/docs/stable/nn.html#loss-functions) and [Optimizer](http://pytorch.org/docs/stable/optim.html) It's recommended that you use cross-entropy loss for classification. If you look at the documentation (linked above), you can see that PyTorch's cross entropy function applies a softmax funtion to the output layer *and* then calculates the log loss. ``` ## TODO: Specify loss and optimization functions # specify loss function criterion = nn.CrossEntropyLoss() # specify optimizer optimizer = torch.optim.Adam(model.parameters(),lr=0.003) ``` --- ## Train the Network The steps for training/learning from a batch of data are described in the comments below: 1. Clear the gradients of all optimized variables 2. Forward pass: compute predicted outputs by passing inputs to the model 3. Calculate the loss 4. Backward pass: compute gradient of the loss with respect to model parameters 5. Perform a single optimization step (parameter update) 6. Update average training loss The following loop trains for 30 epochs; feel free to change this number. For now, we suggest somewhere between 20-50 epochs. As you train, take a look at how the values for the training loss decrease over time. We want it to decrease while also avoiding overfitting the training data. ``` # number of epochs to train the model n_epochs = 30 # suggest training between 20-50 epochs model.train() # prep model for training for epoch in range(n_epochs): # monitor training loss train_loss = 0.0 ################### # train the model # ################### for data, target in train_loader: # clear the gradients of all optimized variables optimizer.zero_grad() # forward pass: compute predicted outputs by passing inputs to the model output = model(data) # calculate the loss loss = criterion(output, target) # backward pass: compute gradient of the loss with respect to model parameters loss.backward() # perform a single optimization step (parameter update) optimizer.step() # update running training loss train_loss += loss.item()*data.size(0) # print training statistics # calculate average loss over an epoch train_loss = train_loss/len(train_loader.sampler) print('Epoch: {} \tTraining Loss: {:.6f}'.format( epoch+1, train_loss )) ``` --- ## Test the Trained Network Finally, we test our best model on previously unseen **test data** and evaluate it's performance. Testing on unseen data is a good way to check that our model generalizes well. It may also be useful to be granular in this analysis and take a look at how this model performs on each class as well as looking at its overall loss and accuracy. #### `model.eval()` `model.eval(`) will set all the layers in your model to evaluation mode. This affects layers like dropout layers that turn "off" nodes during training with some probability, but should allow every node to be "on" for evaluation! ``` # initialize lists to monitor test loss and accuracy test_loss = 0.0 class_correct = list(0. for i in range(10)) class_total = list(0. for i in range(10)) model.eval() # prep model for *evaluation* for data, target in test_loader: # forward pass: compute predicted outputs by passing inputs to the model output = model(data) # calculate the loss loss = criterion(output, target) # update test loss test_loss += loss.item()*data.size(0) # convert output probabilities to predicted class _, pred = torch.max(output, 1) # compare predictions to true label correct = np.squeeze(pred.eq(target.data.view_as(pred))) # calculate test accuracy for each object class for i in range(len(target)): label = target.data[i] class_correct[label] += correct[i].item() class_total[label] += 1 # calculate and print avg test loss test_loss = test_loss/len(test_loader.sampler) print('Test Loss: {:.6f}\n'.format(test_loss)) for i in range(10): if class_total[i] > 0: print('Test Accuracy of %5s: %2d%% (%2d/%2d)' % ( str(i), 100 * class_correct[i] / class_total[i], np.sum(class_correct[i]), np.sum(class_total[i]))) else: print('Test Accuracy of %5s: N/A (no training examples)' % (classes[i])) print('\nTest Accuracy (Overall): %2d%% (%2d/%2d)' % ( 100. * np.sum(class_correct) / np.sum(class_total), np.sum(class_correct), np.sum(class_total))) ``` ### Visualize Sample Test Results This cell displays test images and their labels in this format: `predicted (ground-truth)`. The text will be green for accurately classified examples and red for incorrect predictions. ``` # obtain one batch of test images dataiter = iter(test_loader) images, labels = dataiter.next() # get sample outputs output = model(images) # convert output probabilities to predicted class _, preds = torch.max(output, 1) # prep images for display images = images.numpy() # plot the images in the batch, along with predicted and true labels fig = plt.figure(figsize=(25, 4)) for idx in np.arange(20): ax = fig.add_subplot(2, 20/2, idx+1, xticks=[], yticks=[]) ax.imshow(np.squeeze(images[idx]), cmap='gray') ax.set_title("{} ({})".format(str(preds[idx].item()), str(labels[idx].item())), color=("green" if preds[idx]==labels[idx] else "red")) ```
github_jupyter
# Location and the deviation survey Most wells are vertical, but many are not. All modern wells have a deviation survey, which is converted into a position log, giving the 3D position of the well in space. `welly` has a simple way to add a position log in a specific format, and computes a position log from it. You can use the position log to convert between MD and TVD. First, version check. ``` import welly welly.__version__ ``` ## Adding deviation to an existing well First we'll read a LAS and instantiate a well `w` ``` from welly import Well w = Well.from_las("data/P-130_out.LAS") w w.plot() ``` There aren't a lot of tricks for handling the input data, which is assumed to be a CSV-like file containing columns like: MD, inclination, azimuth For example: ``` with open('data/P-130_deviation_survey.csv') as f: lines = f.readlines() for line in lines[:6]: print(line, end='') ``` Then we can turn that into an `ndarray`: ``` import numpy as np dev = np.loadtxt('data/P-130_deviation_survey.csv', delimiter=',', skiprows=1, usecols=[0,1,2]) dev[:5] ``` You can use any other method to get to an array or `pandas.DataFrame` like this one. Then we can add the deviation survey to the well's `location` attribute. This will automatically convert it into a position log, which is an array containing the x-offset, y-offset, and TVD of the well, in that order. ``` w.location.add_deviation(dev, td=w.location.tdd) ``` Now you have the position log: ``` w.location.position[:5] ``` Note that it is irregularly sampled &mdash; this is nothing more than the deviation survey (which is MD, INCL, AZI) converted into relative positions (i.e. deltaX, deltaY, deltaZ). These positions are relative to the tophole location. ## MD to TVD and vice versa We now have the methods `md2tvd` and `tvd2md` available to us: ``` w.location.md2tvd(1000) w.location.tvd2md(998.78525) ``` These can also accept an array: ``` md = np.linspace(0, 300, 31) w.location.md2tvd(md) ``` Note that these are linear in MD, but not in TVD. ``` w.location.md2tvd([0, 10, 20, 30]) ``` ## If you have the position log, but no deviation survey In general, deviation surveys are considered 'canonical'. That is, they are data recorded in the well. The position log &mdash; a set of (x, y, z) points in a linear Euclidean space like (X_UTM, Y_UTM, TVDSS) &mdash; is then computed from the deviation survey. If you have deviation *and* position log, I recommend loading the deviation survey as above. If you *only* have position, in a 3-column array-like called `position` (say), then you can add it to the well like so: w.location.position = np.array(position) You can still use the MD-to-TVD and TVD-to-MD converters above, and `w.position.trajectory()` will work as usual, but you won't have `w.position.dogleg` or `w.position.deviation`. ## Dogleg severity The dogleg severity array is captured in the `dogleg` attribute: ``` w.location.dogleg[:10] ``` ## Starting from new well Data from Rob: ``` import pandas as pd dev = pd.read_csv('data/deviation.csv') dev.head(10) dev.tail() ``` First we'll create an 'empty' well. ``` x = Well(params={'header': {'name': 'foo'}}) ``` Now add the `Location` object to the well's `location` attribute, finally calling its `add_deviation()` method on the deviation data: ``` from welly import Location x.location = Location(params={'kb': 100}) x.location.add_deviation(dev[['MD[m]', 'Inc[deg]', 'Azi[deg]']].values) ``` Let's see how our new position data compares to what was in the `deviation.csv` data file: ### Compare x, y, and dogleg ``` np.set_printoptions(suppress=True) import matplotlib.pyplot as plt fig, ax = plt.subplots(figsize=(15,5)) md_welly = x.location.deviation[:, 0] # Plot x vs depth ax.plot(x.location.position[:, 0], md_welly, lw=6, label="welly") ax.plot(dev['East[m]'], dev['MD[m]'], c='limegreen', label="file") ax.invert_yaxis() ax.legend() ``` They seem to match well. There's a difference at the top because `welly` always adds a (0, 0, 0) point to both the deviation and position logs: ``` x.location.position[:7] ``` In plan view, the wells match: ``` fig, ax = plt.subplots(figsize=(6,6)) ax.plot(*x.location.position[:, :2].T, c='c', lw=5, label="welly") ax.plot(dev['East[m]'], dev['North[m]'], c='yellow', ls='--', label="file") #ax.set_xlim(-20, 800); ax.set_ylim(-820, 20) ax.grid(color='black', alpha=0.2) ``` ## Fit a spline to the position log To make things a bit more realistic, we can shift to the correct spatial datum, i.e. the (x, y, z) of the top hole, where _z_ is the KB elevation. We can also adjust the _z_ value to elevation (i.e. negative downwards). ``` np.set_printoptions(suppress=True, precision=2) x.location.trajectory(datum=[111000, 2222000, 100], elev=True) ``` We can make a 3D plot with this trajectory: ``` from mpl_toolkits.mplot3d import Axes3D fig, ax = plt.subplots(figsize=(12, 7), subplot_kw={'projection': '3d'}) ax.plot(*x.location.trajectory().T, lw=3, alpha=0.75) plt.show() ``` ## Compare doglegs The `deviation.csv` file also contains a measure of dogleg severity, which `welly` also generates (since v0.4.2). **Note that in the current version dogleg severity is in radians, whereas the usual units are degrees per 100 ft or degrees per 30 m. The next release of welly, v0.5, will start using degrees per 30 m by default.** ``` fig, ax = plt.subplots(figsize=(15,4)) ax.plot(x.location.dogleg, lw=5, label="welly") ax = plt.twinx(ax=ax) ax.plot(dev['Dogleg [deg/30m]'], c='limegreen', ls='--', label="file") ax.text(80, 4, 'file', color='limegreen', ha='right', va='top', size=16) ax.text(80, 3.5, 'welly', color='C0', ha='right', va='top', size=16) ``` Apart from the scaling, they agree. ## Implementation details The position log is computed from the deviation survey with the minimum curvature algorithm, which is fairly standard in the industry. To use a different method, pass `method='aa'` (average angle) or `method='bt'` (balanced tangent) directly to `Location.compute_position_log()` yourself. Once we have the position log, we still need a way to look up arbitrary depths. To do this, we use a cubic spline fitted to the position log. This should be OK for most 'natural' well paths, but it might break horribly. If you get weird results, you can pass `method='linear'` to the conversion functions — less accurate but more stable. ---- ## Azimuth datum You can adjust the angle of the azimuth datum with the `azimuth_datum` keyword argument. The default is zero, which means the azimuths in your survey are in degrees relative to grid north (of your UTM grid, say). Let's make some fake data like MD, INCL, AZI ``` dev = [[100, 0, 0], [200, 10, 45], [300, 20, 45], [400, 20, 45], [500, 20, 60], [600, 20, 75], [700, 90, 90], [800, 90, 90], [900, 90, 90], ] z = welly.Well() z.location = welly.Location(params={'kb': 10}) z.location.add_deviation(dev, td=1000, azimuth_datum=20) z.location.plot_plan() z.location.plot_3d() ``` ## Trajectory Get regularly sampled well trajectory with a specified number of points. Assumes there is a position log already, e.g. resulting from calling `add_deviation()` on a deviation survey. Computed from the position log by `scipy.interpolate.splprep()`. ``` z.location.trajectory(points=20) ``` ## TODO - Add `plot_projection()` for a vertical projection. - Export a `shapely` linestring. - Export SHP. - Export 3D `postgis` object. ---- &copy; Agile Scientific 2019–2022, licensed CC-BY / Apache 2.0
github_jupyter
``` # Script to calculate the holdings of a hypothetical market-cap weighted crypto-ETF. TOP_X_CRYPTOS = 5 # Thresholded up to 100 DONT_INCLUDE_TOP_X = 0 TOTAL_AMOUNT_TO_INVEST = 3000 # dollars BLACK_LISTED_SYMBOLS = {"USDT", "USDC", "UST", "BUSD", "DAI"} from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager import requests from bs4 import BeautifulSoup import pandas as pd import time driver = webdriver.Chrome(ChromeDriverManager().install()) import datetime print(datetime.datetime.now() ) def get_soup(url): # https://coderedirect.com/questions/215584/python-3-using-requests-does-not-get-the-full-content-of-a-web-page driver.get(url) soup = BeautifulSoup(driver.page_source, 'html.parser') driver.quit() return soup def get_soup2(url): page = requests.get(url) soup = BeautifulSoup(page.content, 'html.parser') return soup url_overrides = { "dai" : "multi-collateral-dai", "xdc-network" : "xinfin", '1inch-network' : '1inch', "gno" : "gnosis-gno", "pax-dollar": "paxos-standard" } import time url = "https://coinmarketcap.com/" soup = get_soup(url) table = soup.find('table', attrs={'class':'h7vnx2-2 czTsgW cmc-table'}) table_body = table.find('tbody') url = 'https://coinmarketcap.com/' results = [] rows = table_body.find_all('tr') for row in rows[DONT_INCLUDE_TOP_X:min(100, TOP_X_CRYPTOS)]: time.sleep(5) # coin_item_symbol = row.find('p', class_ = "sc-1eb5slv-0 gGIpIK coin-item-symbol") coin_symbol = row.find('p', attrs={'class':"sc-1eb5slv-0 gGIpIK coin-item-symbol"}) try: if coin_symbol: coin_market_cap =row.find('span', attrs={'class': "sc-1ow4cwt-1 ieFnWP"}) else: coin_symbol = row.find('span', attrs={'class':"crypto-symbol"}) url_symbol_text = row.find_all('span')[3].text.lower().replace(" ", "-").replace(".", "-") if url_symbol_text in url_overrides: url_symbol_text = url_overrides[url_symbol_text] url = f'https://coinmarketcap.com/currencies/{url_symbol_text}/' market_cap_soup = get_soup2(url) coin_market_cap = market_cap_soup.find_all('div', attrs={"class": "statsItemRight"})[0].find("div", attrs={"class": "statsValue"}) coin_market_cap_int = int(coin_market_cap.text.replace(",", "").replace("$", "")) except: print(f"Failed for token {coin_symbol}") if coin_symbol.text in BLACK_LISTED_SYMBOLS: continue results.append({'symbol': coin_symbol.text, 'market_cap': coin_market_cap_int}) investing_df = pd.DataFrame(results) total_market_cap = investing_df['market_cap'].sum() investing_df['weight'] = investing_df['market_cap'] / total_market_cap investing_df.head() # https://docs.gspread.org/en/latest/oauth2.html#enable-api-access # https://docs.gspread.org/en/latest/user-guide.html#opening-a-spreadsheet from google.oauth2.service_account import Credentials import gspread scopes = [ 'https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive' ] credentials = Credentials.from_service_account_file( 'jsonFileFromGoogle.json', scopes=scopes ) gc = gspread.authorize(credentials) sheet_key = '1J7roesFAznFzOY849R35rzc-n97gRfEL5cezDIzZA9c' sheet = gc.open_by_key(key=sheet_key) # https://docs.gspread.org/en/latest/user-guide.html#creating-a-worksheet worksheet_title = "Crypto ETF (From Script)" try: worksheet = sheet.worksheet(worksheet_title) except gspread.WorksheetNotFound: worksheet = sheet.add_worksheet(title=worksheet_title, rows=100, cols=20) # https://docs.gspread.org/en/latest/user-guide.html#using-gspread-with-pandas worksheet.update([]) worksheet.update([investing_df.columns.values.tolist()] + investing_df.values.tolist()) worksheet.update_cell(1, 5, "Time Last Updated:") worksheet.update_cell(2, 5, time.ctime()) ```
github_jupyter
# <span style="color:Maroon">Trade Strategy __Summary:__ <span style="color:Blue">In this code we shall test the results of given model ``` # Import required libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt import os np.random.seed(0) import warnings warnings.filterwarnings('ignore') # User defined names index = "Gold" filename_whole = "whole_dataset"+index+"_rf_model.csv" filename_trending = "Trending_dataset"+index+"_rf_model.csv" filename_meanreverting = "MeanReverting_dataset"+index+"_rf_model.csv" date_col = "Date" Rf = 0.01 #Risk free rate of return # Get current working directory mycwd = os.getcwd() print(mycwd) # Change to data directory os.chdir("..") os.chdir(str(os.getcwd()) + "\\Data") # Read the datasets df_whole = pd.read_csv(filename_whole, index_col=date_col) df_trending = pd.read_csv(filename_trending, index_col=date_col) df_meanreverting = pd.read_csv(filename_meanreverting, index_col=date_col) # Convert index to datetime df_whole.index = pd.to_datetime(df_whole.index) df_trending.index = pd.to_datetime(df_trending.index) df_meanreverting.index = pd.to_datetime(df_meanreverting.index) # Head for whole dataset df_whole.head() df_whole.shape # Head for Trending dataset df_trending.head() df_trending.shape # Head for Mean Reverting dataset df_meanreverting.head() df_meanreverting.shape # Merge results from both models to one df_model = df_trending.append(df_meanreverting) df_model.sort_index(inplace=True) df_model.head() df_model.shape ``` ## <span style="color:Maroon">Functions ``` def initialize(df): days, Action1, Action2, current_status, Money, Shares = ([] for i in range(6)) Open_price = list(df['Open']) Close_price = list(df['Adj Close']) Predicted = list(df['Predicted']) Action1.append(Predicted[0]) Action2.append(0) current_status.append(Predicted[0]) if(Predicted[0] != 0): days.append(1) if(Predicted[0] == 1): Money.append(0) else: Money.append(200) Shares.append(Predicted[0] * (100/Open_price[0])) else: days.append(0) Money.append(100) Shares.append(0) return days, Action1, Action2, current_status, Predicted, Money, Shares, Open_price, Close_price def Action_SA_SA(days, Action1, Action2, current_status, i): if(current_status[i-1] != 0): days.append(1) else: days.append(0) current_status.append(current_status[i-1]) Action1.append(0) Action2.append(0) return days, Action1, Action2, current_status def Action_ZE_NZE(days, Action1, Action2, current_status, i): if(days[i-1] < 5): days.append(days[i-1] + 1) Action1.append(0) Action2.append(0) current_status.append(current_status[i-1]) else: days.append(0) Action1.append(current_status[i-1] * (-1)) Action2.append(0) current_status.append(0) return days, Action1, Action2, current_status def Action_NZE_ZE(days, Action1, Action2, current_status, Predicted, i): current_status.append(Predicted[i]) Action1.append(Predicted[i]) Action2.append(0) days.append(days[i-1] + 1) return days, Action1, Action2, current_status def Action_NZE_NZE(days, Action1, Action2, current_status, Predicted, i): current_status.append(Predicted[i]) Action1.append(Predicted[i]) Action2.append(Predicted[i]) days.append(1) return days, Action1, Action2, current_status def get_df(df, Action1, Action2, days, current_status, Money, Shares): df['Action1'] = Action1 df['Action2'] = Action2 df['days'] = days df['current_status'] = current_status df['Money'] = Money df['Shares'] = Shares return df def Get_TradeSignal(Predicted, days, Action1, Action2, current_status): # Loop over 1 to N for i in range(1, len(Predicted)): # When model predicts no action.. if(Predicted[i] == 0): if(current_status[i-1] != 0): days, Action1, Action2, current_status = Action_ZE_NZE(days, Action1, Action2, current_status, i) else: days, Action1, Action2, current_status = Action_SA_SA(days, Action1, Action2, current_status, i) # When Model predicts sell elif(Predicted[i] == -1): if(current_status[i-1] == -1): days, Action1, Action2, current_status = Action_SA_SA(days, Action1, Action2, current_status, i) elif(current_status[i-1] == 0): days, Action1, Action2, current_status = Action_NZE_ZE(days, Action1, Action2, current_status, Predicted, i) else: days, Action1, Action2, current_status = Action_NZE_NZE(days, Action1, Action2, current_status, Predicted, i) # When model predicts Buy elif(Predicted[i] == 1): if(current_status[i-1] == 1): days, Action1, Action2, current_status = Action_SA_SA(days, Action1, Action2, current_status, i) elif(current_status[i-1] == 0): days, Action1, Action2, current_status = Action_NZE_ZE(days, Action1, Action2, current_status, Predicted, i) else: days, Action1, Action2, current_status = Action_NZE_NZE(days, Action1, Action2, current_status, Predicted, i) return days, Action1, Action2, current_status def Get_FinancialSignal(Open_price, Action1, Action2, Money, Shares, Close_price): for i in range(1, len(Open_price)): if(Action1[i] == 0): Money.append(Money[i-1]) Shares.append(Shares[i-1]) else: if(Action2[i] == 0): # Enter new position if(Shares[i-1] == 0): Shares.append(Action1[i] * (Money[i-1]/Open_price[i])) Money.append(Money[i-1] - Action1[i] * Money[i-1]) # Exit the current position else: Shares.append(0) Money.append(Money[i-1] - Action1[i] * np.abs(Shares[i-1]) * Open_price[i]) else: Money.append(Money[i-1] -1 *Action1[i] *np.abs(Shares[i-1]) * Open_price[i]) Shares.append(Action2[i] * (Money[i]/Open_price[i])) Money[i] = Money[i] - 1 * Action2[i] * np.abs(Shares[i]) * Open_price[i] return Money, Shares def Get_TradeData(df): # Initialize the variables days,Action1,Action2,current_status,Predicted,Money,Shares,Open_price,Close_price = initialize(df) # Get Buy/Sell trade signal days, Action1, Action2, current_status = Get_TradeSignal(Predicted, days, Action1, Action2, current_status) Money, Shares = Get_FinancialSignal(Open_price, Action1, Action2, Money, Shares, Close_price) df = get_df(df, Action1, Action2, days, current_status, Money, Shares) df['CurrentVal'] = df['Money'] + df['current_status'] * np.abs(df['Shares']) * df['Adj Close'] return df def Print_Fromated_PL(active_days, number_of_trades, drawdown, annual_returns, std_dev, sharpe_ratio, year): """ Prints the metrics """ print("++++++++++++++++++++++++++++++++++++++++++++++++++++") print(" Year: {0}".format(year)) print(" Number of Trades Executed: {0}".format(number_of_trades)) print("Number of days with Active Position: {}".format(active_days)) print(" Annual Return: {:.6f} %".format(annual_returns*100)) print(" Sharpe Ratio: {:.2f}".format(sharpe_ratio)) print(" Maximum Drawdown (Daily basis): {:.2f} %".format(drawdown*100)) print("----------------------------------------------------") return def Get_results_PL_metrics(df, Rf, year): df['tmp'] = np.where(df['current_status'] == 0, 0, 1) active_days = df['tmp'].sum() number_of_trades = np.abs(df['Action1']).sum()+np.abs(df['Action2']).sum() df['tmp_max'] = df['CurrentVal'].rolling(window=20).max() df['tmp_min'] = df['CurrentVal'].rolling(window=20).min() df['tmp'] = np.where(df['tmp_max'] > 0, (df['tmp_max'] - df['tmp_min'])/df['tmp_max'], 0) drawdown = df['tmp'].max() annual_returns = (df['CurrentVal'].iloc[-1]/100 - 1) std_dev = df['CurrentVal'].pct_change(1).std() sharpe_ratio = (annual_returns - Rf)/std_dev Print_Fromated_PL(active_days, number_of_trades, drawdown, annual_returns, std_dev, sharpe_ratio, year) return ``` ``` # Change to Images directory os.chdir("..") os.chdir(str(os.getcwd()) + "\\Images") ``` ## <span style="color:Maroon">Whole Dataset ``` df_whole_train = df_whole[df_whole["Sample"] == "Train"] df_whole_test = df_whole[df_whole["Sample"] == "Test"] df_whole_test_2019 = df_whole_test[df_whole_test.index.year == 2019] df_whole_test_2020 = df_whole_test[df_whole_test.index.year == 2020] output_train_whole = Get_TradeData(df_whole_train) output_test_whole = Get_TradeData(df_whole_test) output_test_whole_2019 = Get_TradeData(df_whole_test_2019) output_test_whole_2020 = Get_TradeData(df_whole_test_2020) output_train_whole["BuyandHold"] = (100 * output_train_whole["Adj Close"])/(output_train_whole.iloc[0]["Adj Close"]) output_test_whole["BuyandHold"] = (100*output_test_whole["Adj Close"])/(output_test_whole.iloc[0]["Adj Close"]) output_test_whole_2019["BuyandHold"] = (100 * output_test_whole_2019["Adj Close"])/(output_test_whole_2019.iloc[0] ["Adj Close"]) output_test_whole_2020["BuyandHold"] = (100 * output_test_whole_2020["Adj Close"])/(output_test_whole_2020.iloc[0] ["Adj Close"]) Get_results_PL_metrics(output_test_whole_2019, Rf, 2019) Get_results_PL_metrics(output_test_whole_2020, Rf, 2020) # Scatter plot to save fig plt.figure(figsize=(10,5)) plt.plot(output_train_whole["CurrentVal"], 'b-', label="Value (Model)") plt.plot(output_train_whole["BuyandHold"], 'r--', alpha=0.5, label="Buy and Hold") plt.xlabel("Date", fontsize=12) plt.ylabel("Value", fontsize=12) plt.legend() plt.title("Train Sample "+ str(index) + " RF Whole Dataset", fontsize=16) plt.savefig("Train Sample Whole Dataset RF Model" + str(index) +'.png') plt.show() plt.close() # Scatter plot to save fig plt.figure(figsize=(10,5)) plt.plot(output_test_whole["CurrentVal"], 'b-', label="Value (Model)") plt.plot(output_test_whole["BuyandHold"], 'r--', alpha=0.5, label="Buy and Hold") plt.xlabel("Date", fontsize=12) plt.ylabel("Value", fontsize=12) plt.legend() plt.title("Test Sample "+ str(index) + " RF Whole Dataset", fontsize=16) plt.savefig("Test Sample Whole Dataset RF Model" + str(index) +'.png') plt.show() plt.close() ``` __Comments:__ <span style="color:Blue"> Based on the performance of model on Train Sample, the model has definitely learnt the patter, instead of over-fitting. But the performance of model in Test Sample is very poor ## <span style="color:Maroon">Segment Model ``` df_model_train = df_model[df_model["Sample"] == "Train"] df_model_test = df_model[df_model["Sample"] == "Test"] df_model_test_2019 = df_model_test[df_model_test.index.year == 2019] df_model_test_2020 = df_model_test[df_model_test.index.year == 2020] output_train_model = Get_TradeData(df_model_train) output_test_model = Get_TradeData(df_model_test) output_test_model_2019 = Get_TradeData(df_model_test_2019) output_test_model_2020 = Get_TradeData(df_model_test_2020) output_train_model["BuyandHold"] = (100 * output_train_model["Adj Close"])/(output_train_model.iloc[0]["Adj Close"]) output_test_model["BuyandHold"] = (100 * output_test_model["Adj Close"])/(output_test_model.iloc[0]["Adj Close"]) output_test_model_2019["BuyandHold"] = (100 * output_test_model_2019["Adj Close"])/(output_test_model_2019.iloc[0] ["Adj Close"]) output_test_model_2020["BuyandHold"] = (100 * output_test_model_2020["Adj Close"])/(output_test_model_2020.iloc[0] ["Adj Close"]) Get_results_PL_metrics(output_test_model_2019, Rf, 2019) Get_results_PL_metrics(output_test_model_2020, Rf, 2020) # Scatter plot to save fig plt.figure(figsize=(10,5)) plt.plot(output_train_model["CurrentVal"], 'b-', label="Value (Model)") plt.plot(output_train_model["BuyandHold"], 'r--', alpha=0.5, label="Buy and Hold") plt.xlabel("Date", fontsize=12) plt.ylabel("Value", fontsize=12) plt.legend() plt.title("Train Sample Hurst Segment RF Models "+ str(index), fontsize=16) plt.savefig("Train Sample Hurst Segment RF Models" + str(index) +'.png') plt.show() plt.close() # Scatter plot to save fig plt.figure(figsize=(10,5)) plt.plot(output_test_model["CurrentVal"], 'b-', label="Value (Model)") plt.plot(output_test_model["BuyandHold"], 'r--', alpha=0.5, label="Buy and Hold") plt.xlabel("Date", fontsize=12) plt.ylabel("Value", fontsize=12) plt.legend() plt.title("Test Sample Hurst Segment RF Models" + str(index), fontsize=16) plt.savefig("Test Sample Hurst Segment RF Models" + str(index) +'.png') plt.show() plt.close() ``` __Comments:__ <span style="color:Blue"> Based on the performance of model on Train Sample, the model has definitely learnt the patter, instead of over-fitting. The model does perform well in Test sample (Not compared to Buy and Hold strategy) compared to single model. Hurst Exponent based segmentation has definately added value to the model
github_jupyter
``` # To support both python 2 and python 3 from __future__ import division, print_function, unicode_literals %config InlineBackend.figure_format = 'svg' ###配置可以保存为矢量图 %matplotlib inline import os import numpy as np import pandas as pd import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import axes3d import scipy as sp # scientific computation library from sklearn import datasets from sklearn.datasets import load_iris import IPython.core.display as di; ##导出html时,仅仅显示out和图表 di.display_html('<script>jQuery(function() {if (jQuery("body.notebook_app").length == 0) { jQuery(".input_area").toggle(); jQuery(".prompt").toggle();}});</script>', raw=True) iris = load_iris() # iris data有4个feature, 3类,每一类50个数据(50*4),一共150*4 print(type(iris)) print(type(iris.data)) print(iris.data[:5]) print(dir(iris)) print(iris.data.shape) print(iris.target.shape) print(iris.target) # iris_target0=iris.data[:,iris.target==0] irisdata_target0=iris.data[np.where(iris.target==0)] # print(irisdata_target0) irisdata_target1=iris.data[np.where(iris.target==1)] print(irisdata_target1.shape) irisdata_target2=iris.data[np.where(iris.target==2)] print(irisdata_target2.shape) print(irisdata_target0.T.shape) mju1=np.mean(irisdata_target0,axis=0) #50行4列,每列求平均值,得到4个元素(对应于4个feature)的1维数组 print(mju1.shape) print(mju1) mju2=np.mean(irisdata_target1,axis=0) print(mju2.shape) print(mju2) mju3=np.mean(irisdata_target2,axis=0) print(mju3) ######求类均值的均值 mju_array=np.vstack((mju1,mju2,mju3)) #将3个1*4数组按行合并 print(mju_array) mju=np.mean(mju_array,axis=0) #3*4均值数组每列求平均值,得到1*4数组,每个类的feature均值的均值 print(mju.shape) print(mju) # 求散内阵 print(mju1-mju) #1*4 print((mju1-mju).T.shape) mju1_dis=np.atleast_2d(mju1-mju).T #4*1 print(mju1_dis.shape) Sb0=np.dot(mju1_dis,mju1_dis.T) #4*1矩阵乘以1*4矩阵 print(Sb0) mju2_dis=np.atleast_2d(mju2-mju).T Sb1=np.dot(mju2_dis,mju2_dis.T) print(Sb1) mju3_dis=np.atleast_2d(mju3-mju).T Sb2=np.dot(mju3_dis,mju3_dis.T) print(Sb2) Sb=Sb0+Sb1+Sb2 print(Sb) #求散间阵 def sw(x,mju,nk): x_mju_dis=x-mju sw=nk*np.dot(x_mju_dis.T,x_mju_dis) return sw # x_mju0_dis=irisdata_target0-mju1 # # print(x_mju0_dis) # SW1=np.dot(x_mju0_dis.T,x_mju0_dis) # print(SW1) nk=50 SW1=sw(irisdata_target0,mju1,nk) print(SW1) x_mju1_dis=irisdata_target1-mju2 #50*4 # print(x_mju1_dis) SW2=nk*np.dot(x_mju1_dis.T,x_mju1_dis) #4*50的矩阵乘以50*4的矩阵 print(SW2) x_mju2_dis=irisdata_target2-mju3 # print(x_mju2_dis) SW3=nk*np.dot(x_mju2_dis.T,x_mju2_dis) print(SW3) SW=SW1+SW2+SW3 print(SW) # Sw的逆乘以Sb SW_inverse=np.linalg.inv(SW) swsb=np.dot(SW_inverse,Sb) w_eighvalue,w=np.linalg.eigh(swsb) print(w_eighvalue) print(w) #对应的特征向量按列存储 import math def func(w,x): return np.dot(w,x) for i in range(4): ###最大特征值是解 y1=func(w[:,i].T,irisdata_target0.T) #1*4的矩阵乘以4*50的矩阵 # print(y1.shape) # print(y1) y2=func(w[:,i].T,irisdata_target1.T) y3=func(w[:,i].T,irisdata_target2.T) # y11=y1 plt.scatter(y1,np.zeros(y1.size),c='b') # y21=y2.flatten() plt.scatter(y2,np.zeros(y2.size),c='r') plt.scatter(y3,np.zeros(y3.size),c='g') bins = np.linspace(math.ceil(min(y1)), math.floor(max(y2)), 20) # fixed number of bins plt.hist(y1,alpha=0.3,label='class setosa') plt.hist(y2,alpha=0.3,label='class versicolor') plt.hist(y3,alpha=0.3,label='class virginica') plt.legend(loc='upper right') if(i==3): plt.savefig('iris.pdf', bbox_inches='tight') plt.show() ``` ### 3.2.3 Try other eigenvectors out of the generalised eigenvectors ``` y1=func(2*w[:,3].T,irisdata_target0.T) #1*4的矩阵乘以4*50的矩阵 #print(y1.shape) # print(y1) y2=func(2*w[:,3].T,irisdata_target1.T) y3=func(2*w[:,3].T,irisdata_target2.T) # y11=y1 plt.scatter(y1,np.zeros(y1.size),c='b') # y21=y2.flatten() plt.scatter(y2,np.zeros(y2.size),c='r') plt.scatter(y3,np.zeros(y3.size),c='g') bins = np.linspace(math.ceil(min(y1)), math.floor(max(y2)), 20) # fixed number of bins plt.hist(y1,alpha=0.3,label='class setosa') plt.hist(y2,alpha=0.3,label='class versicolor') plt.hist(y3,alpha=0.3,label='class virginica') plt.xlabel("x") plt.ylabel("y") plt.legend(loc='upper right') plt.savefig('iris2.pdf', bbox_inches='tight') plt.show() w_other = np.array([1,3,5,7]) Wtheta=w_other+w[:,3] y1=func(Wtheta.T,irisdata_target0.T) #1*4的矩阵乘以4*50的矩阵 #print(y1.shape) # print(y1) y2=func(Wtheta.T,irisdata_target1.T) y3=func(Wtheta.T,irisdata_target2.T) # y11=y1 plt.scatter(y1,np.zeros(y1.size),c='b') # y21=y2.flatten() plt.scatter(y2,np.zeros(y2.size),c='r') plt.scatter(y3,np.zeros(y3.size),c='g') bins = np.linspace(math.ceil(min(y1)), math.floor(max(y2)), 20) # fixed number of bins plt.hist(y1,alpha=0.3,label='class setosa') plt.hist(y2,alpha=0.3,label='class versicolor') plt.hist(y3,alpha=0.3,label='class virginica') plt.xlabel("x") plt.ylabel("y") plt.savefig('iris-non1.pdf', bbox_inches='tight') plt.legend(loc='upper right') plt.show() w_other = np.ones(w[0].shape) Wtheta=w_other+w[:,3] y1=func(Wtheta.T,irisdata_target0.T) #1*4的矩阵乘以4*50的矩阵 #print(y1.shape) # print(y1) y2=func(Wtheta.T,irisdata_target1.T) y3=func(Wtheta.T,irisdata_target2.T) # y11=y1 plt.scatter(y1,np.zeros(y1.size),c='b') # y21=y2.flatten() plt.scatter(y2,np.zeros(y2.size),c='r') plt.scatter(y3,np.zeros(y3.size),c='g') bins = np.linspace(math.ceil(min(y1)), math.floor(max(y2)), 20) # fixed number of bins plt.hist(y1,alpha=0.3,label='class setosa') plt.hist(y2,alpha=0.3,label='class versicolor') plt.hist(y3,alpha=0.3,label='class virginica') plt.xlabel("x") plt.ylabel("y") plt.legend(loc='upper right') plt.savefig('iris-non2.pdf', bbox_inches='tight') plt.show() w_other = 3*np.ones(w[0].shape) Wtheta=w_other+w[:,3] y1=func(Wtheta.T,irisdata_target0.T) #1*4的矩阵乘以4*50的矩阵 #print(y1.shape) # print(y1) y2=func(Wtheta.T,irisdata_target1.T) y3=func(Wtheta.T,irisdata_target2.T) # y11=y1 plt.scatter(y1,np.zeros(y1.size),c='b') # y21=y2.flatten() plt.scatter(y2,np.zeros(y2.size),c='r') plt.scatter(y3,np.zeros(y3.size),c='g') bins = np.linspace(math.ceil(min(y1)), math.floor(max(y2)), 20) # fixed number of bins plt.hist(y1,alpha=0.3,label='class 1') plt.hist(y2,alpha=0.3,label='class 2') plt.hist(y3,alpha=0.3,label='class 3') plt.legend(loc='upper right') plt.show() # 使用自带的LDA工具包test # from sklearn.lda import LDA from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA lda = LDA() lda = LDA(n_components=2) lda_result = lda.fit_transform(iris.data, iris.target) print(lda_result.shape) import sklearn sklearn.__version__ plt.scatter(lda_result[iris.target==0, 0], lda_result[iris.target==0, 1], color='r') plt.scatter(lda_result[iris.target==1, 0], lda_result[iris.target==1, 1], color='g') plt.scatter(lda_result[iris.target==2, 0], lda_result[iris.target==2, 1], color='b') plt.title('LDA on iris') ```
github_jupyter
# Transfer Learning Template ``` %load_ext autoreload %autoreload 2 %matplotlib inline import os, json, sys, time, random import numpy as np import torch from torch.optim import Adam from easydict import EasyDict import matplotlib.pyplot as plt from steves_models.steves_ptn import Steves_Prototypical_Network from steves_utils.lazy_iterable_wrapper import Lazy_Iterable_Wrapper from steves_utils.iterable_aggregator import Iterable_Aggregator from steves_utils.ptn_train_eval_test_jig import PTN_Train_Eval_Test_Jig from steves_utils.torch_sequential_builder import build_sequential from steves_utils.torch_utils import get_dataset_metrics, ptn_confusion_by_domain_over_dataloader from steves_utils.utils_v2 import (per_domain_accuracy_from_confusion, get_datasets_base_path) from steves_utils.PTN.utils import independent_accuracy_assesment from torch.utils.data import DataLoader from steves_utils.stratified_dataset.episodic_accessor import Episodic_Accessor_Factory from steves_utils.ptn_do_report import ( get_loss_curve, get_results_table, get_parameters_table, get_domain_accuracies, ) from steves_utils.transforms import get_chained_transform ``` # Allowed Parameters These are allowed parameters, not defaults Each of these values need to be present in the injected parameters (the notebook will raise an exception if they are not present) Papermill uses the cell tag "parameters" to inject the real parameters below this cell. Enable tags to see what I mean ``` required_parameters = { "experiment_name", "lr", "device", "seed", "dataset_seed", "n_shot", "n_query", "n_way", "train_k_factor", "val_k_factor", "test_k_factor", "n_epoch", "patience", "criteria_for_best", "x_net", "datasets", "torch_default_dtype", "NUM_LOGS_PER_EPOCH", "BEST_MODEL_PATH", "x_shape", } from steves_utils.CORES.utils import ( ALL_NODES, ALL_NODES_MINIMUM_1000_EXAMPLES, ALL_DAYS ) from steves_utils.ORACLE.utils_v2 import ( ALL_DISTANCES_FEET_NARROWED, ALL_RUNS, ALL_SERIAL_NUMBERS, ) standalone_parameters = {} standalone_parameters["experiment_name"] = "STANDALONE PTN" standalone_parameters["lr"] = 0.001 standalone_parameters["device"] = "cuda" standalone_parameters["seed"] = 1337 standalone_parameters["dataset_seed"] = 1337 standalone_parameters["n_way"] = 8 standalone_parameters["n_shot"] = 3 standalone_parameters["n_query"] = 2 standalone_parameters["train_k_factor"] = 1 standalone_parameters["val_k_factor"] = 2 standalone_parameters["test_k_factor"] = 2 standalone_parameters["n_epoch"] = 50 standalone_parameters["patience"] = 10 standalone_parameters["criteria_for_best"] = "source_loss" standalone_parameters["datasets"] = [ { "labels": ALL_SERIAL_NUMBERS, "domains": ALL_DISTANCES_FEET_NARROWED, "num_examples_per_domain_per_label": 100, "pickle_path": os.path.join(get_datasets_base_path(), "oracle.Run1_framed_2000Examples_stratified_ds.2022A.pkl"), "source_or_target_dataset": "source", "x_transforms": ["unit_mag", "minus_two"], "episode_transforms": [], "domain_prefix": "ORACLE_" }, { "labels": ALL_NODES, "domains": ALL_DAYS, "num_examples_per_domain_per_label": 100, "pickle_path": os.path.join(get_datasets_base_path(), "cores.stratified_ds.2022A.pkl"), "source_or_target_dataset": "target", "x_transforms": ["unit_power", "times_zero"], "episode_transforms": [], "domain_prefix": "CORES_" } ] standalone_parameters["torch_default_dtype"] = "torch.float32" standalone_parameters["x_net"] = [ {"class": "nnReshape", "kargs": {"shape":[-1, 1, 2, 256]}}, {"class": "Conv2d", "kargs": { "in_channels":1, "out_channels":256, "kernel_size":(1,7), "bias":False, "padding":(0,3), },}, {"class": "ReLU", "kargs": {"inplace": True}}, {"class": "BatchNorm2d", "kargs": {"num_features":256}}, {"class": "Conv2d", "kargs": { "in_channels":256, "out_channels":80, "kernel_size":(2,7), "bias":True, "padding":(0,3), },}, {"class": "ReLU", "kargs": {"inplace": True}}, {"class": "BatchNorm2d", "kargs": {"num_features":80}}, {"class": "Flatten", "kargs": {}}, {"class": "Linear", "kargs": {"in_features": 80*256, "out_features": 256}}, # 80 units per IQ pair {"class": "ReLU", "kargs": {"inplace": True}}, {"class": "BatchNorm1d", "kargs": {"num_features":256}}, {"class": "Linear", "kargs": {"in_features": 256, "out_features": 256}}, ] # Parameters relevant to results # These parameters will basically never need to change standalone_parameters["NUM_LOGS_PER_EPOCH"] = 10 standalone_parameters["BEST_MODEL_PATH"] = "./best_model.pth" # Parameters parameters = { "experiment_name": "tl_1v2:oracle.run1-oracle.run2", "device": "cuda", "lr": 0.0001, "n_shot": 3, "n_query": 2, "train_k_factor": 3, "val_k_factor": 2, "test_k_factor": 2, "torch_default_dtype": "torch.float32", "n_epoch": 50, "patience": 3, "criteria_for_best": "target_accuracy", "x_net": [ {"class": "nnReshape", "kargs": {"shape": [-1, 1, 2, 256]}}, { "class": "Conv2d", "kargs": { "in_channels": 1, "out_channels": 256, "kernel_size": [1, 7], "bias": False, "padding": [0, 3], }, }, {"class": "ReLU", "kargs": {"inplace": True}}, {"class": "BatchNorm2d", "kargs": {"num_features": 256}}, { "class": "Conv2d", "kargs": { "in_channels": 256, "out_channels": 80, "kernel_size": [2, 7], "bias": True, "padding": [0, 3], }, }, {"class": "ReLU", "kargs": {"inplace": True}}, {"class": "BatchNorm2d", "kargs": {"num_features": 80}}, {"class": "Flatten", "kargs": {}}, {"class": "Linear", "kargs": {"in_features": 20480, "out_features": 256}}, {"class": "ReLU", "kargs": {"inplace": True}}, {"class": "BatchNorm1d", "kargs": {"num_features": 256}}, {"class": "Linear", "kargs": {"in_features": 256, "out_features": 256}}, ], "NUM_LOGS_PER_EPOCH": 10, "BEST_MODEL_PATH": "./best_model.pth", "n_way": 16, "datasets": [ { "labels": [ "3123D52", "3123D65", "3123D79", "3123D80", "3123D54", "3123D70", "3123D7B", "3123D89", "3123D58", "3123D76", "3123D7D", "3123EFE", "3123D64", "3123D78", "3123D7E", "3124E4A", ], "domains": [32, 38, 8, 44, 14, 50, 20, 26], "num_examples_per_domain_per_label": 10000, "pickle_path": "/mnt/wd500GB/CSC500/csc500-main/datasets/oracle.Run1_10kExamples_stratified_ds.2022A.pkl", "source_or_target_dataset": "target", "x_transforms": [], "episode_transforms": [], "domain_prefix": "ORACLE.run1_", }, { "labels": [ "3123D52", "3123D65", "3123D79", "3123D80", "3123D54", "3123D70", "3123D7B", "3123D89", "3123D58", "3123D76", "3123D7D", "3123EFE", "3123D64", "3123D78", "3123D7E", "3124E4A", ], "domains": [32, 38, 8, 44, 14, 50, 20, 26], "num_examples_per_domain_per_label": 10000, "pickle_path": "/mnt/wd500GB/CSC500/csc500-main/datasets/oracle.Run2_10kExamples_stratified_ds.2022A.pkl", "source_or_target_dataset": "source", "x_transforms": [], "episode_transforms": [], "domain_prefix": "ORACLE.run2_", }, ], "dataset_seed": 500, "seed": 500, } # Set this to True if you want to run this template directly STANDALONE = False if STANDALONE: print("parameters not injected, running with standalone_parameters") parameters = standalone_parameters if not 'parameters' in locals() and not 'parameters' in globals(): raise Exception("Parameter injection failed") #Use an easy dict for all the parameters p = EasyDict(parameters) if "x_shape" not in p: p.x_shape = [2,256] # Default to this if we dont supply x_shape supplied_keys = set(p.keys()) if supplied_keys != required_parameters: print("Parameters are incorrect") if len(supplied_keys - required_parameters)>0: print("Shouldn't have:", str(supplied_keys - required_parameters)) if len(required_parameters - supplied_keys)>0: print("Need to have:", str(required_parameters - supplied_keys)) raise RuntimeError("Parameters are incorrect") ################################### # Set the RNGs and make it all deterministic ################################### np.random.seed(p.seed) random.seed(p.seed) torch.manual_seed(p.seed) torch.use_deterministic_algorithms(True) ########################################### # The stratified datasets honor this ########################################### torch.set_default_dtype(eval(p.torch_default_dtype)) ################################### # Build the network(s) # Note: It's critical to do this AFTER setting the RNG ################################### x_net = build_sequential(p.x_net) start_time_secs = time.time() p.domains_source = [] p.domains_target = [] train_original_source = [] val_original_source = [] test_original_source = [] train_original_target = [] val_original_target = [] test_original_target = [] # global_x_transform_func = lambda x: normalize(x.to(torch.get_default_dtype()), "unit_power") # unit_power, unit_mag # global_x_transform_func = lambda x: normalize(x, "unit_power") # unit_power, unit_mag def add_dataset( labels, domains, pickle_path, x_transforms, episode_transforms, domain_prefix, num_examples_per_domain_per_label, source_or_target_dataset:str, iterator_seed=p.seed, dataset_seed=p.dataset_seed, n_shot=p.n_shot, n_way=p.n_way, n_query=p.n_query, train_val_test_k_factors=(p.train_k_factor,p.val_k_factor,p.test_k_factor), ): if x_transforms == []: x_transform = None else: x_transform = get_chained_transform(x_transforms) if episode_transforms == []: episode_transform = None else: raise Exception("episode_transforms not implemented") episode_transform = lambda tup, _prefix=domain_prefix: (_prefix + str(tup[0]), tup[1]) eaf = Episodic_Accessor_Factory( labels=labels, domains=domains, num_examples_per_domain_per_label=num_examples_per_domain_per_label, iterator_seed=iterator_seed, dataset_seed=dataset_seed, n_shot=n_shot, n_way=n_way, n_query=n_query, train_val_test_k_factors=train_val_test_k_factors, pickle_path=pickle_path, x_transform_func=x_transform, ) train, val, test = eaf.get_train(), eaf.get_val(), eaf.get_test() train = Lazy_Iterable_Wrapper(train, episode_transform) val = Lazy_Iterable_Wrapper(val, episode_transform) test = Lazy_Iterable_Wrapper(test, episode_transform) if source_or_target_dataset=="source": train_original_source.append(train) val_original_source.append(val) test_original_source.append(test) p.domains_source.extend( [domain_prefix + str(u) for u in domains] ) elif source_or_target_dataset=="target": train_original_target.append(train) val_original_target.append(val) test_original_target.append(test) p.domains_target.extend( [domain_prefix + str(u) for u in domains] ) else: raise Exception(f"invalid source_or_target_dataset: {source_or_target_dataset}") for ds in p.datasets: add_dataset(**ds) # from steves_utils.CORES.utils import ( # ALL_NODES, # ALL_NODES_MINIMUM_1000_EXAMPLES, # ALL_DAYS # ) # add_dataset( # labels=ALL_NODES, # domains = ALL_DAYS, # num_examples_per_domain_per_label=100, # pickle_path=os.path.join(get_datasets_base_path(), "cores.stratified_ds.2022A.pkl"), # source_or_target_dataset="target", # x_transform_func=global_x_transform_func, # domain_modifier=lambda u: f"cores_{u}" # ) # from steves_utils.ORACLE.utils_v2 import ( # ALL_DISTANCES_FEET, # ALL_RUNS, # ALL_SERIAL_NUMBERS, # ) # add_dataset( # labels=ALL_SERIAL_NUMBERS, # domains = list(set(ALL_DISTANCES_FEET) - {2,62}), # num_examples_per_domain_per_label=100, # pickle_path=os.path.join(get_datasets_base_path(), "oracle.Run2_framed_2000Examples_stratified_ds.2022A.pkl"), # source_or_target_dataset="source", # x_transform_func=global_x_transform_func, # domain_modifier=lambda u: f"oracle1_{u}" # ) # from steves_utils.ORACLE.utils_v2 import ( # ALL_DISTANCES_FEET, # ALL_RUNS, # ALL_SERIAL_NUMBERS, # ) # add_dataset( # labels=ALL_SERIAL_NUMBERS, # domains = list(set(ALL_DISTANCES_FEET) - {2,62,56}), # num_examples_per_domain_per_label=100, # pickle_path=os.path.join(get_datasets_base_path(), "oracle.Run2_framed_2000Examples_stratified_ds.2022A.pkl"), # source_or_target_dataset="source", # x_transform_func=global_x_transform_func, # domain_modifier=lambda u: f"oracle2_{u}" # ) # add_dataset( # labels=list(range(19)), # domains = [0,1,2], # num_examples_per_domain_per_label=100, # pickle_path=os.path.join(get_datasets_base_path(), "metehan.stratified_ds.2022A.pkl"), # source_or_target_dataset="target", # x_transform_func=global_x_transform_func, # domain_modifier=lambda u: f"met_{u}" # ) # # from steves_utils.wisig.utils import ( # # ALL_NODES_MINIMUM_100_EXAMPLES, # # ALL_NODES_MINIMUM_500_EXAMPLES, # # ALL_NODES_MINIMUM_1000_EXAMPLES, # # ALL_DAYS # # ) # import steves_utils.wisig.utils as wisig # add_dataset( # labels=wisig.ALL_NODES_MINIMUM_100_EXAMPLES, # domains = wisig.ALL_DAYS, # num_examples_per_domain_per_label=100, # pickle_path=os.path.join(get_datasets_base_path(), "wisig.node3-19.stratified_ds.2022A.pkl"), # source_or_target_dataset="target", # x_transform_func=global_x_transform_func, # domain_modifier=lambda u: f"wisig_{u}" # ) ################################### # Build the dataset ################################### train_original_source = Iterable_Aggregator(train_original_source, p.seed) val_original_source = Iterable_Aggregator(val_original_source, p.seed) test_original_source = Iterable_Aggregator(test_original_source, p.seed) train_original_target = Iterable_Aggregator(train_original_target, p.seed) val_original_target = Iterable_Aggregator(val_original_target, p.seed) test_original_target = Iterable_Aggregator(test_original_target, p.seed) # For CNN We only use X and Y. And we only train on the source. # Properly form the data using a transform lambda and Lazy_Iterable_Wrapper. Finally wrap them in a dataloader transform_lambda = lambda ex: ex[1] # Original is (<domain>, <episode>) so we strip down to episode only train_processed_source = Lazy_Iterable_Wrapper(train_original_source, transform_lambda) val_processed_source = Lazy_Iterable_Wrapper(val_original_source, transform_lambda) test_processed_source = Lazy_Iterable_Wrapper(test_original_source, transform_lambda) train_processed_target = Lazy_Iterable_Wrapper(train_original_target, transform_lambda) val_processed_target = Lazy_Iterable_Wrapper(val_original_target, transform_lambda) test_processed_target = Lazy_Iterable_Wrapper(test_original_target, transform_lambda) datasets = EasyDict({ "source": { "original": {"train":train_original_source, "val":val_original_source, "test":test_original_source}, "processed": {"train":train_processed_source, "val":val_processed_source, "test":test_processed_source} }, "target": { "original": {"train":train_original_target, "val":val_original_target, "test":test_original_target}, "processed": {"train":train_processed_target, "val":val_processed_target, "test":test_processed_target} }, }) from steves_utils.transforms import get_average_magnitude, get_average_power print(set([u for u,_ in val_original_source])) print(set([u for u,_ in val_original_target])) s_x, s_y, q_x, q_y, _ = next(iter(train_processed_source)) print(s_x) # for ds in [ # train_processed_source, # val_processed_source, # test_processed_source, # train_processed_target, # val_processed_target, # test_processed_target # ]: # for s_x, s_y, q_x, q_y, _ in ds: # for X in (s_x, q_x): # for x in X: # assert np.isclose(get_average_magnitude(x.numpy()), 1.0) # assert np.isclose(get_average_power(x.numpy()), 1.0) ################################### # Build the model ################################### # easfsl only wants a tuple for the shape model = Steves_Prototypical_Network(x_net, device=p.device, x_shape=tuple(p.x_shape)) optimizer = Adam(params=model.parameters(), lr=p.lr) ################################### # train ################################### jig = PTN_Train_Eval_Test_Jig(model, p.BEST_MODEL_PATH, p.device) jig.train( train_iterable=datasets.source.processed.train, source_val_iterable=datasets.source.processed.val, target_val_iterable=datasets.target.processed.val, num_epochs=p.n_epoch, num_logs_per_epoch=p.NUM_LOGS_PER_EPOCH, patience=p.patience, optimizer=optimizer, criteria_for_best=p.criteria_for_best, ) total_experiment_time_secs = time.time() - start_time_secs ################################### # Evaluate the model ################################### source_test_label_accuracy, source_test_label_loss = jig.test(datasets.source.processed.test) target_test_label_accuracy, target_test_label_loss = jig.test(datasets.target.processed.test) source_val_label_accuracy, source_val_label_loss = jig.test(datasets.source.processed.val) target_val_label_accuracy, target_val_label_loss = jig.test(datasets.target.processed.val) history = jig.get_history() total_epochs_trained = len(history["epoch_indices"]) val_dl = Iterable_Aggregator((datasets.source.original.val,datasets.target.original.val)) confusion = ptn_confusion_by_domain_over_dataloader(model, p.device, val_dl) per_domain_accuracy = per_domain_accuracy_from_confusion(confusion) # Add a key to per_domain_accuracy for if it was a source domain for domain, accuracy in per_domain_accuracy.items(): per_domain_accuracy[domain] = { "accuracy": accuracy, "source?": domain in p.domains_source } # Do an independent accuracy assesment JUST TO BE SURE! # _source_test_label_accuracy = independent_accuracy_assesment(model, datasets.source.processed.test, p.device) # _target_test_label_accuracy = independent_accuracy_assesment(model, datasets.target.processed.test, p.device) # _source_val_label_accuracy = independent_accuracy_assesment(model, datasets.source.processed.val, p.device) # _target_val_label_accuracy = independent_accuracy_assesment(model, datasets.target.processed.val, p.device) # assert(_source_test_label_accuracy == source_test_label_accuracy) # assert(_target_test_label_accuracy == target_test_label_accuracy) # assert(_source_val_label_accuracy == source_val_label_accuracy) # assert(_target_val_label_accuracy == target_val_label_accuracy) experiment = { "experiment_name": p.experiment_name, "parameters": dict(p), "results": { "source_test_label_accuracy": source_test_label_accuracy, "source_test_label_loss": source_test_label_loss, "target_test_label_accuracy": target_test_label_accuracy, "target_test_label_loss": target_test_label_loss, "source_val_label_accuracy": source_val_label_accuracy, "source_val_label_loss": source_val_label_loss, "target_val_label_accuracy": target_val_label_accuracy, "target_val_label_loss": target_val_label_loss, "total_epochs_trained": total_epochs_trained, "total_experiment_time_secs": total_experiment_time_secs, "confusion": confusion, "per_domain_accuracy": per_domain_accuracy, }, "history": history, "dataset_metrics": get_dataset_metrics(datasets, "ptn"), } ax = get_loss_curve(experiment) plt.show() get_results_table(experiment) get_domain_accuracies(experiment) print("Source Test Label Accuracy:", experiment["results"]["source_test_label_accuracy"], "Target Test Label Accuracy:", experiment["results"]["target_test_label_accuracy"]) print("Source Val Label Accuracy:", experiment["results"]["source_val_label_accuracy"], "Target Val Label Accuracy:", experiment["results"]["target_val_label_accuracy"]) json.dumps(experiment) ```
github_jupyter
``` !pip install -Uq catalyst gym ``` # Seminar. RL, DDPG. Hi! It's a second part of the seminar. Here we are going to introduce another way to train bot how to play games. A new algorithm will help bot to work in enviroments with continuos actinon spaces. However, the algorithm have no small changes in bot-enviroment communication process. That's why a lot of code for DQN part are reused. Let's code! ``` from collections import deque, namedtuple import random import numpy as np import gym import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import DataLoader from catalyst import dl, utils device = utils.get_device() import numpy as np from collections import deque, namedtuple Transition = namedtuple( 'Transition', field_names=[ 'state', 'action', 'reward', 'done', 'next_state' ] ) class ReplayBuffer: def __init__(self, capacity: int): self.buffer = deque(maxlen=capacity) def append(self, transition: Transition): self.buffer.append(transition) def sample(self, size: int): indices = np.random.choice( len(self.buffer), size, replace=size > len(self.buffer) ) states, actions, rewards, dones, next_states = \ zip(*[self.buffer[idx] for idx in indices]) states, actions, rewards, dones, next_states = ( np.array(states, dtype=np.float32), np.array(actions, dtype=np.int64), np.array(rewards, dtype=np.float32), np.array(dones, dtype=np.bool), np.array(next_states, dtype=np.float32) ) return states, actions, rewards, dones, next_states def __len__(self): return len(self.buffer) from torch.utils.data.dataset import IterableDataset # as far as RL does not have some predefined dataset, # we need to specify epoch lenght by ourselfs class ReplayDataset(IterableDataset): def __init__(self, buffer: ReplayBuffer, epoch_size: int = int(1e3)): self.buffer = buffer self.epoch_size = epoch_size def __iter__(self): states, actions, rewards, dones, next_states = \ self.buffer.sample(self.epoch_size) for i in range(len(dones)): yield states[i], actions[i], rewards[i], dones[i], next_states[i] def __len__(self): return self.epoch_size ``` The first difference is action normalization. Some enviroments have action space bounds, and model's actino have to lie in the bounds. ``` class NormalizedActions(gym.ActionWrapper): def action(self, action): low_bound = self.action_space.low upper_bound = self.action_space.high action = low_bound + (action + 1.0) * 0.5 * (upper_bound - low_bound) action = np.clip(action, low_bound, upper_bound) return action def _reverse_action(self, action): low_bound = self.action_space.low upper_bound = self.action_space.high action = 2 * (action - low_bound) / (upper_bound - low_bound) - 1 action = np.clip(action, low_bound, upper_bound) return actions ``` Next difference is randomness. We can't just sample an action from action space. But we can add noise to generated action. ``` def get_action(env, network, state, sigma=None): state = torch.tensor(state, dtype=torch.float32).to(device).unsqueeze(0) action = network(state).detach().cpu().numpy()[0] if sigma is not None: action = np.random.normal(action, sigma) return action def generate_session( env, network, sigma=None, replay_buffer=None, ): total_reward = 0 state = env.reset() for t in range(env.spec.max_episode_steps): action = get_action(env, network, state=state, sigma=sigma) next_state, reward, done, _ = env.step(action) if replay_buffer is not None: transition = Transition( state, action, reward, done, next_state) replay_buffer.append(transition) total_reward += reward state = next_state if done: break return total_reward, t def generate_sessions( env, network, sigma=None, replay_buffer=None, num_sessions=100, ): sessions_reward, sessions_steps = 0, 0 for i_episone in range(num_sessions): r, t = generate_session( env=env, network=network, sigma=sigma, replay_buffer=replay_buffer, ) sessions_reward += r sessions_steps += t return sessions_reward, sessions_steps def soft_update(target, source, tau): """Updates the target data with smoothing by ``tau``""" for target_param, param in zip(target.parameters(), source.parameters()): target_param.data.copy_( target_param.data * (1.0 - tau) + param.data * tau ) class GameCallback(dl.Callback): def __init__( self, *, env, replay_buffer, session_period, sigma, # sigma_k, actor_key, ): super().__init__(order=0) self.env = env self.replay_buffer = replay_buffer self.session_period = session_period self.sigma = sigma # self.sigma_k = sigma_k self.actor_key = actor_key def on_stage_start(self, runner: dl.IRunner): self.actor = runner.model[self.actor_key] self.actor.eval() generate_sessions( env=self.env, network=self.actor, sigma=self.sigma, replay_buffer=self.replay_buffer, num_sessions=1000, ) self.actor.train() def on_epoch_start(self, runner: dl.IRunner): self.session_counter = 0 self.session_steps = 0 def on_batch_end(self, runner: dl.IRunner): if runner.global_batch_step % self.session_period == 0: self.actor.eval() session_reward, session_steps = generate_session( env=self.env, network=self.actor, sigma=self.sigma, replay_buffer=self.replay_buffer, ) self.session_counter += 1 self.session_steps += session_steps runner.batch_metrics.update({"s_reward": session_reward}) runner.batch_metrics.update({"s_steps": session_steps}) self.actor.train() def on_epoch_end(self, runner: dl.IRunner): num_sessions = 100 self.actor.eval() valid_rewards, valid_steps = generate_sessions( env=self.env, network=self.actor, num_sessions=num_sessions ) self.actor.train() valid_rewards /= float(num_sessions) valid_steps /= float(num_sessions) runner.epoch_metrics["_epoch_"]["num_samples"] = self.session_steps runner.epoch_metrics["_epoch_"]["updates_per_sample"] = ( runner.loader_sample_step / self.session_steps ) runner.epoch_metrics["_epoch_"]["v_reward"] = valid_rewards ``` And the main difference is that we have two networks! Look at the algorithm: ![DDPG algorithm](https://miro.medium.com/max/1084/1*BVST6rlxL2csw3vxpeBS8Q.png) One network is used to generate action (Policy Network). Another judge network's action and predict current reward. Because we have two networks, we can train our model to act in a continues space. Let's code this algorithm in Runner train step. ``` class CustomRunner(dl.Runner): def __init__( self, *, gamma, tau, tau_period=1, **kwargs, ): super().__init__(**kwargs) self.gamma = gamma self.tau = tau self.tau_period = tau_period def on_stage_start(self, runner: dl.IRunner): super().on_stage_start(runner) soft_update(self.model["target_actor"], self.model["actor"], 1.0) soft_update(self.model["target_critic"], self.model["critic"], 1.0) def handle_batch(self, batch): # model train/valid step states, actions, rewards, dones, next_states = batch actor, target_actor = self.model["actor"], self.model["target_actor"] critic, target_critic = self.model["critic"], self.model["target_critic"] actor_optimizer, critic_optimizer = self.optimizer["actor"], self.optimizer["critic"] # get actions for the current state pred_actions = actor(states) # get q-values for the actions in current states pred_critic_states = torch.cat([states, pred_actions], 1) # use q-values to train the actor model policy_loss = (-critic(pred_critic_states)).mean() with torch.no_grad(): # get possible actions for the next states next_state_actions = target_actor(next_states) # get possible q-values for the next actions next_critic_states = torch.cat([next_states, next_state_actions], 1) next_state_values = target_critic(next_critic_states).detach().squeeze() next_state_values[dones] = 0.0 # compute Bellman's equation value target_state_values = next_state_values * self.gamma + rewards # compute predicted values critic_states = torch.cat([states, actions], 1) state_values = critic(critic_states).squeeze() # train the critic model value_loss = self.criterion( state_values, target_state_values.detach() ) self.batch_metrics.update({ "critic_loss": value_loss, "actor_loss": policy_loss }) if self.is_train_loader: actor.zero_grad() actor_optimizer.zero_grad() policy_loss.backward() actor_optimizer.step() critic.zero_grad() critic_optimizer.zero_grad() value_loss.backward() critic_optimizer.step() if self.global_batch_step % self.tau_period == 0: soft_update(target_actor, actor, self.tau) soft_update(target_critic, critic, self.tau) ``` Prepare networks generator and train models! ``` def get_network_actor(env): inner_fn = utils.get_optimal_inner_init(nn.ReLU) outer_fn = utils.outer_init network = torch.nn.Sequential( nn.Linear(env.observation_space.shape[0], 400), nn.ReLU(), nn.Linear(400, 300), nn.ReLU(), ) head = torch.nn.Sequential( nn.Linear(300, 1), nn.Tanh() ) network.apply(inner_fn) head.apply(outer_fn) return torch.nn.Sequential(network, head) def get_network_critic(env): inner_fn = utils.get_optimal_inner_init(nn.LeakyReLU) outer_fn = utils.outer_init network = torch.nn.Sequential( nn.Linear(env.observation_space.shape[0] + 1, 400), nn.LeakyReLU(0.01), nn.Linear(400, 300), nn.LeakyReLU(0.01), ) head = nn.Linear(300, 1) network.apply(inner_fn) head.apply(outer_fn) return torch.nn.Sequential(network, head) # data batch_size = 64 epoch_size = int(1e3) * batch_size buffer_size = int(1e5) # runner settings, ~training gamma = 0.99 tau = 0.01 tau_period = 1 # callback, ~exploration session_period = 1 sigma = 0.3 # optimization lr_actor = 1e-4 lr_critic = 1e-3 # env_name = "LunarLanderContinuous-v2" env_name = "Pendulum-v0" env = NormalizedActions(gym.make(env_name)) replay_buffer = ReplayBuffer(buffer_size) actor, target_actor = get_network_actor(env), get_network_actor(env) critic, target_critic = get_network_critic(env), get_network_critic(env) utils.set_requires_grad(target_actor, requires_grad=False) utils.set_requires_grad(target_critic, requires_grad=False) models = { "actor": actor, "critic": critic, "target_actor": target_actor, "target_critic": target_critic, } criterion = torch.nn.MSELoss() optimizer = { "actor": torch.optim.Adam(actor.parameters(), lr_actor), "critic": torch.optim.Adam(critic.parameters(), lr=lr_critic), } loaders = { "train": DataLoader( ReplayDataset(replay_buffer, epoch_size=epoch_size), batch_size=batch_size, ), } runner = CustomRunner( gamma=gamma, tau=tau, tau_period=tau_period, ) runner.train( model=models, criterion=criterion, optimizer=optimizer, loaders=loaders, logdir="./logs_ddpg", num_epochs=10, verbose=True, valid_loader="_epoch_", valid_metric="v_reward", minimize_valid_metric=False, load_best_on_end=True, callbacks=[ GameCallback( env=env, replay_buffer=replay_buffer, session_period=session_period, sigma=sigma, actor_key="actor", ) ] ) ``` And we can watch how our model plays in the games! \* to run cells below, you should update your python environment. Instruction depends on your system specification. ``` import gym.wrappers env = gym.wrappers.Monitor( gym.make(env_name), directory="videos_ddpg", force=True) generate_sessions( env=env, network=runner.model["actor"], num_sessions=100 ) env.close() # show video from IPython.display import HTML import os video_names = list( filter(lambda s: s.endswith(".mp4"), os.listdir("./videos_ddpg/"))) HTML(""" <video width="640" height="480" controls> <source src="{}" type="video/mp4"> </video> """.format("./videos/"+video_names[-1])) # this may or may not be _last_ video. Try other indices ```
github_jupyter
``` import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from scipy.stats import norm from scipy.stats import stats import math import random from matplotlib import pyplot as plt import numpy as np import matplotlib.backends.backend_pdf import random import math import numpy as np import matplotlib.pyplot as plt import datetime as dt import sys from pyecharts.charts import Bar from pyecharts import options as opts from pyecharts.globals import ThemeType from pyecharts.charts import Bar from pyecharts import options as opts import dataframe_image as dfi from jupyterthemes import get_themes import jupyterthemes as jt from jupyterthemes.stylefx import set_nb_theme from IPython.core.display import display, HTML from IPython.display import display, Markdown, clear_output import ipywidgets as widgets from ipywidgets import interact, interactive, fixed, interact_manual import time %matplotlib inline sns.set() #Load the dataset with the calculated differences Y[t], ommit the first value because difference is NaN and print the head() def file(fileinput): if not ".csv" in fileinput: fileinput = "data/" + fileinput + ".csv" global df df = pd.read_csv(fileinput,skiprows=0) df['difference'] = df.iloc[:,1].diff() df = df.iloc[1:] df.columns = ['date', 'X[t]', 'Y[t]'] df.date = pd.to_datetime(df.date) df.set_index('date', inplace=True) return df ``` # Code for the Random(p) Problem ``` def random_prob_model(counter, probability): #From the dataframe these are the load values and the dates columns stored in arrays to be processed distribution = df.reset_index(drop=False).iloc[:,1].values distribution = distribution[:len(distribution)-31] dates = df.reset_index(drop=False).iloc[:,0].values #Fix a probability #probability = 0.5 #counter = 100 #Empty lists to store times we stopped, loads at each stop and the minimum values of each run and times load_list = [] time_list = [] minimums = [] minimums_times = [] load_data = [] for i in range(0, len(distribution), counter): chunked_data = distribution[i:i + counter] min_value = min(chunked_data) minimums.append(min_value) min_index = np.where(chunked_data == min_value)[0][0] minimums_times.append(min_index) load_data.append(chunked_data) for chunk in load_data: best = 0 index = 0 #Find the best candidate for the model to stop in the first run by comparing the random generated value with the fixed probability x #If less STOP and offload, else Keep looking unitl the 100th observation while index <= len(chunk)-1: x = random.uniform(0, 1) if x < probability: best = index #print ("Best candidate found! We offload on " + str(candidate_time[best]) + "\nThe load when we offload is " + str(candidate[best])) time_list.append(np.where(chunk == chunk[best])[0][0]) load_list.append(chunk[best]) #print("The difference between the Optimal and the Achieved load values is " + str(candidate[best] - minimumL)) break elif index == counter-1: best = index #print ("Best candidate found! We offload on " + str(next_times[-1]) + "\nThe load when we offload is " + str(next_observations[-1])) time_list.append(np.where(chunk == chunk[best])[0][0]) load_list.append(chunk[best]) #print("The difference between the Optimal and the Achieved load values is " + str(next_observations[-1] - minimumL)) break index += 1 load_differences = np.asarray(load_list) - np.asarray(minimums) times_differences = np.array(time_list) - np.array(minimums_times) return minimums, load_list, load_differences, minimums_times, time_list, times_differences ``` # Code for Secretary Model ``` def secretary_model(counter): #This is the code for the Secretary Problem #From the dataframe these are the load values and the dates columns stored in arrays to be processed distribution = df.reset_index(drop=False).iloc[:,1].values distribution = distribution[:len(distribution)-31] dates = df.reset_index(drop=False).iloc[:,0].values #Empty lists to store times we stopped, loads at each stop and the minimum values of each run time_list = [] load_list = [] minimums = [] minimums_times = [] load_data = [] for i in range(0, len(distribution), counter): chunked_data = distribution[i:i + counter] min_value = min(chunked_data) minimums.append(min_value) min_index = np.where(chunked_data == min_value)[0][0] minimums_times.append(min_index) load_data.append(chunked_data) for chunk in load_data: samplesize = round(len(chunk) * math.exp(-1)) sample = chunk[ : samplesize] #Compute the benchmark_secretary of the sample (minimum values of the sample) benchmark = min(sample) best = 0 index = samplesize #Find the best_secretary candidate_secretary for the model to stop in the first run by comparing all next values with the benchmark_secretary value while index <= len(chunk)-1: if chunk[index] <= benchmark: best = index break index += 1 #Once we observe the first that is less than the benchmark_secretary value STOP there and offload. Store the value if(chunk[best] <= benchmark): time_list.append(np.where(chunk == chunk[best])[0][0]) load_list.append(chunk[best]) #If we dont then go to the end of the 100 observations, Stop there and offload elif index == counter: best = index time_list.append(np.where(chunk == chunk[best-1])[0][0]) load_list.append(chunk[best-1]) load_differences = np.asarray(load_list) - np.asarray(minimums) times_differences = np.array(time_list) - np.array(minimums_times) time_delays = [x - 37 for x in time_list] return minimums, load_list, load_differences, minimums_times, time_list, times_differences ``` # Code for the House Selling Model ``` #Without Dataset # A = [[2,6,7,10,4,7,4,8,9,3], [8,5,3,9,1,7,9,10,4,3]] def house_selling_model(counter, r): distribution = df.reset_index(drop=False).iloc[:,1].values distribution = distribution[:len(distribution)-31] dates = df.reset_index(drop=False).iloc[:,0].values N = counter #Empty lists to store times we stopped, loads at each stop and the minimum values of each run and times scaled_list = [] load_list = [] time_list = [] minimums = [] minimums_times = [] A = [] for i in range(0, len(distribution), counter): chunked_data = distribution[i:i + counter] min_value = min(chunked_data) minimums.append(min_value) min_index = np.where(chunked_data == min_value)[0][0] minimums_times.append(min_index) A.append(chunked_data) # Scale the availability values for each in A: scaled_availability = np.full(shape=len(each), fill_value=0, dtype=np.float) for k in range(1,len(each)): scaled_availability[k] = (max(each) - each[k])/(max(each) - min(each)) scaled_list.append(scaled_availability) d = np.full(shape=counter, fill_value=0, dtype=np.float) for i in range(N-2,-1,-1): d[i] = (1/(1+r))*((1+(d[i+1])**2)/2) c = 0 for each_list in scaled_list: for i in range(0,len(each_list)+1): if each_list[i] >= d[i]: load_list.append(A[c][i]) time_list.append(i) break c += 1 load_differences = np.asarray(load_list) - np.asarray(minimums) times_differences = np.array(time_list) - np.array(minimums_times) return minimums, load_list, load_differences, minimums_times, time_list, times_differences ``` # RUNS AND VALUES SIMULATIONS FOR MODELS ``` #Simulate the random prob model by defining the rpb to be executed #Define chunk_func as rpb_200[0-4] and chunks N def randomP_simulation_run(chunk_func, N): n_groups = len(chunk_func[0]) # create plot for loads plt.figure(figsize=(30,25)) index = np.arange(n_groups) bar_width = 0.4 opacity = 0.8 #Loads Plot #Plot the achieved values of each observed samle rects2 = plt.bar(index, chunk_func[1], bar_width,alpha=opacity,color='black',label='Achieved') #Plot the minimum values of each observed sample rects1 = plt.bar(index + bar_width, chunk_func[0], bar_width,alpha=opacity,color='darkred',label='Optimal') #Label plt.xlabel('Stops', size = 50) plt.ylabel('Load Values', size = 50) plt.title('Loads in each Run with N = {} for Random(P) Model'.format(N), size = 60) plt.xticks(index + (bar_width/2), tuple(range(1,n_groups+1))) plt.xticks(fontsize= 30) plt.yticks(fontsize= 30) plt.xlim([0-bar_width/2,index.size]) plt.plot() plt.legend(prop={'size': 25}) plt.savefig('randomp_figures/random(p)_{}_'.format(N) + time.strftime("%Y-%m-%d %H%M%S") + '.png') plt.figure(figsize=(30,25)) #Times Plot rects2 = plt.bar(index, np.absolute(chunk_func[5]), bar_width,alpha=opacity,color='darkblue',label='Time instance difference from optimal') #Label plt.xlabel('Stops', size = 50) plt.ylabel('Time Instances', size = 50) plt.title('Times in each Run with N = {} for Random(P) Model'.format(N), size = 60) plt.xticks(index, tuple(range(1,n_groups+1))) plt.xticks(fontsize= 30) plt.yticks(fontsize= 30) plt.xlim([0-bar_width/2,index.size]) plt.plot() plt.legend(prop={'size': 25}) plt.savefig('randomp_figures/random(p)_times_{}_'.format(N) + time.strftime("%Y-%m-%d %H%M%S") + '.png') #Display the dataframe runs_data = {'Run': list(range(1,len(chunk_func[0])+1)),'Optimal': chunk_func[0],'Load when Offloading': chunk_func[1], 'Load Difference': chunk_func[2],} runs_frame = pd.DataFrame(runs_data, columns = ['Run','Optimal','Load when Offloading', 'Load Difference']) runs_frame.index += 1 display(runs_frame) runs_frame.to_csv('randomp_figures/dataframes/randomp_data_{}_'.format(N) + time.strftime("%Y-%m-%d %H%M%S") + '.csv') #Simulate the random prob model by defining the rpb to be executed #Define secretary_model as 200 def secretary_simulation_run(chunks): # data to plot n_groups_secretary = len(secretary_model(chunks)[0]) # create plot for loads plt.figure(figsize=(30,25)) index = np.arange(n_groups_secretary) bar_width = 0.4 opacity = 0.8 # Loads Plot #Plot the achieved values of each observed samle rects2 = plt.bar(index, secretary_model(chunks)[1], bar_width,alpha=opacity,color='black',label='Achieved') #Plot the minimum values of each observed sample rects1 = plt.bar(index + bar_width, secretary_model(chunks)[0], bar_width, alpha=opacity,color='darkred',label='Optimal') #Label plt.xlabel('Stops', size = 50) plt.ylabel('Load Values', size = 50) plt.title('Loads in each Run with N = {} for Secretary Model'.format(chunks), size = 60) plt.xticks(index + (bar_width/2), tuple(range(1,n_groups_secretary+1))) plt.xticks(fontsize= 30) plt.yticks(fontsize= 30) plt.xlim([0-bar_width/2,index.size]) plt.plot() plt.legend(prop={'size': 25}) plt.savefig('secretary_figures/secretary_{}_'.format(chunks) + time.strftime("%Y-%m-%d %H%M%S") + '.png') #Time Plot plt.figure(figsize=(30,25)) #Plot the minimum values of each observed sample rects1 = plt.bar(index + bar_width, secretary_model(chunks)[5], bar_width, alpha=opacity,color='darkblue',label='Time instance difference from optimal') #Label plt.xlabel('Stops', size = 50) plt.ylabel('Time Instances', size = 50) plt.title('Times in each Run with N = {} for Secretary Model'.format(chunks), size = 60) plt.xticks(index + (bar_width), tuple(range(1,n_groups_secretary+1))) plt.xticks(fontsize= 30) plt.yticks(fontsize= 30) plt.xlim([0-bar_width/2,index.size]) plt.plot() plt.legend(prop={'size': 25}) # ax2.plot() plt.savefig('secretary_figures/secretary_times_{}_'.format(chunks) + time.strftime("%Y-%m-%d %H%M%S") + '.png') #Display the dataframe runs_data = {'Run': list(range(1,len(secretary_model(chunks)[0])+1)),'Optimal': secretary_model(chunks)[0],'Load when Offloading': secretary_model(chunks)[1], 'Load Difference': secretary_model(chunks)[2],} runs_frame = pd.DataFrame(runs_data, columns = ['Run','Optimal','Load when Offloading', 'Load Difference']) runs_frame.index += 1 display(runs_frame) runs_frame.to_csv('secretary_figures/dataframes/secretary_data_{}_'.format(chunks) + time.strftime("%Y-%m-%d %H%M%S") + '.csv') def house_selling_simulation_run(chunks, r): n_groups_house = len(house_selling_model(chunks, r)[0]) # create plot for loads plt.figure(figsize=(30,25)) index = np.arange(n_groups_house) bar_width = 0.4 opacity = 0.8 # Loads Plot #Plot the achieved values of each observed samle rects2 = plt.bar(index, house_selling_model(chunks, r)[1], bar_width,alpha=opacity,color='black',label='Achieved') #Plot the minimum values of each observed sample rects1 = plt.bar(index + bar_width, house_selling_model(chunks, r)[0], bar_width, alpha=opacity,color='darkred',label='Optimal') #Label #Label plt.xlabel('Stops', size = 50) plt.ylabel('Load Values', size = 50) plt.title('Loads in each Run with N = {} for House Selling Model'.format(chunks), size = 60) plt.xticks(index + (bar_width/2), tuple(range(1,n_groups_house+1))) plt.xticks(fontsize= 30) plt.yticks(fontsize= 30) plt.xlim([0-bar_width/2,index.size]) plt.legend(prop={'size': 25}) plt.savefig('house_selling_figures/hs_{}_'.format(chunks) + time.strftime("%Y-%m-%d %H%M%S") + '.png') plt.figure(figsize=(30,25)) # Times Plot #Plot the achieved values of each observed sample rects2 = plt.bar(index, house_selling_model(chunks, r)[5], bar_width,alpha=opacity,color='darkblue',label='Time instance difference from optimal') plt.xlabel('Stops', size = 50) plt.ylabel('Time Instances', size = 50) plt.title('Times in each Run with N = {} for House Selling Model'.format(chunks), size = 60) plt.xticks(index, tuple(range(1,n_groups_house+1))) plt.xticks(fontsize= 30) plt.yticks(fontsize= 30) plt.xlim([0-bar_width/2,index.size]) plt.legend(prop={'size': 25}) plt.plot() plt.savefig('house_selling_figures/hs_times_{}_'.format(chunks) + time.strftime("%Y-%m-%d %H%M%S") + '.png') #Display the dataframe runs_data = {'Run': list(range(1,len(house_selling_model(chunks, r)[0])+1)),'Optimal': house_selling_model(chunks, r)[0],'Load when Offloading': house_selling_model(chunks, r)[1], 'Load Difference': house_selling_model(chunks, r)[2],} runs_frame = pd.DataFrame(runs_data, columns = ['Run','Optimal','Load when Offloading', 'Load Difference']) runs_frame.index += 1 display(runs_frame) runs_frame.to_csv('house_selling_figures/dataframes/hs_data_{}_'.format(chunks) + time.strftime("%Y-%m-%d %H%M%S") + '.csv') ``` # RANDOM AND SECRETARY MODELS Vs OPTIMAL ``` #Plot the different models (random(P) for different probabilities and seecretary model) to compare with the optimal for each model #Set the rpb_model(eg. rpb_200) and the secretary model(eg. secretary model(200)) def avg_loads_by_stop(rpb_model, secretary_model, house_selling_model): fig, ax = plt.subplots(1, 1,figsize=(30,25)) bar_width = 0.4 opacity = 0.8 optimal_means = [np.mean(rpb_model[0][0]),np.mean(rpb_model[1][0]),np.mean(rpb_model[2][0]),np.mean(rpb_model[3][0]), np.mean(rpb_model[4][0]), np.mean(secretary_model[0]), np.mean(house_selling_model[0])] achieved_means = [np.mean(rpb_model[0][1]),np.mean(rpb_model[1][1]),np.mean(rpb_model[2][1]),np.mean(rpb_model[3][1]), np.mean(rpb_model[4][1]),np.mean(secretary_model[1]), np.mean(house_selling_model[1])] all_means = np.array([np.mean(rpb_model[0][0]), np.mean(rpb_model[0][1]),np.mean(rpb_model[1][1]),np.mean(rpb_model[2][1]),np.mean(rpb_model[3][1]), np.mean(rpb_model[4][1]),np.mean(secretary_model[1]), np.mean(house_selling_model[1])]) comparison = all_means - all_means[0][None] comp = list(comparison) comp.pop(0) #Plot the achieved values of each observed samle rects2 = plt.bar(np.arange(8) + bar_width, all_means, bar_width,alpha=opacity,color = '#99ccff',label='Means') rects2[0].set_color('g') #Label x_ticks_labels = ['Optimal', 'Random(P = 0.05)','Random(P = 0.1)','Random(P = 0.2)','Random(P = 0.3)','Random(P = 0.5)', 'Secretary', 'House Selling'] plt.xlabel('Models', size = 40) plt.ylabel('Load Values', size = 40) plt.title('Avg Loads by Stop for each Model for selected Chunk', size=50) plt.xticks(np.arange(8) + bar_width/2, ('Optimal','Random(P = 0.05)','Random(P = 0.1)','Random(P = 0.2)','Random(P = 0.3)','Random(P = 0.5)', 'Secretary', 'House Selling'), rotation=35) plt.xticks(fontsize= 35) plt.yticks(fontsize= 35) # for p in ax.patches: # ax.annotate("%.2f" % p.get_height(), (p.get_x() + p.get_width() / 2., p.get_height()), # ha='center', va='center', rotation=0, xytext=(0, 20), textcoords='offset points') plt.legend(prop={'size': 25}) plt.savefig('averages/Averages for chosen N_' + time.strftime("%Y-%m-%d %H%M%S") + '.png') #Display the dataframe runs_data = {'Model': ['Random(P = 0.05)','Random(P = 0.1)','Random(P = 0.2)','Random(P = 0.3)','Random(P = 0.5)', 'Secretary', 'House Selling'], 'Optimal Means': optimal_means, 'Offloading Means': achieved_means, 'Mean Load Difference': comp} #np.array(achieved_means) - np.array(optimal_means)} runs_frame = pd.DataFrame(runs_data, columns = ['Model','Optimal Means', 'Offloading Means', 'Mean Load Difference']) runs_frame.index += 1 fig = plt.figure(figsize=(20,20)) ax1 = plt.subplot(111) ret = ax1.bar(runs_frame['Model'], runs_frame['Mean Load Difference'], color = '#99ccff') ret[np.where(runs_frame['Mean Load Difference'] == runs_frame['Mean Load Difference'].min())[0][0]].set_color('#404040') plt.xticks(fontsize= 30, rotation = 90) plt.yticks(fontsize= 30) plt.xlabel('Models', size = 40) plt.ylabel('Load Difference', size = 40) plt.title('Load Mean Differences', size = 50) for p in ax1.patches: ax1.annotate("%.2f" % p.get_height(), (p.get_x() + p.get_width() / 2., p.get_height()), ha='center', va='center', rotation=0, xytext=(0, 20), textcoords='offset points') plt.savefig('averages/Best_Model_' + time.strftime("%Y-%m-%d %H%M%S") + '.png') display(runs_frame) runs_frame.to_csv('averages/dataframes/averages_data_' + time.strftime("%Y-%m-%d %H%M%S") + '.csv') #These are the Random(P) probability models #ALL COMBINATIONS OF CHUNKS AND PROBABILITIES #RUN THESE BEFORE PROCEEDING TO ANALYSIS # rpb_20 = [random_prob_model(20, 0.05), # random_prob_model(20, 0.1), # random_prob_model(20, 0.2), # random_prob_model(20, 0.3), # random_prob_model(20, 0.5)] # rpb_50 = [random_prob_model(50, 0.05), # random_prob_model(50, 0.1), # random_prob_model(50, 0.2), # random_prob_model(50, 0.3), # random_prob_model(50, 0.5)] # rpb_80 = [random_prob_model(80, 0.05), # random_prob_model(80, 0.1), # random_prob_model(80, 0.2), # random_prob_model(80, 0.3), # random_prob_model(80, 0.5)] # rpb_100 = [random_prob_model(100, 0.05), # random_prob_model(100, 0.1), # random_prob_model(100, 0.2), # random_prob_model(100, 0.3), # random_prob_model(100, 0.5)] # rpb_150 = [random_prob_model(150, 0.05), # random_prob_model(150, 0.1), # random_prob_model(150, 0.2), # random_prob_model(150, 0.3), # random_prob_model(150, 0.5)] # rpb_200 = [random_prob_model(200, 0.05), # random_prob_model(200, 0.1), # random_prob_model(200, 0.2), # random_prob_model(200, 0.3), # random_prob_model(200, 0.5)] #EXAMPLES, run the models by changing the chunk number (eg. rpb_200) and the square bracket value for the Probability #Probabilities # 0 = 0.05 # 1 = 0.1 # 2 = 0.2 # 3 = 0.3 # 4 = 0.5 #Chunks N # 20,50,80,100,150,200 #For the House Selling model define chunks and the factor r (eg r = 0.1) # #MODELS # randomP_simulation_run(rpb_200[1],200) # secretary_simulation_run(200) # house_selling_simulation_run(200, 0) # avg_loads_by_stop(rpb_200, secretary_model(200), house_selling_model(200, 0.015)) # 50 0.052 # 100 0.064 # 150 0.046 # 200 0.015 def main(): user_input = str(input("Please enter the name of the .csv file you want to view: ")) print(file(user_input)) #Generate the dataset for the Random(P) Model rpb_20 = [random_prob_model(20, 0.05),random_prob_model(20, 0.1),random_prob_model(20, 0.2),random_prob_model(20, 0.3),random_prob_model(20, 0.5)] rpb_50 = [random_prob_model(50, 0.05),random_prob_model(50, 0.1),random_prob_model(50, 0.2),random_prob_model(50, 0.3),random_prob_model(50, 0.5)] rpb_80 = [random_prob_model(80, 0.05),random_prob_model(80, 0.1),random_prob_model(80, 0.2),random_prob_model(80, 0.3),random_prob_model(80, 0.5)] rpb_100 = [random_prob_model(100, 0.05),random_prob_model(100, 0.1),random_prob_model(100, 0.2),random_prob_model(100, 0.3),random_prob_model(100, 0.5)] rpb_150 = [random_prob_model(150, 0.05),random_prob_model(150, 0.1),random_prob_model(150, 0.2),random_prob_model(150, 0.3),random_prob_model(150, 0.5)] rpb_200 = [random_prob_model(200, 0.05),random_prob_model(200, 0.1),random_prob_model(200, 0.2),random_prob_model(200, 0.3),random_prob_model(200, 0.5)] loop = True while(loop): selection = str(input("You can choose from:\n 1 = Random(P) Model\n 2 = Secretary Model\n 3 = House Selling Model\n 4 = Average of Models\nEnter your selection: ")) if selection == '1': chunk_selection = int(input("Please enter the number of chunks you want to analyze. You can choose from [20,50,80,100,150,200]: ")) if chunk_selection == 20: probability_selection = int(input("Please enter the probability you want.\n\nYou can choose from:\n 0 = 0.05\n 1 = 0.1\n 2 = 0.2\n 3 = 0.3\n 4 = 0.5\n\nEnter your selection: ")) randomP_simulation_run(rpb_20[probability_selection], chunk_selection) if chunk_selection == 50: probability_selection = int(input("Please enter the probability you want.\n\n\nYou can choose from:\n 0 = 0.05\n 1 = 0.1\n 2 = 0.2\n 3 = 0.3\n 4 = 0.5\n\nEnter your selection: ")) randomP_simulation_run(rpb_50[probability_selection], chunk_selection) if chunk_selection == 80: probability_selection = int(input("Please enter the probability you want.\n\n\nYou can choose from:\n 0 = 0.05\n 1 = 0.1\n 2 = 0.2\n 3 = 0.3\n 4 = 0.5\n\nEnter your selection: ")) randomP_simulation_run(rpb_80[probability_selection], chunk_selection) if chunk_selection == 100: probability_selection = int(input("Please enter the probability you want.\n\n\nYou can choose from:\n 0 = 0.05\n 1 = 0.1\n 2 = 0.2\n 3 = 0.3\n 4 = 0.5\n\nEnter your selection: ")) randomP_simulation_run(rpb_100[probability_selection], chunk_selection) if chunk_selection == 150: probability_selection = int(input("Please enter the probability you want.\n\n\nYou can choose from:\n 0 = 0.05\n 1 = 0.1\n 2 = 0.2\n 3 = 0.3\n 4 = 0.5\n\nEnter your selection: ")) randomP_simulation_run(rpb_150[probability_selection], chunk_selection) if chunk_selection == 200: probability_selection = int(input("Please enter the probability you want.\n\n\nYou can choose from:\n 0 = 0.05\n 1 = 0.1\n 2 = 0.2\n 3 = 0.3\n 4 = 0.5\n\nEnter your selection: ")) randomP_simulation_run(rpb_200[probability_selection], chunk_selection) print("\nYour result figures have been saved. You can view them in the /randomp_figures/ folder!\n\n") elif selection == '2': chunk_selection = int(input("Please enter the number of chunks you want to analyze. You can choose from [20,50,80,100,150,200]: ")) secretary_simulation_run(chunk_selection) print("\nYour result figures have been saved. You can view them in the /secretary_figures/ folder!\n\n") elif selection == '3': chunk_selection = int(input("Please enter the number of chunks you want to analyze. You can choose from [20,50,80,100,150,200]: ")) r_factor = float(input("Please enter the R factor you want to use: ")) house_selling_simulation_run(chunk_selection,r_factor) print("\nYour result figures have been saved. You can view them in the /house_selling_figures/ folder!\nDataframe .csv is in the /dataframes/ folder\n\n") elif selection == '4': chunk_selection = int(input("Please enter the number of chunks you want to analyze. You can choose from [20,50,80,100,150,200]: ")) if chunk_selection == 20: r_factor = float(input("Please enter the R factor you want to use: ")) avg_loads_by_stop(rpb_20, secretary_model(chunk_selection), house_selling_model(chunk_selection, r_factor)) if chunk_selection == 50: r_factor = float(input("Please enter the R factor you want to use: ")) avg_loads_by_stop(rpb_50, secretary_model(chunk_selection), house_selling_model(chunk_selection, r_factor)) if chunk_selection == 80: r_factor = float(input("Please enter the R factor you want to use: ")) avg_loads_by_stop(rpb_80, secretary_model(chunk_selection), house_selling_model(chunk_selection, r_factor)) if chunk_selection == 100: r_factor = float(input("Please enter the R factor you want to use: ")) avg_loads_by_stop(rpb_100, secretary_model(chunk_selection), house_selling_model(chunk_selection, r_factor)) if chunk_selection == 150: r_factor = float(input("Please enter the R factor you want to use: ")) avg_loads_by_stop(rpb_150, secretary_model(chunk_selection), house_selling_model(chunk_selection, r_factor)) if chunk_selection == 200: r_factor = float(input("Please enter the R factor you want to use: ")) avg_loads_by_stop(rpb_200, secretary_model(chunk_selection), house_selling_model(chunk_selection, r_factor)) print("\nYour result figures have been saved. You can view them in the /averages/ folder!\nDataframe .csv is in the /dataframes/ folder\n\n") else: print("Error! Please enter a valid selection!\n") repeat = str(input("Do you want to repeat? If not type 'exit' or 'N' to go back. Else enter 'Y' to continue: ")) while (repeat != 'Y' and repeat != 'N' and repeat != 'exit' ): print("Sorry! I didn't understand that! :( Please enter a valid selection!\n") repeat = str(input("Do you want to repeat? If not type 'exit' or 'N' to go back. Else enter 'Y' to continue: ")) if repeat == 'Y': loop = True elif repeat == 'N' or repeat == 'exit': print("Terminating......") loop = False return if __name__ == "__main__": main() ```
github_jupyter
``` # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd import cv2 # Using glob to read all pokemon images at once # Don't forget to change the path when copying this project import glob images = [cv2.imread(file) for file in glob.glob("C:/Users/Rahul/Desktop/data/Pikachu/*.jpg")] images_1 = [cv2.imread(file) for file in glob.glob("C:/Users/Rahul/Desktop/data/Butterfree/*.jpg")] images_2 = [cv2.imread(file) for file in glob.glob("C:/Users/Rahul/Desktop/data/Ditto/*.jpg")] images, images_1, images_2 # Scaling and resizing all the Pikachu images and saving the result in a new list called mera_dat mera_dat = [] for i in range(199): desired_size = 368 im = images[i] old_size = im.shape[:2] # old_size is in (height, width) format ratio = float(desired_size)/max(old_size) new_size = tuple([int(x*ratio) for x in old_size]) # new_size should be in (width, height) format im = cv2.resize(im, (new_size[1], new_size[0])) delta_w = desired_size - new_size[1] delta_h = desired_size - new_size[0] top, bottom = delta_h//2, delta_h-(delta_h//2) left, right = delta_w//2, delta_w-(delta_w//2) color = [0, 0, 0] new_im = cv2.copyMakeBorder(im, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # cv2.imshow("image", new_im) # cv2.waitKey(0) # cv2.destroyAllWindows() # # cv2.imwrite('C:/Users/Rahul/Desktop/a.jpg'.format(i), new_im) mera_dat.append(new_im) # Scaling and resizing all the Butterfree images and saving the result in a new list called mera_dat mera_dat_1 = [] for i in range(66): desired_size = 368 im = images_1[i] old_size = im.shape[:2] # old_size is in (height, width) format ratio = float(desired_size)/max(old_size) new_size = tuple([int(x*ratio) for x in old_size]) # new_size should be in (width, height) format im = cv2.resize(im, (new_size[1], new_size[0])) delta_w = desired_size - new_size[1] delta_h = desired_size - new_size[0] top, bottom = delta_h//2, delta_h-(delta_h//2) left, right = delta_w//2, delta_w-(delta_w//2) color = [0, 0, 0] new_im = cv2.copyMakeBorder(im, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # cv2.imshow("image", new_im) # cv2.waitKey(0) # cv2.destroyAllWindows() # # cv2.imwrite('C:/Users/Rahul/Desktop/a.jpg'.format(i), new_im) mera_dat_1.append(new_im) # Scaling and resizing all the Ditto images and saving the result in a new list called mera_dat_2 mera_dat_2 = [] for i in range(56): desired_size = 368 im = images_2[i] old_size = im.shape[:2] # old_size is in (height, width) format ratio = float(desired_size)/max(old_size) new_size = tuple([int(x*ratio) for x in old_size]) # new_size should be in (width, height) format im = cv2.resize(im, (new_size[1], new_size[0])) delta_w = desired_size - new_size[1] delta_h = desired_size - new_size[0] top, bottom = delta_h//2, delta_h-(delta_h//2) left, right = delta_w//2, delta_w-(delta_w//2) color = [0, 0, 0] new_im = cv2.copyMakeBorder(im, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # cv2.imshow("image", new_im) # cv2.waitKey(0) # cv2.destroyAllWindows() # # cv2.imwrite('C:/Users/Rahul/Desktop/a.jpg'.format(i), new_im) mera_dat_2.append(new_im) # Converting the preprocessed and resized list into numpy arrays and performing normalization arr = np.array(mera_dat) arr = arr.reshape((199, 406272)) ar1 = np.array(mera_dat_1) ar1 = ar1.reshape((66, 406272)) ar2 = np.array(mera_dat_2) ar2 = ar2.reshape((56, 406272)) arr = arr / 255 ar1 = ar1 / 255 ar2 = ar2 / 255 # Scaled Images in numpy ndarray data structure arr, ar1, ar2 # Converting the numpy arrays to pandas dataframe structure # Generating labels for different pokemons # label 1 is for Pikachu # label 0 is for Butterfree # label 2 is for Ditto dataset = pd.DataFrame(arr) dataset['label'] = np.ones(199) dataset.iloc[:, -1] dataset_1 = pd.DataFrame(ar1) dataset_1['label'] = np.zeros(66) dataset_1.iloc[:, -1] dataset_2 = pd.DataFrame(ar2) dataset_2['label'] = np.array(np.ones(56) + np.ones(56)) dataset_2.iloc[:, -1] # Concatenating everything into a master dataframe dataset_master = pd.concat([dataset, dataset_1, dataset_2]) dataset_master # Splitting the dataset into feature matrix 'X' and vector of predictions 'y' X = dataset_master.iloc[:, 0:406272].values y = dataset_master.iloc[:, -1].values X, y # Implementing a simple ANN architecture for the classification problem import tensorflow as tf from tensorflow import keras model = keras.models.Sequential() model.add(keras.layers.Dense(256, activation = 'relu')) model.add(keras.layers.Dense(128, activation = 'relu')) model.add(keras.layers.Dense(3, activation = 'softmax')) model.compile(loss = 'sparse_categorical_crossentropy', optimizer = 'adam', metrics = ['accuracy']) history = model.fit(X, y, epochs = 5) # Visualizing the results pd.DataFrame(history.history).plot(figsize = (8, 5)) plt.grid(True) plt.gca().set_ylim(0, 1) plt.show() ```
github_jupyter
# **0) Imports** ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import re import pathlib import glob import os !git clone https://github.com/loier13/IEOR235.git # set option below so Pandas dataframe can output readable text, not truncated pd.set_option('display.max_colwidth', 0) ``` # **1) Open reviews** ``` all_reviews = pd.read_csv('IEOR235/all_reviews/all_reviews.csv', sep = ';') def clean_reviews(data): data['pros'] = data['pros'].astype(str).apply(lambda x: '. '.join(x.split('\n'))) data['cons'] = data['cons'].astype(str).apply(lambda x: '. '.join(x.split('\n'))) data.drop_duplicates(inplace = True) data = data[['pros']].reset_index() data.columns = ['Id', 'text'] return data all_reviews = clean_reviews(all_reviews) display(all_reviews.head()) display(all_reviews.info()) ``` # **2) Naive topic detection** Topic detection by keywords. ``` E_keywords = ['renewable', 'recycl', 'reuse', 'compost', 'recovery', 'ecocide', 'bio', 'carbon', 'forest', 'sustainable', 'renewable', 'pollut', 'emissions', 'green', 'co2', 'ch4', 'n2o', 'hfcs', 'pfcs', 'sf6', 'nf3', 'cfc-11', 'nox', 'sox', 'warming', 'climate', 'waste', 'garbage', 'trash', 'disposal', 'landfill', 'chemicals', 'acidification', 'fossil', 'eutrophication', 'environmental', 'consumption', 'water', 'resource', 'ecosystem', 'ecology', 'incineration', 'ozone', 'natural', 'solar', 'biomass', 'air', 'soil', 'dioxide', 'footprint', 'geoengineering'] S_keywords = ['labor', 'health', 'safe', 'human', 'standards', 'quality', 'life', 'privacy', 'private', 'responsib', 'insur', 'risk', 'care', 'opportunit', 'resource'] G_keywords = ['corrupt', 'management', 'board', 'pay', 'fair', 'owner', 'account', 'ethics', 'competit', 'practice', 'stable', 'stabilit', 'system', 'transparen'] def naive_topic_detection(data, topic, keywords): """ For this prototype we have a naive topic detection algorithms by keywords. We may have a suboptimal precision and recall. """ output = data.copy() output[f'{topic}_naive'] = data['text'].apply(lambda x: any([x.lower().find(word) >=0 for word in keywords])).astype(int) return output all_reviews_E = naive_topic_detection(all_reviews, 'E', E_keywords) all_reviews_S = naive_topic_detection(all_reviews, 'S', S_keywords) all_reviews_G = naive_topic_detection(all_reviews, 'G', G_keywords) display(all_reviews_E.head()) ``` # **3) Manual annotation** We voluntarily separate E, S and G instead of multiclass labeling in order to implement different better trained classifiers on these overlapping classes. So we proceed to E, S and G labelling in the following sections. ``` %%capture --no-display !pip install superintendent from superintendent.distributed import ClassLabeller ``` ### **a. Environment** ``` all_reviews_E['E'] = np.nan active_E = all_reviews_E[all_reviews_E.E_naive == 1] widget_E = ClassLabeller( features=active_E[active_E['E'].isnull()]['text'].tolist(), options=[ "E", "Non-E" ] ) widget_E active_E['E'] = active_E['E'].map({"E":1, "non-E": 0}) active_E.head() non_E = all_reviews_E[all_reviews_E.E_naive == 0] non_E['E'] = 0 final_E = pd.concat([non_E, active_E]) final_E.to_csv('reviews_E_labeled.csv', sep = ';') ``` The final dataset final_E is saved and will be used in the next notebook for classification purposes. ### **b. Social** ``` all_reviews_S['S'] = np.nan active_S = all_reviews_S[all_reviews_S.S_naive == 1] widget_S = ClassLabeller( features=active_S[active_S['S'].isnull()]['text'].tolist(), options=[ "S", "Non-S" ] ) widget_S active_S['S'] = active_S['S'].map({"S":1, "non-S": 0}) active_S.head() non_S = all_reviews_S[all_reviews_S.S_naive == 0] non_S['S'] = 0 final_S = pd.concat([non_S, active_S]) final_S.to_csv('reviews_S_labeled.csv', sep = ';') ``` ### **c. Governance** ``` all_reviews_G['G'] = np.nan active_G = all_reviews_G[all_reviews_G.G_naive == 1] widget_G = ClassLabeller( features=active_G[active_G['G'].isnull()]['text'].tolist(), options=[ "G", "Non-G" ] ) widget_G active_G['G'] = active_G['G'].map({"G":1, "non-G": 0}) active_G.head() non_G = all_reviews_G[all_reviews_G.G_naive == 0] non_G['G'] = 0 final_G = pd.concat([non_G, active_G]) final_G.to_csv('reviews_G_labeled.csv', sep = ';') ```
github_jupyter
# Notebook used to visualize the daily distribution of electrical events, as depicted in the data descriptor ## Load packages and basic dataset information ``` import numpy as np import matplotlib.pyplot as plt import matplotlib.dates as mdates from sklearn.preprocessing import MinMaxScaler from matplotlib import patches import h5py import pandas as pd import os import sys from pathlib import Path from datetime import datetime from datetime import timedelta import math import seaborn as sns import pdb import scipy # Add project path to path for import project_path = os.path.abspath("..") if project_path not in sys.path: sys.path.append(project_path) # Add module path to path for import module_path = os.path.abspath("../data_utility/data_utility.py") if module_path not in sys.path: sys.path.append(module_path) from data_utility import CREAM_Day # class to work with a day of the CREAM Dataset # Intentional replication is necessary %load_ext autoreload # Reload all modules every time before executing the Python code typed. %autoreload 2 # Import some graphical modules from IPython.display import display, clear_output from ipywidgets import Button, Layout, ButtonStyle, HBox, VBox, widgets, Output from IPython.display import SVG, display, clear_output import subprocess import glob PATH_TO_DATA = os.path.abspath(os.path.join("..", "..","rbgstorage", "nilm", "i13-dataset", "CREAM")) def create_time_bin(hours : float, minutes : float) -> str: """ Creates a hour:minutes timestamp, ceiled to full 30 minutes. All minutes below 15, become 0. All between 15 and 45 minutes, become 30 minutes. All minutes between 45 and 60 become 0 and belong to the next hour. """ if minutes < 15: minutes = "00" elif minutes >= 15 and minutes < 45: minutes = "30" elif minutes >= 45: minutes = "00" hours += 1 if hours < 10: hours = "0" + str(hours) else: hours = str(hours) return hours + ":" + minutes def get_distribution(path_to_data, machine_name): path_to_data = os.path.join(path_to_data, machine_name) all_days = glob.glob(os.path.join(path_to_data, "*")) all_days = [os.path.basename(d) for d in all_days if "2018" in os.path.basename(d) or "2019" in os.path.basename(d) ] all_days.sort() # Load the events day_path = os.path.join(path_to_data, all_days[0]) #arbitrary day to initialize the object current_CREAM_day = CREAM_Day(cream_day_location=day_path,use_buffer=True, buffer_size_files=2) # Load the electrical component events (the raw ones) if machine == "X9": all_component_events = current_CREAM_day.load_component_events(os.path.join(path_to_data, "component_events_coarse.csv"), filter_day=False) else: all_component_events = current_CREAM_day.load_component_events(os.path.join(path_to_data, "component_events.csv"), filter_day=False) # Load the product and the maintenance events (the raw ones, per minute events) and filter for the day all_maintenance_events = current_CREAM_day.load_machine_events(os.path.join(path_to_data, "maintenance_events.csv"), raw_file=False, filter_day=False) all_product_events = current_CREAM_day.load_machine_events(os.path.join(path_to_data, "product_events.csv"), raw_file=False, filter_day=False) # create a new column with: hour:30, hour:0 in it for the x-axis as the labels all_component_events["Time_Bin"] = all_component_events.Timestamp.apply(lambda x: create_time_bin(x.hour, x.minute)) times, counts = np.unique(all_component_events["Time_Bin"] , return_counts=True) return times, counts ``` # Plot of the daily distribution of electrical events ``` # Create the figure fig, axes = plt.subplots(2, 1, sharex=True, sharey=True, figsize=(28,8)) # Iterate over the machines for i, machine in enumerate(["X8", "X9"]): # get the axis object ax = axes[i] # get the count information for the barplot times, counts = get_distribution(path_to_data=PATH_TO_DATA, machine_name=machine) # scale the counts between 0 and 1 counts = counts / np.max(counts) title_text = "Daily, scaled distribution of electrical events (Jura GIGA " + machine + ")" ax.set_title(label = title_text, fontdict={'fontsize': 24}) ax.set_ylabel("Events", fontsize=24) ax.tick_params(axis="both", labelsize=24, rotation=90) # ax.set_ylim(0, 20000) sns.barplot(x=times, y=counts,color="b", ax=ax) plt.xlabel("Time", fontsize=24) plt.tight_layout() plt.savefig("./Figure_3_BOTH.pdf") plt.show() ```
github_jupyter
# Baseline training on network and other features besides text content ``` import numpy as np import pandas as pd from sklearn.dummy import DummyClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import classification_report from sklearn.neural_network import MLPClassifier ``` # Data loading ``` # Data paths TRAIN = "../../data/prepared/train_features.pkl" VAL = "../../data/prepared/val_features.pkl" TEST = "../../data/prepared/test_features.pkl" train_df = pd.read_pickle(TRAIN) train_df.info() train_df_labels = train_df.retweet_label train_df.drop(["retweet_label", "id_str"], axis=1, inplace=True) val_df = pd.read_pickle(VAL) val_df.info() val_df_labels = val_df.retweet_label val_df.drop(["retweet_label", "id_str"], axis=1, inplace=True) test_df = pd.read_pickle(TEST) test_df.info() test_df_labels = test_df.retweet_label test_df.drop(["retweet_label", "id_str"], axis=1, inplace=True) ``` # MLP Training ``` clf = MLPClassifier( max_iter=50, hidden_layer_sizes=(512,), random_state=1, verbose=True, early_stopping=True, validation_fraction=0.1, n_iter_no_change=5, learning_rate_init=0.001, batch_size=256) clf.fit(train_df.values, train_df_labels.values) clf.best_validation_score_ clf.score(train_df.values, train_df_labels.values) clf.score(val_df.values, val_df_labels.values) val_predictions = clf.predict(val_df.values) val_predictions.shape out = classification_report(val_df_labels.values, val_predictions, output_dict=False) print(out) ``` ## MLP Classifier (2) ``` clf_2 = MLPClassifier( max_iter=50, hidden_layer_sizes=(1000,50,30), random_state=1, verbose=True, early_stopping=True, validation_fraction=0.1, n_iter_no_change=5, learning_rate_init=0.001, batch_size=32) clf_2.fit(train_df.values, train_df_labels.values) clf_2.best_validation_score_ clf_2.score(train_df.values, train_df_labels.values) clf_2.score(val_df.values, val_df_labels.values) val_predictions = clf_2.predict(val_df.values) val_predictions.shape out = classification_report(val_df_labels.values, val_predictions, output_dict=False) print(out) ``` # Random Forest ``` rf = RandomForestClassifier( n_estimators=200, max_depth=25, min_samples_split=0.00002, min_samples_leaf=0.00002, random_state=1, verbose=True, n_jobs=-1, max_samples=0.4, max_features=0.2, oob_score=True, class_weight="balanced", min_impurity_decrease=0.00008 ) rf.fit(train_df.values, train_df_labels.values) rf.score(train_df.values, train_df_labels.values) rf.score(val_df.values, val_df_labels.values) rf_val_predictions = rf.predict(val_df.values) out = classification_report(val_df_labels.values, rf_val_predictions, output_dict=False, digits=3) print(out) ``` # Dummy classifier ``` s_dummy = DummyClassifier(strategy="stratified", random_state=1) s_dummy.fit(train_df.values, train_df_labels.values) dummy_val_predictions = s_dummy.predict(val_df.values) out = classification_report(val_df_labels.values, dummy_val_predictions, output_dict=False) print(out) ```
github_jupyter
# Steam equilibrating with liquid water Accident scenario: steam leaks into a rigid, insulated tank that is partially filled with water. The steam and liquid water are not initially at thermal equilibrium, though they are at the same pressure. The steam is at temperature $T_{s,1}$ = 600 C and pressure $P_1$ = 20 MPa. The liquid water is initially at $T_{\text{liq},1}$ = 40 C and pressure $P_1$ = 20 MPa. The total volume of the tank is $V$ = 10 m$^3$ and the volume of the liquid water initially in the tank is $V_{\text{liq},1} = 1 \; \text{m}^3$. Eventually, the contents of the tank reach a uniform temperature and pressure, $T_2$ and $P_2$. The tank is well-insulated and rigid. **Problem:** Determine the final temperature and pressure of the water in the tank. ``` # load necessary modules # Numpy adds some useful numerical types and functions import numpy as np # Cantera will handle thermodynamic properties import cantera as ct # Pint gives us some helpful unit conversion from pint import UnitRegistry ureg = UnitRegistry() Q_ = ureg.Quantity ``` First, what are the initial states of the steam and liquid? ``` steam = ct.Water() temp_steam1 = Q_(600, 'degC') pres1 = Q_(20, 'MPa') steam.TP = temp_steam1.to('K').magnitude, pres1.to('Pa').magnitude steam() liquid = ct.Water() temp_liquid1 = Q_(40, 'degC') liquid.TP = temp_liquid1.to('K').magnitude, pres1.to('Pa').magnitude liquid() ``` State $s,1$ is in the superheated vapor region (vapor fraction: 1) and state $\text{liq},1$ is in the compressed liquid region (vapor fraction: 0). We can calculate the mass of liquid water in the tank, and then determine the volume and mass of steam: \begin{align} m_{\text{liq},1} &= \frac{V_{\text{liq},1}}{v_{\text{liq},1}} \\ V_{s,1} &= V_{\text{tank}} - V_{\text{liq},1} \\ m_{s,1} &= \frac{V_{s,1}}{v_{s,1}} \end{align} ``` vol_tank = Q_(10, 'meter^3') vol_liquid1 = Q_(1, 'meter^3') mass_liquid1 = vol_liquid1 / Q_(liquid.v, 'm^3/kg') print(f'Mass of liquid at state 1: {mass_liquid1: .2f}') vol_steam1 = vol_tank - vol_liquid1 mass_steam1 = vol_steam1 / Q_(steam.v, 'm^3/kg') print(f'Mass of steam at state 1: {mass_steam1: .2f}') mass_1 = mass_liquid1 + mass_steam1 print(f'Total mass of system: {mass_1: .2f}') ``` Do a mass balance on the tank for going from state 1 to state 2 (after equilibrium): \begin{equation} \frac{dm}{dt} = m_2 - m_1 = 0 \end{equation} and so $m_2 = m_1$, meaning the mass of water in the tank does not change. We can then find the specific volume of water in the tank: \begin{equation} v_2 = \frac{V_{\text{tank}}}{m_2} \end{equation} The tank experiences no heat or work, and does not exhibit any bulk changes in kinetic or potential energy; we can do an energy balance on the tank for the process of going from state 1 to state 2: \begin{align} Q - W &= \Delta KE + \Delta PE + \Delta U \\ \rightarrow 0 &= U_2 - U_1 \\ 0 &= u_2 m_2 - \left( u_{\text{liq},1} m_{\text{liq},1} + u_{s,1} m_{s,1} \right) \end{align} Therefore, we can find the specific internal energy of the final state: \begin{equation} u_2 = \frac{ u_{\text{liq},1} m_{\text{liq},1} + u_{s,1} m_{s,1} }{m_2} \end{equation} ``` mass_2 = mass_1 spec_vol2 = vol_tank / mass_2 print(f'Specific volume of state 2: {spec_vol2: .2e}') int_energy2 = ( Q_(liquid.u, 'J/kg')*mass_liquid1 + Q_(steam.u, 'J/kg')*mass_steam1 ) / mass_2 int_energy2.ito('kilojoule/kg') print(f'Internal energy of state 2: {int_energy2: .2f}') water_equilibrium = ct.Water() water_equilibrium.UV = int_energy2.to('J/kg').magnitude, spec_vol2.to('m^3/kg').magnitude water_equilibrium() ``` So, at equilibrium, the tank contains a mixture of saturated liquid and vapor, with temperature and pressure: ``` final_temperature = Q_(water_equilibrium.T, 'K') final_pressure = Q_(water_equilibrium.P, 'Pa') print(f'Final temperature: {final_temperature: .2f}') print(f'Final pressure: {final_pressure.to(ureg.MPa): .2f}') ```
github_jupyter
``` import pandas as pd import matplotlib.pyplot as plt # for benchmarks # on 18000 frame episodes, average of 10 episodes soloRandomScores = { 'Alien-v0': 164.0,'Asteroids-v0': 815.0,'Atlantis-v0': 21100.0,'BankHeist-v0': 17.0, 'BattleZone-v0': 3300.0,'Bowling-v0': 20.2,'Boxing-v0': 2.4,'Centipede-v0': 2229.7, 'ChopperCommand-v0': 660.0,'DoubleDunk-v0': -19.2,'FishingDerby-v0': -92.2, 'Freeway-v0': 0.0,'Frostbite-v0': 53.0,'Gravitar-v0': 310.0,'Hero-v0': 1217.5, 'IceHockey-v0': -10.9,'Jamesbond-v0': 25.0,'Kangaroo-v0': 60.0,'Krull-v0': 1479.8, 'KungFuMaster-v0': 760.0,'MsPacman-v0': 246.0,'PrivateEye-v0': 40.0, 'RoadRunner-v0': 20.0, 'Skiing-v0': -16270.7, 'Tennis-v0': -24.0,'TimePilot-v0': 3190.0, 'UpNDown-v0': 422.0,'Venture-v0': 0.0,'WizardOfWor-v0': 750.0,'Zaxxon-v0': 0.0} soloTpgScores = { 'Alien-v0': 3382.7,'Asteroids-v0': 3050.7,'Atlantis-v0': 89653,'BankHeist-v0': 1051, 'BattleZone-v0': 47233.4,'Bowling-v0': 223.7,'Boxing-v0': 76.5,'Centipede-v0': 34731.7, 'ChopperCommand-v0': 7070,'DoubleDunk-v0': 2,'FishingDerby-v0': 49, 'Freeway-v0': 28.9,'Frostbite-v0': 8144.4,'Gravitar-v0': 786.7,'Hero-v0': 16545.4, 'IceHockey-v0': 10,'Jamesbond-v0': 3120,'Kangaroo-v0': 14780,'Krull-v0': 12850.4, 'KungFuMaster-v0': 43353.4,'MsPacman-v0': 5156,'PrivateEye-v0': 15028.3, 'RoadRunner-v0': 17410, 'Skiing-v0': 0, 'Tennis-v0': 1,'TimePilot-v0': 13540, 'RoadRunner-v0': 17410,'Tennis-v0': 0,'TimePilot-v0': 13540, 'UpNDown-v0': 34416,'Venture-v0': 576.7,'WizardOfWor-v0': 5196.7,'Zaxxon-v0': 6233.4} df = pd.read_csv('individuals.txt') envDfs = [] for envName in sorted(pd.unique(df.envName)): envDfs.append(df.loc[df['envName'] == envName]) # 10 colors in cycle plt.figure(figsize=(8,10)) cnt = 0 lineStyles = ['-', '--', '-.'] lsi = 0 for edf in envDfs: cnt += 1 plt.plot(((edf.tpgMax-soloRandomScores[edf.envName.iloc[0]])/ (soloTpgScores[edf.envName.iloc[0]]-soloRandomScores[edf.envName.iloc[0]])).tolist(), label=edf.envName.iloc[0], ls=lineStyles[lsi]) if cnt == 10: cnt = 0 lsi += 1 plt.legend(loc=2, bbox_to_anchor=(1.01, 1.0)) plt.ylim(-0.2,3.55) plt.xlabel('Generation') plt.ylabel('NormalizedScore') plt.title('TPG Scores on Various Environments Trained Individually') plt.show() df = pd.read_csv('15-shrink-novir.txt') envDfs = [] lengths = {} for envName in sorted(pd.unique(df.envName)): envDfs.append(df.loc[df['envName'] == envName]) lengths[envName] = len(envDfs[-1]) print(lengths) # 10 colors in cycle plt.figure(figsize=(4,5)) cnt = 0 lineStyles = ['-', '--', '-.'] lsi = 0 for edf in envDfs: cnt += 1 #print(edf.envName + ': ' + str(max(((edf.tpgMax-soloRandomScores[edf.envName.iloc[0]])/ # (soloTpgScores[edf.envName.iloc[0]]-soloRandomScores[edf.envName.iloc[0]])).tolist()))) plt.plot(((edf.tpgMax-soloRandomScores[edf.envName.iloc[0]])/ (soloTpgScores[edf.envName.iloc[0]]-soloRandomScores[edf.envName.iloc[0]])).tolist(), label=edf.envName.iloc[0], ls=lineStyles[lsi]) if cnt == 10: cnt = 0 lsi += 1 plt.legend(loc=2, bbox_to_anchor=(1.01, 1.0)) plt.ylim(-0.25,1.5) plt.xlim(0,250) plt.xlabel('Environment Exposures') #plt.ylabel('Score') plt.title('TPG Scores on 15 Environments without Virulence') plt.show() df = pd.read_csv('15-shrink-vir.txt') envDfs = [] lengths = {} for envName in sorted(pd.unique(df.envName)): envDfs.append(df.loc[df['envName'] == envName]) lengths[envName] = len(envDfs[-1]) print(lengths) # 10 colors in cycle plt.figure(figsize=(4,5)) cnt = 0 lineStyles = ['-', '--', '-.'] lsi = 0 for edf in envDfs: cnt += 1 #print(edf.envName + ': ' + str(max(((edf.tpgMax-soloRandomScores[edf.envName.iloc[0]])/ # (soloTpgScores[edf.envName.iloc[0]]-soloRandomScores[edf.envName.iloc[0]])).tolist()))) plt.plot(((edf.tpgMax-soloRandomScores[edf.envName.iloc[0]])/ (soloTpgScores[edf.envName.iloc[0]]-soloRandomScores[edf.envName.iloc[0]])).tolist(), label=edf.envName.iloc[0], ls=lineStyles[lsi]) if cnt == 10: cnt = 0 lsi += 1 #plt.legend(loc=2, bbox_to_anchor=(1.01, 1.0)) plt.ylim(-0.25,1.5) plt.xlim(0,250) plt.xlabel('Environment Exposures') plt.ylabel('Score') plt.title('TPG Scores on 15 Environments with Virulence') plt.show() df1 = pd.read_csv('15-shrink-novir.txt') df2 = pd.read_csv('15-shrink-vir.txt') envDfs1 = [] envDfs2 = [] for envName in sorted(pd.unique(df1['envName'])): tmpDf = pd.DataFrame(df1.loc[df1['envName'] == envName] .reset_index(drop=True)) tmpDf['tpgMax'] = ((tmpDf['tpgMax']-soloRandomScores[envName])/ (soloTpgScores[envName]-soloRandomScores[envName])) envDfs1.append(pd.DataFrame(tmpDf['tpgMax'])) tmpDf = pd.DataFrame(df2.loc[df2['envName'] == envName] .reset_index(drop=True)) tmpDf['tpgMax'] = ((tmpDf['tpgMax']-soloRandomScores[envName])/ (soloTpgScores[envName]-soloRandomScores[envName])) envDfs2.append(pd.DataFrame(tmpDf['tpgMax'])) meansNoVir = pd.concat(envDfs1, axis=1).mean(axis=1).values meansVir = pd.concat(envDfs2, axis=1).mean(axis=1).values plt.plot(meansVir[:100], label='With Virulence') plt.plot(meansNoVir[:185], label='Without Virulence') plt.legend(loc=2, bbox_to_anchor=(1.01, 1.0)) plt.ylim(0,1) plt.xlabel('Environment Exposures') plt.ylabel('Mean Score') plt.title('Mean Scores across all Environments') plt.show() df = pd.read_csv('8-all-at-once.txt') envDfs = [] lengths = {} for envName in sorted(pd.unique(df.envName)): envDfs.append(df.loc[df['envName'] == envName]) lengths[envName] = len(envDfs[-1]) print(lengths) # 10 colors in cycle plt.figure(figsize=(8,10)) cnt = 0 lineStyles = ['-', '--', '-.'] lsi = 0 for edf in envDfs: cnt += 1 #print(edf.envName + ': ' + str(max(((edf.tpgMax-soloRandomScores[edf.envName.iloc[0]])/ # (soloTpgScores[edf.envName.iloc[0]]-soloRandomScores[edf.envName.iloc[0]])).tolist()))) plt.plot(((edf.tpgMax-soloRandomScores[edf.envName.iloc[0]])/ (soloTpgScores[edf.envName.iloc[0]]-soloRandomScores[edf.envName.iloc[0]])).tolist(), label=edf.envName.iloc[0], ls=lineStyles[lsi]) if cnt == 10: cnt = 0 lsi += 1 plt.legend(loc=2, bbox_to_anchor=(1.01, 1.0)) plt.ylim(-0.1,3.1) plt.xlabel('Generation') plt.ylabel('Score') plt.title('TPG Scores on 8 Environments (all at once)') plt.show() df = pd.read_csv('8-all-at-once-window-2.txt') envDfs = [] lengths = {} for envName in sorted(pd.unique(df.envName)): envDfs.append(df.loc[df['envName'] == envName]) lengths[envName] = len(envDfs[-1]) print(lengths) # 10 colors in cycle plt.figure(figsize=(8,10)) cnt = 0 lineStyles = ['-', '--', '-.'] lsi = 0 for edf in envDfs: cnt += 1 plt.plot(((edf.tpgMax-soloRandomScores[edf.envName.iloc[0]])/ (soloTpgScores[edf.envName.iloc[0]]-soloRandomScores[edf.envName.iloc[0]])).tolist(), label=edf.envName.iloc[0], ls=lineStyles[lsi]) if cnt == 10: cnt = 0 lsi += 1 plt.legend(loc=2, bbox_to_anchor=(1.01, 1.0)) plt.ylim(-0.1,2.52) plt.xlabel('Generation') plt.ylabel('Score') plt.title('TPG Scores on 8 Environments (2 at a time)') plt.show() df = pd.read_csv('8-all-at-once-window-4.txt') envDfs = [] lengths = {} for envName in sorted(pd.unique(df.envName)): envDfs.append(df.loc[df['envName'] == envName]) lengths[envName] = len(envDfs[-1]) print(lengths) # 10 colors in cycle plt.figure(figsize=(8,10)) cnt = 0 lineStyles = ['-', '--', '-.'] lsi = 0 for edf in envDfs: cnt += 1 #print(edf.envName + ': ' + str(max(((edf.tpgMax-soloRandomScores[edf.envName.iloc[0]])/ # (soloTpgScores[edf.envName.iloc[0]]-soloRandomScores[edf.envName.iloc[0]])).tolist()))) plt.plot(((edf.tpgMax-soloRandomScores[edf.envName.iloc[0]])/ (soloTpgScores[edf.envName.iloc[0]]-soloRandomScores[edf.envName.iloc[0]])).tolist(), label=edf.envName.iloc[0], ls=lineStyles[lsi]) if cnt == 10: cnt = 0 lsi += 1 plt.legend(loc=2, bbox_to_anchor=(1.01, 1.0)) plt.ylim(-0.1,2.52) plt.xlabel('Generation') plt.ylabel('Score') plt.title('TPG Scores on 8 Environments (4 at a time)') plt.show() df = pd.read_csv('8-all-at-once-window-4-2.txt') envDfs = [] lengths = {} for envName in sorted(pd.unique(df.envName)): envDfs.append(df.loc[df['envName'] == envName]) lengths[envName] = len(envDfs[-1]) print(lengths) # 10 colors in cycle plt.figure(figsize=(8,10)) cnt = 0 lineStyles = ['-', '--', '-.'] lsi = 0 for edf in envDfs: cnt += 1 #print(edf.envName + ': ' + str(max(((edf.tpgMax-soloRandomScores[edf.envName.iloc[0]])/ # (soloTpgScores[edf.envName.iloc[0]]-soloRandomScores[edf.envName.iloc[0]])).tolist()))) plt.plot(((edf.tpgMax-soloRandomScores[edf.envName.iloc[0]])/ (soloTpgScores[edf.envName.iloc[0]]-soloRandomScores[edf.envName.iloc[0]])).tolist(), label=edf.envName.iloc[0], ls=lineStyles[lsi]) if cnt == 10: cnt = 0 lsi += 1 plt.legend(loc=2, bbox_to_anchor=(1.01, 1.0)) plt.ylim(-0.1,2.52) plt.xlabel('Generation') plt.ylabel('Score') plt.title('TPG Scores on 8 Environments (4 at a time)') plt.show() df = pd.read_csv('8-merge.txt') envDfs = [] lengths = {} for envName in sorted(pd.unique(df.envName)): envDfs.append(df.loc[df['envName'] == envName]) lengths[envName] = len(envDfs[-1]) print(lengths) # 10 colors in cycle plt.figure(figsize=(8,10)) cnt = 0 lineStyles = ['-', '--', '-.'] lsi = 0 for edf in envDfs: cnt += 1 #print(edf.envName + ': ' + str(max(((edf.tpgMax-soloRandomScores[edf.envName.iloc[0]])/ # (soloTpgScores[edf.envName.iloc[0]]-soloRandomScores[edf.envName.iloc[0]])).tolist()))) plt.plot(((edf.tpgMax-soloRandomScores[edf.envName.iloc[0]])/ (soloTpgScores[edf.envName.iloc[0]]-soloRandomScores[edf.envName.iloc[0]])).tolist(), label=edf.envName.iloc[0], ls=lineStyles[lsi]) if cnt == 10: cnt = 0 lsi += 1 plt.legend(loc=2, bbox_to_anchor=(1.01, 1.0)) plt.ylim(0,3.1) plt.xlabel('Generation') plt.ylabel('Score') plt.title('TPG Scores on 8 Environments (all merged at once)') plt.show() df = pd.read_csv('8-merge-window-4.txt') envDfs = [] lengths = {} for envName in sorted(pd.unique(df.envName)): envDfs.append(df.loc[df['envName'] == envName]) lengths[envName] = len(envDfs[-1]) print(lengths) # 10 colors in cycle plt.figure(figsize=(8,10)) cnt = 0 lineStyles = ['-', '--', '-.'] lsi = 0 for edf in envDfs: cnt += 1 print(edf.envName + ': ' + str(max(((edf.tpgMax-soloRandomScores[edf.envName.iloc[0]])/ (soloTpgScores[edf.envName.iloc[0]]-soloRandomScores[edf.envName.iloc[0]])).tolist()))) plt.plot(((edf.tpgMax-soloRandomScores[edf.envName.iloc[0]])/ (soloTpgScores[edf.envName.iloc[0]]-soloRandomScores[edf.envName.iloc[0]])).tolist(), label=edf.envName.iloc[0], ls=lineStyles[lsi]) if cnt == 10: cnt = 0 lsi += 1 plt.legend(loc=2, bbox_to_anchor=(1.01, 1.0)) plt.ylim(0,3.1) plt.xlabel('Generation') plt.ylabel('Score') plt.title('TPG Scores on 8 Environments (merged 4 at a time)') plt.show() df1 = pd.read_csv('8-all-at-once.txt') df2 = pd.read_csv('8-all-at-once-window-2.txt') df3 = pd.read_csv('8-all-at-once-window-4.txt') envDfs1 = [] envDfs2 = [] envDfs3 = [] for envName in sorted(pd.unique(df1['envName'])): tmpDf = pd.DataFrame(df1.loc[df1['envName'] == envName] .reset_index(drop=True)) tmpDf['tpgMax'] = ((tmpDf['tpgMax']-soloRandomScores[envName])/ (soloTpgScores[envName]-soloRandomScores[envName])) envDfs1.append(pd.DataFrame(tmpDf['tpgMax'])) tmpDf = pd.DataFrame(df2.loc[df2['envName'] == envName] .reset_index(drop=True)) tmpDf['tpgMax'] = ((tmpDf['tpgMax']-soloRandomScores[envName])/ (soloTpgScores[envName]-soloRandomScores[envName])) envDfs2.append(pd.DataFrame(tmpDf['tpgMax'])) tmpDf = pd.DataFrame(df3.loc[df3['envName'] == envName] .reset_index(drop=True)) tmpDf['tpgMax'] = ((tmpDf['tpgMax']-soloRandomScores[envName])/ (soloTpgScores[envName]-soloRandomScores[envName])) envDfs3.append(pd.DataFrame(tmpDf['tpgMax'])) meansFullWindow = pd.concat(envDfs1, axis=1).mean(axis=1).values means2Window = pd.concat(envDfs2, axis=1).mean(axis=1).values means4Window = pd.concat(envDfs3, axis=1).mean(axis=1).values plt.plot(meansFullWindow[:184], label='Window Size Max') plt.plot(means2Window[:74], label='Window Size 2') plt.plot(means4Window[:76], label='Window Size 4') plt.legend(loc=2, bbox_to_anchor=(1.01, 1.0)) plt.ylim(0,1) plt.xlabel('Game Exposures') plt.ylabel('Mean Score') plt.title('Mean Scores accross all games (No Merge)') plt.show() df1 = pd.read_csv('8-merge.txt') df2 = pd.read_csv('8-merge-window-4.txt') envDfs1 = [] envDfs2 = [] for envName in sorted(pd.unique(df1['envName'])): tmpDf = pd.DataFrame(df1.loc[df1['envName'] == envName] .reset_index(drop=True)) tmpDf['tpgMax'] = ((tmpDf['tpgMax']-soloRandomScores[envName])/ (soloTpgScores[envName]-soloRandomScores[envName])) envDfs1.append(pd.DataFrame(tmpDf['tpgMax'])) tmpDf = pd.DataFrame(df2.loc[df2['envName'] == envName] .reset_index(drop=True)) tmpDf['tpgMax'] = ((tmpDf['tpgMax']-soloRandomScores[envName])/ (soloTpgScores[envName]-soloRandomScores[envName])) envDfs2.append(pd.DataFrame(tmpDf['tpgMax'])) meansFullWindow = pd.concat(envDfs1, axis=1).mean(axis=1).values means4Window = pd.concat(envDfs3, axis=1).mean(axis=1).values plt.plot(meansFullWindow[:117], label='Window Size Max') plt.plot(means4Window[:74], label='Window Size 4') plt.legend(loc=2, bbox_to_anchor=(1.01, 1.0)) plt.ylim(0,1) plt.xlabel('Game Exposures') plt.ylabel('Mean Score') plt.title('Mean Scores accross all games (Merge)') plt.show() df1 = pd.read_csv('8-all-at-once.txt') df2 = pd.read_csv('8-all-at-once-window-2.txt') df3 = pd.read_csv('8-all-at-once-window-4.txt') df4 = pd.read_csv('8-merge.txt') df5 = pd.read_csv('8-merge-window-4.txt') envDfs1 = [] envDfs2 = [] envDfs3 = [] envDfs4 = [] envDfs5 = [] for envName in sorted(pd.unique(df1['envName'])): tmpDf = pd.DataFrame(df1.loc[df1['envName'] == envName] .reset_index(drop=True)) tmpDf['tpgMax'] = ((tmpDf['tpgMax']-soloRandomScores[envName])/ (soloTpgScores[envName]-soloRandomScores[envName])) envDfs1.append(pd.DataFrame(tmpDf['tpgMax'])) tmpDf = pd.DataFrame(df2.loc[df2['envName'] == envName] .reset_index(drop=True)) tmpDf['tpgMax'] = ((tmpDf['tpgMax']-soloRandomScores[envName])/ (soloTpgScores[envName]-soloRandomScores[envName])) envDfs2.append(pd.DataFrame(tmpDf['tpgMax'])) tmpDf = pd.DataFrame(df3.loc[df3['envName'] == envName] .reset_index(drop=True)) tmpDf['tpgMax'] = ((tmpDf['tpgMax']-soloRandomScores[envName])/ (soloTpgScores[envName]-soloRandomScores[envName])) envDfs3.append(pd.DataFrame(tmpDf['tpgMax'])) tmpDf = pd.DataFrame(df4.loc[df4['envName'] == envName] .reset_index(drop=True)) tmpDf['tpgMax'] = ((tmpDf['tpgMax']-soloRandomScores[envName])/ (soloTpgScores[envName]-soloRandomScores[envName])) envDfs4.append(pd.DataFrame(tmpDf['tpgMax'])) tmpDf = pd.DataFrame(df5.loc[df5['envName'] == envName] .reset_index(drop=True)) tmpDf['tpgMax'] = ((tmpDf['tpgMax']-soloRandomScores[envName])/ (soloTpgScores[envName]-soloRandomScores[envName])) envDfs5.append(pd.DataFrame(tmpDf['tpgMax'])) meansFullWindowAll = pd.concat(envDfs1, axis=1).mean(axis=1).values means2WindowAll = pd.concat(envDfs2, axis=1).mean(axis=1).values means4WindowAll = pd.concat(envDfs3, axis=1).mean(axis=1).values meansFullWindowMerge = pd.concat(envDfs4, axis=1).mean(axis=1).values means4WindowMerge = pd.concat(envDfs5, axis=1).mean(axis=1).values plt.figure(figsize=(4,4)) plt.plot(meansFullWindowAll[:184], label='Window Size Max (All at Once)') #plt.plot(means2WindowAll[:74], label='Window Size 2 (All at Once)') plt.plot(means4WindowAll[:76], label='Window Size 4 (All at Once)') plt.plot(meansFullWindowMerge[:117], label='Window Size Max (Merge)') plt.plot(means4WindowMerge[:74], label='Window Size 4 (Merge)') plt.legend(loc=2, bbox_to_anchor=(1.01, 1.0)) plt.ylim(0,1) plt.xlabel('Environment Exposures') plt.ylabel('Mean Score') plt.title('Mean Scores on 8 Environments') plt.show() ```
github_jupyter
# TRAIN WHEEL DEFECT DETECTION ``` #The following dataset has the values captured by the sensors placed on railway tracks. #Sensors detect the force applied on them. #Variations in the values of force occur due to three different types of defects. #The dataset has a defect attribute which is the class attribute. #The dataset has 150 rows and 5 columns. #Four attributes are related to the values captured by the sensors and the left over attribute is the class. #The class attribute has 3 different classes. #Classes of the defect are: #Flatspot #Shelling #Non-roundness ``` ## Library imports ``` import numpy as np import pandas as pd ``` ## Separating class attribute ``` dataset=pd.read_csv('wheels.csv') print(dataset.head()) X=dataset[['sensor_1','sensor_2','sensor_3','sensor_4']] y=dataset[['defect']] ``` ## Transform the class attribute values to appropriate arrays ``` from sklearn.preprocessing import OneHotEncoder ohe = OneHotEncoder() y = ohe.fit_transform(y).toarray() ``` ## Train and Test dataset split ``` from sklearn.model_selection import train_test_split X_train,X_test,y_train,y_test = train_test_split(X,y,test_size = 0.30) ``` ## Neural network using Keras ``` from keras.models import Sequential from keras.layers import Dense from keras import optimizers model = Sequential() model.add(Dense(6, input_dim=4, activation='relu')) model.add(Dense(3,activation='softmax')) sgd = optimizers.SGD(lr=0.3, momentum=0) model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy']) history = model.fit(X_train, y_train, epochs=250, batch_size=5) ``` ## Predicting results for test set ``` y_pred = model.predict(X_test) pred = list() for i in range(len(y_pred)): pred.append(np.argmax(y_pred[i])) test = list() for i in range(len(y_test)): test.append(np.argmax(y_test[i])) ``` ## Evaluate accuracy and validate the model ``` from sklearn.metrics import accuracy_score a = accuracy_score(pred,test) print('Accuracy is:', a*100) history = model.fit(X_train, y_train,validation_data = (X_test,y_test), epochs=250, batch_size=40) ``` ## Using the model for predictions ``` print('Enter the sensor values: ') s1=float(input()) s2=float(input()) s3=float(input()) s4=float(input()) res=np.argmax(model.predict([[[s1,s2,s3,s4]]])) if res==0: print('Flatspot is the defect detected!') elif res==2: print('Shelling is the defect detected!') elif res==1: print('Non-roundness is the defect detected!') ``` ## Displaying the accuracy and plotting the graph ``` import matplotlib.pyplot as plt plt.plot(history.history['acc']) plt.plot(history.history['val_acc']) plt.title('Model accuracy') plt.ylabel('Accuracy') plt.xlabel('Epoch') plt.legend(['Train', 'Test'], loc='upper left') plt.show() print('Accuracy is:', a*100) ```
github_jupyter
# Discretization --- In this notebook, you will deal with continuous state and action spaces by discretizing them. This will enable you to apply reinforcement learning algorithms that are only designed to work with discrete spaces. ### 1. Import the Necessary Packages ``` import sys import gym import numpy as np import pandas as pd import matplotlib.pyplot as plt # Set plotting options %matplotlib inline plt.style.use('ggplot') np.set_printoptions(precision=3, linewidth=120) ``` ### 2. Specify the Environment, and Explore the State and Action Spaces We'll use [OpenAI Gym](https://gym.openai.com/) environments to test and develop our algorithms. These simulate a variety of classic as well as contemporary reinforcement learning tasks. Let's use an environment that has a continuous state space, but a discrete action space. ``` # Create an environment and set random seed env = gym.make('MountainCar-v0') env.seed(505); ``` Run the next code cell to watch a random agent. ``` state = env.reset() score = 0 for t in range(200): action = env.action_space.sample() env.render() state, reward, done, _ = env.step(action) score += reward if done: break print('Final score:', score) env.close() ``` In this notebook, you will train an agent to perform much better! For now, we can explore the state and action spaces, as well as sample them. ``` # Explore state (observation) space print("State space:", env.observation_space) print("- low:", env.observation_space.low) print("- high:", env.observation_space.high) # Generate some samples from the state space print("State space samples:") print(np.array([env.observation_space.sample() for i in range(10)])) # Explore the action space print("Action space:", env.action_space) # Generate some samples from the action space print("Action space samples:") print(np.array([env.action_space.sample() for i in range(10)])) ``` ### 3. Discretize the State Space with a Uniform Grid We will discretize the space using a uniformly-spaced grid. Implement the following function to create such a grid, given the lower bounds (`low`), upper bounds (`high`), and number of desired `bins` along each dimension. It should return the split points for each dimension, which will be 1 less than the number of bins. For instance, if `low = [-1.0, -5.0]`, `high = [1.0, 5.0]`, and `bins = (10, 10)`, then your function should return the following list of 2 NumPy arrays: ``` [array([-0.8, -0.6, -0.4, -0.2, 0.0, 0.2, 0.4, 0.6, 0.8]), array([-4.0, -3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 4.0])] ``` Note that the ends of `low` and `high` are **not** included in these split points. It is assumed that any value below the lowest split point maps to index `0` and any value above the highest split point maps to index `n-1`, where `n` is the number of bins along that dimension. ``` def create_uniform_grid(low, high, bins=(10, 10)): """Define a uniformly-spaced grid that can be used to discretize a space. Parameters ---------- low : array_like Lower bounds for each dimension of the continuous space. high : array_like Upper bounds for each dimension of the continuous space. bins : tuple Number of bins along each corresponding dimension. Returns ------- grid : list of array_like A list of arrays containing split points for each dimension. """ # TODO: Implement this grid = [np.linspace(low[dim], high[dim], bins[dim] + 1)[1:-1] for dim in range(len(bins))] print("Uniform grid: [<low>, <high>] / <bins> => <splits>") for l, h, b, splits in zip(low, high, bins, grid): print(" [{}, {}] / {} => {}".format(l, h, b, splits)) return grid low = [-1.0, -5.0] high = [1.0, 5.0] create_uniform_grid(low, high) # [test] ``` Now write a function that can convert samples from a continuous space into its equivalent discretized representation, given a grid like the one you created above. You can use the [`numpy.digitize()`](https://docs.scipy.org/doc/numpy-1.9.3/reference/generated/numpy.digitize.html) function for this purpose. Assume the grid is a list of NumPy arrays containing the following split points: ``` [array([-0.8, -0.6, -0.4, -0.2, 0.0, 0.2, 0.4, 0.6, 0.8]), array([-4.0, -3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 4.0])] ``` Here are some potential samples and their corresponding discretized representations: ``` [-1.0 , -5.0] => [0, 0] [-0.81, -4.1] => [0, 0] [-0.8 , -4.0] => [1, 1] [-0.5 , 0.0] => [2, 5] [ 0.2 , -1.9] => [6, 3] [ 0.8 , 4.0] => [9, 9] [ 0.81, 4.1] => [9, 9] [ 1.0 , 5.0] => [9, 9] ``` **Note**: There may be one-off differences in binning due to floating-point inaccuracies when samples are close to grid boundaries, but that is alright. ``` def discretize(sample, grid): """Discretize a sample as per given grid. Parameters ---------- sample : array_like A single sample from the (original) continuous space. grid : list of array_like A list of arrays containing split points for each dimension. Returns ------- discretized_sample : array_like A sequence of integers with the same number of dimensions as sample. """ # TODO: Implement this return list(int(np.digitize(s, g)) for s, g in zip(sample, grid)) # apply along each dimension # Test with a simple grid and some samples grid = create_uniform_grid([-1.0, -5.0], [1.0, 5.0]) samples = np.array( [[-1.0 , -5.0], [-0.81, -4.1], [-0.8 , -4.0], [-0.5 , 0.0], [ 0.2 , -1.9], [ 0.8 , 4.0], [ 0.81, 4.1], [ 1.0 , 5.0]]) discretized_samples = np.array([discretize(sample, grid) for sample in samples]) print("\nSamples:", repr(samples), sep="\n") print("\nDiscretized samples:", repr(discretized_samples), sep="\n") ``` ### 4. Visualization It might be helpful to visualize the original and discretized samples to get a sense of how much error you are introducing. ``` import matplotlib.collections as mc def visualize_samples(samples, discretized_samples, grid, low=None, high=None): """Visualize original and discretized samples on a given 2-dimensional grid.""" fig, ax = plt.subplots(figsize=(10, 10)) # Show grid ax.xaxis.set_major_locator(plt.FixedLocator(grid[0])) ax.yaxis.set_major_locator(plt.FixedLocator(grid[1])) ax.grid(True) # If bounds (low, high) are specified, use them to set axis limits if low is not None and high is not None: ax.set_xlim(low[0], high[0]) ax.set_ylim(low[1], high[1]) else: # Otherwise use first, last grid locations as low, high (for further mapping discretized samples) low = [splits[0] for splits in grid] high = [splits[-1] for splits in grid] # Map each discretized sample (which is really an index) to the center of corresponding grid cell grid_extended = np.hstack((np.array([low]).T, grid, np.array([high]).T)) # add low and high ends grid_centers = (grid_extended[:, 1:] + grid_extended[:, :-1]) / 2 # compute center of each grid cell locs = np.stack(grid_centers[i, discretized_samples[:, i]] for i in range(len(grid))).T # map discretized samples ax.plot(samples[:, 0], samples[:, 1], 'o') # plot original samples ax.plot(locs[:, 0], locs[:, 1], 's') # plot discretized samples in mapped locations ax.add_collection(mc.LineCollection(list(zip(samples, locs)), colors='orange')) # add a line connecting each original-discretized sample ax.legend(['original', 'discretized']) visualize_samples(samples, discretized_samples, grid, low, high) ``` Now that we have a way to discretize a state space, let's apply it to our reinforcement learning environment. ``` # Create a grid to discretize the state space state_grid = create_uniform_grid(env.observation_space.low, env.observation_space.high, bins=(10, 10)) state_grid # Obtain some samples from the space, discretize them, and then visualize them state_samples = np.array([env.observation_space.sample() for i in range(10)]) discretized_state_samples = np.array([discretize(sample, state_grid) for sample in state_samples]) visualize_samples(state_samples, discretized_state_samples, state_grid, env.observation_space.low, env.observation_space.high) plt.xlabel('position'); plt.ylabel('velocity'); # axis labels for MountainCar-v0 state space ``` You might notice that if you have enough bins, the discretization doesn't introduce too much error into your representation. So we may be able to now apply a reinforcement learning algorithm (like Q-Learning) that operates on discrete spaces. Give it a shot to see how well it works! ### 5. Q-Learning Provided below is a simple Q-Learning agent. Implement the `preprocess_state()` method to convert each continuous state sample to its corresponding discretized representation. ``` class QLearningAgent: """Q-Learning agent that can act on a continuous state space by discretizing it.""" def __init__(self, env, state_grid, alpha=0.02, gamma=0.99, epsilon=1.0, epsilon_decay_rate=0.9995, min_epsilon=.01, seed=505): """Initialize variables, create grid for discretization.""" # Environment info self.env = env self.state_grid = state_grid self.state_size = tuple(len(splits) + 1 for splits in self.state_grid) # n-dimensional state space self.action_size = self.env.action_space.n # 1-dimensional discrete action space self.seed = np.random.seed(seed) print("Environment:", self.env) print("State space size:", self.state_size) print("Action space size:", self.action_size) # Learning parameters self.alpha = alpha # learning rate self.gamma = gamma # discount factor self.epsilon = self.initial_epsilon = epsilon # initial exploration rate self.epsilon_decay_rate = epsilon_decay_rate # how quickly should we decrease epsilon self.min_epsilon = min_epsilon # Create Q-table self.q_table = np.zeros(shape=(self.state_size + (self.action_size,))) print("Q table size:", self.q_table.shape) def preprocess_state(self, state): """Map a continuous state to its discretized representation.""" # TODO: Implement this return tuple(discretize(state, self.state_grid)) def reset_episode(self, state): """Reset variables for a new episode.""" # Gradually decrease exploration rate self.epsilon *= self.epsilon_decay_rate self.epsilon = max(self.epsilon, self.min_epsilon) # Decide initial action self.last_state = self.preprocess_state(state) self.last_action = np.argmax(self.q_table[self.last_state]) return self.last_action def reset_exploration(self, epsilon=None): """Reset exploration rate used when training.""" self.epsilon = epsilon if epsilon is not None else self.initial_epsilon def act(self, state, reward=None, done=None, mode='train'): """Pick next action and update internal Q table (when mode != 'test').""" state = self.preprocess_state(state) if mode == 'test': # Test mode: Simply produce an action action = np.argmax(self.q_table[state]) else: # Train mode (default): Update Q table, pick next action # Note: We update the Q table entry for the *last* (state, action) pair with current state, reward self.q_table[self.last_state + (self.last_action,)] += self.alpha * \ (reward + self.gamma * max(self.q_table[state]) - self.q_table[self.last_state + (self.last_action,)]) # Exploration vs. exploitation do_exploration = np.random.uniform(0, 1) < self.epsilon if do_exploration: # Pick a random action action = np.random.randint(0, self.action_size) else: # Pick the best action from Q table action = np.argmax(self.q_table[state]) # Roll over current state, action for next step self.last_state = state self.last_action = action return action q_agent = QLearningAgent(env, state_grid) ``` Let's also define a convenience function to run an agent on a given environment. When calling this function, you can pass in `mode='test'` to tell the agent not to learn. ``` def run(agent, env, num_episodes=20000, mode='train'): """Run agent in given reinforcement learning environment and return scores.""" scores = [] max_avg_score = -np.inf for i_episode in range(1, num_episodes+1): # Initialize episode state = env.reset() action = agent.reset_episode(state) total_reward = 0 done = False # Roll out steps until done while not done: state, reward, done, info = env.step(action) total_reward += reward action = agent.act(state, reward, done, mode) # Save final score scores.append(total_reward) # Print episode stats if mode == 'train': if len(scores) > 100: avg_score = np.mean(scores[-100:]) if avg_score > max_avg_score: max_avg_score = avg_score if i_episode % 100 == 0: print("\rEpisode {}/{} | Max Average Score: {}".format(i_episode, num_episodes, max_avg_score), end="") sys.stdout.flush() return scores scores = run(q_agent, env) ``` The best way to analyze if your agent was learning the task is to plot the scores. It should generally increase as the agent goes through more episodes. ``` # Plot scores obtained per episode plt.plot(scores); plt.title("Scores"); ``` If the scores are noisy, it might be difficult to tell whether your agent is actually learning. To find the underlying trend, you may want to plot a rolling mean of the scores. Let's write a convenience function to plot both raw scores as well as a rolling mean. ``` def plot_scores(scores, rolling_window=100): """Plot scores and optional rolling mean using specified window.""" plt.plot(scores); plt.title("Scores"); rolling_mean = pd.Series(scores).rolling(rolling_window).mean() plt.plot(rolling_mean); return rolling_mean rolling_mean = plot_scores(scores) ``` You should observe the mean episode scores go up over time. Next, you can freeze learning and run the agent in test mode to see how well it performs. ``` # Run in test mode and analyze scores obtained test_scores = run(q_agent, env, num_episodes=100, mode='test') print("[TEST] Completed {} episodes with avg. score = {}".format(len(test_scores), np.mean(test_scores))) _ = plot_scores(test_scores) ``` It's also interesting to look at the final Q-table that is learned by the agent. Note that the Q-table is of size MxNxA, where (M, N) is the size of the state space, and A is the size of the action space. We are interested in the maximum Q-value for each state, and the corresponding (best) action associated with that value. ``` def plot_q_table(q_table): """Visualize max Q-value for each state and corresponding action.""" q_image = np.max(q_table, axis=2) # max Q-value for each state q_actions = np.argmax(q_table, axis=2) # best action for each state fig, ax = plt.subplots(figsize=(10, 10)) cax = ax.imshow(q_image, cmap='jet'); cbar = fig.colorbar(cax) for x in range(q_image.shape[0]): for y in range(q_image.shape[1]): ax.text(x, y, q_actions[x, y], color='white', horizontalalignment='center', verticalalignment='center') ax.grid(False) ax.set_title("Q-table, size: {}".format(q_table.shape)) ax.set_xlabel('position') ax.set_ylabel('velocity') plot_q_table(q_agent.q_table) ``` ### 6. Modify the Grid Now it's your turn to play with the grid definition and see what gives you optimal results. Your agent's final performance is likely to get better if you use a finer grid, with more bins per dimension, at the cost of higher model complexity (more parameters to learn). ``` # TODO: Create a new agent with a different state space grid state_grid_new = create_uniform_grid(env.observation_space.low, env.observation_space.high, bins=(20, 20)) q_agent_new = QLearningAgent(env, state_grid_new) q_agent_new.scores = [] # initialize a list to store scores for this agent # Train it over a desired number of episodes and analyze scores # Note: This cell can be run multiple times, and scores will get accumulated q_agent_new.scores += run(q_agent_new, env, num_episodes=50000) # accumulate scores rolling_mean_new = plot_scores(q_agent_new.scores) # Run in test mode and analyze scores obtained test_scores = run(q_agent_new, env, num_episodes=100, mode='test') print("[TEST] Completed {} episodes with avg. score = {}".format(len(test_scores), np.mean(test_scores))) _ = plot_scores(test_scores) # Visualize the learned Q-table plot_q_table(q_agent_new.q_table) ``` ### 7. Watch a Smart Agent ``` state = env.reset() score = 0 for t in range(200): action = q_agent_new.act(state, mode='test') env.render() state, reward, done, _ = env.step(action) score += reward if done: break print('Final score:', score) env.close() ```
github_jupyter
# Statistics ``` num_friends = [100.0,49,41,40,25,21,21,19,19,18,18,16,15, 15,15,15,14,14,13,13,13,13,12,12,11,10,10, 10,10,10,10,10,10,10,10,10,10,10,10,10,9,9 ,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,8,8,8,8,8, 8,8,8,8,8,8,8,8,7,7,7,7,7,7,7,7,7,7,7,7,7,7 ,7,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,4,4,4,4 ,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,3,3,3,3,3,3,3, 3,3,3,3,3,3,3,3,3,3,3,3,3,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1] from collections import Counter import matplotlib.pyplot as plt friend_counts = Counter(num_friends) xs = range(101) ys = [friend_counts[x] for x in xs] plt.bar(xs,ys) plt.axis([0, 101, 0, 25]) plt.title("Histogram of Friend Counts") plt.xlabel("# of friends") plt.ylabel("# of people") plt.show() num_points = len(num_friends) num_points largest_value = max(num_friends) # 100 smallest_value = min(num_friends) # 1 assert largest_value == 100 assert smallest_value == 1 sorted_values = sorted(num_friends) smallest_value = sorted_values[0] # 1 second_smallest_value = sorted_values[1] # 1 second_largest_value = sorted_values[-2] # 49 assert smallest_value == 1 assert second_smallest_value == 1 assert second_largest_value == 49 ``` ### Central Tendencies ``` from typing import List def mean(xs: List[float]) -> float: return sum(xs) / len(xs) mean(num_friends) # The underscores indicate that these are "private" functions, as they're # intended to be called by our median function but not by other people # using our statistics library. def _median_odd(xs: List[float]) -> float: """If len(xs) is odd, the median is the middle element""" return sorted(xs)[len(xs) // 2] def _median_even(xs: List[float]) -> float: """If len(xs) is even, it's the average of the middle two elements""" sorted_xs = sorted(xs) hi_midpoint = len(xs) // 2 # e.g. length 4 => hi_midpoint 2 return (sorted_xs[hi_midpoint - 1] + sorted_xs[hi_midpoint]) / 2 def median(v: List[float]) -> float: """Finds the 'middle-most' value of v""" return _median_even(v) if len(v) % 2 == 0 else _median_odd(v) assert median([1, 10, 2, 9, 5]) == 5 assert median([1, 9, 2, 10]) == (2 + 9) / 2 print(median(num_friends)) ``` ### Quantile ``` def quantile(xs: List[float], p: float) -> float: p_index = int(p * len(xs)) return sorted(xs)[p_index] assert quantile(num_friends, 0.10) == 1 assert quantile(num_friends, 0.25) == 3 assert quantile(num_friends, 0.75) == 9 assert quantile(num_friends, 0.90) == 13 def mode(x: List[float]) -> List[float]: counts = Counter(x) max_count = max(counts.values()) return [ x_i for x_i, count in counts.items() if count == max_count] assert set(mode(num_friends)) == {1,6} ``` ### Dispersion ``` # Imported from Lineal Algebra ----------------------------------------------------- from typing import List Vector = List[float] def dot(v: Vector, w: Vector) -> float: assert len(v) == len(w), "Vectors must be same length" return sum(v_i * w_i for v_i, w_i in zip(v,w)) def sum_of_squares(v: Vector) -> float: """ Return v_1 * v_1 + ... + v_n * v_n """ return dot(v,v) # ----------------------------------------------------------------------------------- # "range" already means something in Python, so we'll use a different name def data_range(xs: List[float]) -> float: return max(xs) - min(xs) assert data_range(num_friends) == 99 def de_mean(xs: List[float]) -> List[float]: x_bar = mean(xs) return [ x - x_bar for x in xs ] def variance(xs: List[float]) -> float: assert len(xs) >= 2, "Variance requires at least two elements" n = len(xs) deviations = de_mean(xs) return sum_of_squares(deviations) / (n - 1) assert 81.54 < variance(num_friends) < 81.55 import math def standard_deviation(xs: List[float]) -> float: return math.sqrt(variance(xs)) assert 9.02 < standard_deviation(num_friends) < 9.04 def interquartile_range(xs: List[float]) -> float: return quantile(xs, 0.75) - quantile(xs, 0.25) assert interquartile_range(num_friends) == 6 ``` ## Correlation ``` daily_minutes = [1,68.77,51.25,52.08,38.36,44.54,57.13,51.4, 41.42,31.22,34.76,54.01,38.79,47.59,49.1, 27.66,41.03,36.73,48.65,28.12,46.62,35.57, 32.98,35,26.07,23.77,39.73,40.57,31.65,31.21, 36.32,20.45,21.93,26.02,27.34,23.49,46.94,30.5, 33.8,24.23,21.4,27.94,32.24,40.57,25.07,19.42, 22.39,18.42,46.96,23.72,26.41,26.97,36.76,40.32 ,35.02,29.47,30.2,31,38.11,38.18,36.31,21.03, 30.86,36.07,28.66,29.08,37.28,15.28,24.17,22.31, 30.17,25.53,19.85,35.37,44.6,17.23,13.47,26.33,35.02 ,32.09,24.81,19.33,28.77,24.26,31.98,25.73,24.86, 16.28,34.51,15.23,39.72,40.8,26.06,35.76,34.76,16.13 ,44.04,18.03,19.65,32.62,35.59,39.43,14.18,35.24,40.13 ,41.82,35.45,36.07,43.67,24.61,20.9,21.9,18.79, 27.61,27.21,26.61,29.77,20.59,27.53,13.82,33.2, 25,33.1,36.65,18.63,14.87,22.2,36.81,25.53,24.62,26.25 ,18.21,28.08,19.42,29.79,32.8,35.99,28.32,27.79,35.88, 29.06,36.28,14.1,36.63,37.49,26.9,18.58,38.48,24.48,18.95 ,33.55,14.24,29.04,32.51,25.63,22.22,19,32.73,15.16,13.9, 27.2,32.01,29.27,33,13.74,20.42,27.32,18.23,35.35,28.48, 9.08,24.62,20.12,35.26,19.92,31.02,16.49,12.16,30.7,31.22 ,34.65,13.13,27.51,33.2,31.57,14.1,33.42,17.44,10.12,24.42 ,9.82,23.39,30.93,15.03,21.67,31.09,33.29,22.61,26.89,23.48 ,8.38,27.81,32.35,23.84] daily_hours = [dm / 60 for dm in daily_minutes] def covariance(xs: List[float], ys: List[float]) -> float: assert len(xs) == len(ys),"xs and ys must have same number of elements" return dot(de_mean(xs),de_mean(ys)) / (len(xs) - 1) assert 22.42 < covariance(num_friends, daily_minutes) < 22.43 assert 22.42 / 60 < covariance(num_friends, daily_hours) < 22.43 / 60 def correlation(xs: List[float], ys: List[float]) -> float: stdev_x = standard_deviation(xs) stdev_y = standard_deviation(ys) if stdev_x > 0 and stdev_y > 0: return covariance(xs, ys) / stdev_x / stdev_y else: return 0 assert 0.24 < correlation(num_friends, daily_minutes) < 0.25 assert 0.24 < correlation(num_friends, daily_hours) < 0.25 outlier = num_friends.index(100) # index of outlier num_friends_good = [x for i, x in enumerate(num_friends) if i != outlier] daily_minutes_good = [x for i, x in enumerate(daily_minutes) if i != outlier] daily_hours_good = [dm / 60 for dm in daily_minutes_good] assert 0.57 < correlation(num_friends_good, daily_minutes_good) < 0.58 assert 0.57 < correlation(num_friends_good, daily_hours_good) < 0.58 ```
github_jupyter
``` #@title Clone MelGAN-VC Repository ! git clone https://github.com/moiseshorta/MelGAN-VC.git #@title Mount your Google Drive #Mount your Google Drive account from google.colab import drive drive.mount('/content/drive') #Get Example Datasets %cd /content/ #Target Audio = Antonio Zepeda - Templo Mayor !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=1-1pKhCyccFc6cDIHe_vOZFSRak6eh5Dy' -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1\n/p')&id=1-1pKhCyccFc6cDIHe_vOZFSRak6eh5Dy" -O az.zip && rm -rf /tmp/cookies.txt #Source Audio = Native American flutes !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=1-BR2SlBmxskjBKHKqazUiyIL0GGdyeg7' -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1\n/p')&id=1-BR2SlBmxskjBKHKqazUiyIL0GGdyeg7" -O flautaindigena.zip && rm -rf /tmp/cookies.txt !unzip az.zip !unzip flautaindigena.zip #@title Import Tensorflow and torchaudio #We'll be using TF 2.1 and torchaudio try: %tensorflow_version 2.x except Exception: pass import tensorflow as tf !pip install soundfile #to save wav files !pip install torch==1.8.0 !pip install --no-deps torchaudio==0.8 !pip uninstall tensorflow !pip install tensorflow-gpu==2.1 #@title Imports from __future__ import print_function, division from glob import glob import scipy import soundfile as sf import matplotlib.pyplot as plt from IPython.display import clear_output from tensorflow.keras.layers import Input, Dense, Reshape, Flatten, Concatenate, Conv2D, Conv2DTranspose, GlobalAveragePooling2D, UpSampling2D, LeakyReLU, ReLU, Add, Multiply, Lambda, Dot, BatchNormalization, Activation, ZeroPadding2D, Cropping2D, Cropping1D from tensorflow.keras.models import Sequential, Model, load_model from tensorflow.keras.optimizers import Adam from tensorflow.keras.initializers import TruncatedNormal, he_normal import tensorflow.keras.backend as K import datetime import numpy as np import random import matplotlib.pyplot as plt import collections from PIL import Image from skimage.transform import resize import imageio import librosa import librosa.display from librosa.feature import melspectrogram import os import time import IPython #@title Hyperparameters #Hyperparameters hop=512 #hop size (window size = 6*hop) sr=44100 #sampling rate min_level_db=-100 #reference values to normalize data ref_level_db=20 shape=64 #length of time axis of split specrograms to feed to generator vec_len=128 #length of vector generated by siamese vector bs = 16 #batch size delta = 2. #constant for siamese loss #@title Waveform to Spectrogram converter #There seems to be a problem with Tensorflow STFT, so we'll be using pytorch to handle offline mel-spectrogram generation and waveform reconstruction #For waveform reconstruction, a gradient-based method is used: ''' Decorsière, Rémi, Peter L. Søndergaard, Ewen N. MacDonald, and Torsten Dau. "Inversion of auditory spectrograms, traditional spectrograms, and other envelope representations." IEEE/ACM Transactions on Audio, Speech, and Language Processing 23, no. 1 (2014): 46-56.''' #ORIGINAL CODE FROM https://github.com/yoyololicon/spectrogram-inversion import torch import torch.nn as nn import torch.nn.functional as F from tqdm import tqdm from functools import partial import math import heapq from torchaudio.transforms import MelScale, Spectrogram torch.set_default_tensor_type('torch.cuda.FloatTensor') specobj = Spectrogram(n_fft=6*hop, win_length=6*hop, hop_length=hop, pad=0, power=2, normalized=True) specfunc = specobj.forward melobj = MelScale(n_mels=hop, sample_rate=sr, f_min=0.) melfunc = melobj.forward def melspecfunc(waveform): specgram = specfunc(waveform) mel_specgram = melfunc(specgram) return mel_specgram def spectral_convergence(input, target): return 20 * ((input - target).norm().log10() - target.norm().log10()) def GRAD(spec, transform_fn, samples=None, init_x0=None, maxiter=1000, tol=1e-6, verbose=1, evaiter=10, lr=0.003): spec = torch.Tensor(spec) samples = (spec.shape[-1]*hop)-hop if init_x0 is None: init_x0 = spec.new_empty((1,samples)).normal_(std=1e-6) x = nn.Parameter(init_x0) T = spec criterion = nn.L1Loss() optimizer = torch.optim.Adam([x], lr=lr) bar_dict = {} metric_func = spectral_convergence bar_dict['spectral_convergence'] = 0 metric = 'spectral_convergence' init_loss = None with tqdm(total=maxiter, disable=not verbose) as pbar: for i in range(maxiter): optimizer.zero_grad() V = transform_fn(x) loss = criterion(V, T) loss.backward() optimizer.step() lr = lr*0.9999 for param_group in optimizer.param_groups: param_group['lr'] = lr if i % evaiter == evaiter - 1: with torch.no_grad(): V = transform_fn(x) bar_dict[metric] = metric_func(V, spec).item() l2_loss = criterion(V, spec).item() pbar.set_postfix(**bar_dict, loss=l2_loss) pbar.update(evaiter) return x.detach().view(-1).cpu() def normalize(S): return np.clip((((S - min_level_db) / -min_level_db)*2.)-1., -1, 1) def denormalize(S): return (((np.clip(S, -1, 1)+1.)/2.) * -min_level_db) + min_level_db def prep(wv,hop=192): S = np.array(torch.squeeze(melspecfunc(torch.Tensor(wv).view(1,-1))).detach().cpu()) S = librosa.power_to_db(S)-ref_level_db return normalize(S) def deprep(S): S = denormalize(S)+ref_level_db S = librosa.db_to_power(S) wv = GRAD(np.expand_dims(S,0), melspecfunc, maxiter=2000, evaiter=10, tol=1e-8) return np.array(np.squeeze(wv)) #@title Helper Functions #Helper functions #Generate spectrograms from waveform array def tospec(data): specs=np.empty(data.shape[0], dtype=object) for i in range(data.shape[0]): x = data[i] S=prep(x) S = np.array(S, dtype=np.float32) specs[i]=np.expand_dims(S, -1) print(specs.shape) return specs #Generate multiple spectrograms with a determined length from single wav file def tospeclong(path, length=4*44100): x, sr = librosa.load(path,sr=44100) x,_ = librosa.effects.trim(x) loudls = librosa.effects.split(x, top_db=50) xls = np.array([]) for interv in loudls: xls = np.concatenate((xls,x[interv[0]:interv[1]])) x = xls num = x.shape[0]//length specs=np.empty(num, dtype=object) for i in range(num-1): a = x[i*length:(i+1)*length] S = prep(a) S = np.array(S, dtype=np.float32) try: sh = S.shape specs[i]=S except AttributeError: print('spectrogram failed') print(specs.shape) return specs #Waveform array from path of folder containing wav files def audio_array(path): ls = glob(f'{path}/*.wav') adata = [] for i in range(len(ls)): x, sr = tf.audio.decode_wav(tf.io.read_file(ls[i]), 1) x = np.array(x, dtype=np.float32) adata.append(x) return np.array(adata) #Concatenate spectrograms in array along the time axis def testass(a): but=False con = np.array([]) nim = a.shape[0] for i in range(nim): im = a[i] im = np.squeeze(im) if not but: con=im but=True else: con = np.concatenate((con,im), axis=1) return np.squeeze(con) #Split spectrograms in chunks with equal size def splitcut(data): ls = [] mini = 0 minifinal = 10*shape #max spectrogram length for i in range(data.shape[0]-1): if data[i].shape[1]<=data[i+1].shape[1]: mini = data[i].shape[1] else: mini = data[i+1].shape[1] if mini>=3*shape and mini<minifinal: minifinal = mini for i in range(data.shape[0]): x = data[i] if x.shape[1]>=3*shape: for n in range(x.shape[1]//minifinal): ls.append(x[:,n*minifinal:n*minifinal+minifinal,:]) ls.append(x[:,-minifinal:,:]) return np.array(ls) #@title Generating Mel-Spectrogram dataset. Audio files must be 44.1Khz/16bit .wav source_audio_directory = "/content/flautaindigena" #@param {type:"string"} target_audio_directory = "/content/AntonioZepeda" #@param {type:"string"} #Generating Mel-Spectrogram dataset (Uncomment where needed) #adata: source spectrograms #bdata: target spectrograms #SOURCE awv = audio_array(source_audio_directory) #get waveform array from folder containing wav files aspec = tospec(awv) #get spectrogram array adata = splitcut(aspec) #split spectrogams to fixed length #TARGET bwv = audio_array(target_audio_directory) bspec = tospec(bwv) bdata = splitcut(bspec) #@title Creates Tensorflow Datasets #Creating Tensorflow Datasets @tf.function def proc(x): return tf.image.random_crop(x, size=[hop, 3*shape, 1]) dsa = tf.data.Dataset.from_tensor_slices(adata).repeat(50).map(proc, num_parallel_calls=tf.data.experimental.AUTOTUNE).shuffle(10000).batch(bs, drop_remainder=True) dsb = tf.data.Dataset.from_tensor_slices(bdata).repeat(50).map(proc, num_parallel_calls=tf.data.experimental.AUTOTUNE).shuffle(10000).batch(bs, drop_remainder=True) #@title Adding Spectral Normalization to convolutional layers #Adding Spectral Normalization to convolutional layers from tensorflow.python.keras.utils import conv_utils from tensorflow.python.ops import array_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import sparse_ops from tensorflow.python.ops import gen_math_ops from tensorflow.python.ops import standard_ops from tensorflow.python.eager import context from tensorflow.python.framework import tensor_shape def l2normalize(v, eps=1e-12): return v / (tf.norm(v) + eps) class ConvSN2D(tf.keras.layers.Conv2D): def __init__(self, filters, kernel_size, power_iterations=1, **kwargs): super(ConvSN2D, self).__init__(filters, kernel_size, **kwargs) self.power_iterations = power_iterations def build(self, input_shape): super(ConvSN2D, self).build(input_shape) if self.data_format == 'channels_first': channel_axis = 1 else: channel_axis = -1 self.u = self.add_weight(self.name + '_u', shape=tuple([1, self.kernel.shape.as_list()[-1]]), initializer=tf.initializers.RandomNormal(0, 1), trainable=False ) def compute_spectral_norm(self, W, new_u, W_shape): for _ in range(self.power_iterations): new_v = l2normalize(tf.matmul(new_u, tf.transpose(W))) new_u = l2normalize(tf.matmul(new_v, W)) sigma = tf.matmul(tf.matmul(new_v, W), tf.transpose(new_u)) W_bar = W/sigma with tf.control_dependencies([self.u.assign(new_u)]): W_bar = tf.reshape(W_bar, W_shape) return W_bar def call(self, inputs): W_shape = self.kernel.shape.as_list() W_reshaped = tf.reshape(self.kernel, (-1, W_shape[-1])) new_kernel = self.compute_spectral_norm(W_reshaped, self.u, W_shape) outputs = self._convolution_op(inputs, new_kernel) if self.use_bias: if self.data_format == 'channels_first': outputs = tf.nn.bias_add(outputs, self.bias, data_format='NCHW') else: outputs = tf.nn.bias_add(outputs, self.bias, data_format='NHWC') if self.activation is not None: return self.activation(outputs) return outputs class ConvSN2DTranspose(tf.keras.layers.Conv2DTranspose): def __init__(self, filters, kernel_size, power_iterations=1, **kwargs): super(ConvSN2DTranspose, self).__init__(filters, kernel_size, **kwargs) self.power_iterations = power_iterations def build(self, input_shape): super(ConvSN2DTranspose, self).build(input_shape) if self.data_format == 'channels_first': channel_axis = 1 else: channel_axis = -1 self.u = self.add_weight(self.name + '_u', shape=tuple([1, self.kernel.shape.as_list()[-1]]), initializer=tf.initializers.RandomNormal(0, 1), trainable=False ) def compute_spectral_norm(self, W, new_u, W_shape): for _ in range(self.power_iterations): new_v = l2normalize(tf.matmul(new_u, tf.transpose(W))) new_u = l2normalize(tf.matmul(new_v, W)) sigma = tf.matmul(tf.matmul(new_v, W), tf.transpose(new_u)) W_bar = W/sigma with tf.control_dependencies([self.u.assign(new_u)]): W_bar = tf.reshape(W_bar, W_shape) return W_bar def call(self, inputs): W_shape = self.kernel.shape.as_list() W_reshaped = tf.reshape(self.kernel, (-1, W_shape[-1])) new_kernel = self.compute_spectral_norm(W_reshaped, self.u, W_shape) inputs_shape = array_ops.shape(inputs) batch_size = inputs_shape[0] if self.data_format == 'channels_first': h_axis, w_axis = 2, 3 else: h_axis, w_axis = 1, 2 height, width = inputs_shape[h_axis], inputs_shape[w_axis] kernel_h, kernel_w = self.kernel_size stride_h, stride_w = self.strides if self.output_padding is None: out_pad_h = out_pad_w = None else: out_pad_h, out_pad_w = self.output_padding out_height = conv_utils.deconv_output_length(height, kernel_h, padding=self.padding, output_padding=out_pad_h, stride=stride_h, dilation=self.dilation_rate[0]) out_width = conv_utils.deconv_output_length(width, kernel_w, padding=self.padding, output_padding=out_pad_w, stride=stride_w, dilation=self.dilation_rate[1]) if self.data_format == 'channels_first': output_shape = (batch_size, self.filters, out_height, out_width) else: output_shape = (batch_size, out_height, out_width, self.filters) output_shape_tensor = array_ops.stack(output_shape) outputs = K.conv2d_transpose( inputs, new_kernel, output_shape_tensor, strides=self.strides, padding=self.padding, data_format=self.data_format, dilation_rate=self.dilation_rate) if not context.executing_eagerly(): out_shape = self.compute_output_shape(inputs.shape) outputs.set_shape(out_shape) if self.use_bias: outputs = tf.nn.bias_add( outputs, self.bias, data_format=conv_utils.convert_data_format(self.data_format, ndim=4)) if self.activation is not None: return self.activation(outputs) return outputs class DenseSN(Dense): def build(self, input_shape): super(DenseSN, self).build(input_shape) self.u = self.add_weight(self.name + '_u', shape=tuple([1, self.kernel.shape.as_list()[-1]]), initializer=tf.initializers.RandomNormal(0, 1), trainable=False) def compute_spectral_norm(self, W, new_u, W_shape): new_v = l2normalize(tf.matmul(new_u, tf.transpose(W))) new_u = l2normalize(tf.matmul(new_v, W)) sigma = tf.matmul(tf.matmul(new_v, W), tf.transpose(new_u)) W_bar = W/sigma with tf.control_dependencies([self.u.assign(new_u)]): W_bar = tf.reshape(W_bar, W_shape) return W_bar def call(self, inputs): W_shape = self.kernel.shape.as_list() W_reshaped = tf.reshape(self.kernel, (-1, W_shape[-1])) new_kernel = self.compute_spectral_norm(W_reshaped, self.u, W_shape) rank = len(inputs.shape) if rank > 2: outputs = standard_ops.tensordot(inputs, new_kernel, [[rank - 1], [0]]) if not context.executing_eagerly(): shape = inputs.shape.as_list() output_shape = shape[:-1] + [self.units] outputs.set_shape(output_shape) else: inputs = math_ops.cast(inputs, self._compute_dtype) if K.is_sparse(inputs): outputs = sparse_ops.sparse_tensor_dense_matmul(inputs, new_kernel) else: outputs = gen_math_ops.mat_mul(inputs, new_kernel) if self.use_bias: outputs = tf.nn.bias_add(outputs, self.bias) if self.activation is not None: return self.activation(outputs) return outputs #@title Networks Architecture #Networks Architecture init = tf.keras.initializers.he_uniform() def conv2d(layer_input, filters, kernel_size=4, strides=2, padding='same', leaky=True, bnorm=True, sn=True): if leaky: Activ = LeakyReLU(alpha=0.2) else: Activ = ReLU() if sn: d = ConvSN2D(filters, kernel_size=kernel_size, strides=strides, padding=padding, kernel_initializer=init, use_bias=False)(layer_input) else: d = Conv2D(filters, kernel_size=kernel_size, strides=strides, padding=padding, kernel_initializer=init, use_bias=False)(layer_input) if bnorm: d = BatchNormalization()(d) d = Activ(d) return d def deconv2d(layer_input, layer_res, filters, kernel_size=4, conc=True, scalev=False, bnorm=True, up=True, padding='same', strides=2): if up: u = UpSampling2D((1,2))(layer_input) u = ConvSN2D(filters, kernel_size, strides=(1,1), kernel_initializer=init, use_bias=False, padding=padding)(u) else: u = ConvSN2DTranspose(filters, kernel_size, strides=strides, kernel_initializer=init, use_bias=False, padding=padding)(layer_input) if bnorm: u = BatchNormalization()(u) u = LeakyReLU(alpha=0.2)(u) if conc: u = Concatenate()([u,layer_res]) return u #Extract function: splitting spectrograms def extract_image(im): im1 = Cropping2D(((0,0), (0, 2*(im.shape[2]//3))))(im) im2 = Cropping2D(((0,0), (im.shape[2]//3,im.shape[2]//3)))(im) im3 = Cropping2D(((0,0), (2*(im.shape[2]//3), 0)))(im) return im1,im2,im3 #Assemble function: concatenating spectrograms def assemble_image(lsim): im1,im2,im3 = lsim imh = Concatenate(2)([im1,im2,im3]) return imh #U-NET style architecture def build_generator(input_shape): h,w,c = input_shape inp = Input(shape=input_shape) #downscaling g0 = tf.keras.layers.ZeroPadding2D((0,1))(inp) g1 = conv2d(g0, 256, kernel_size=(h,3), strides=1, padding='valid') g2 = conv2d(g1, 256, kernel_size=(1,9), strides=(1,2)) g3 = conv2d(g2, 256, kernel_size=(1,7), strides=(1,2)) #upscaling g4 = deconv2d(g3,g2, 256, kernel_size=(1,7), strides=(1,2)) g5 = deconv2d(g4,g1, 256, kernel_size=(1,9), strides=(1,2), bnorm=False) g6 = ConvSN2DTranspose(1, kernel_size=(h,1), strides=(1,1), kernel_initializer=init, padding='valid', activation='tanh')(g5) return Model(inp,g6, name='G') #Siamese Network def build_siamese(input_shape): h,w,c = input_shape inp = Input(shape=input_shape) g1 = conv2d(inp, 256, kernel_size=(h,3), strides=1, padding='valid', sn=False) g2 = conv2d(g1, 256, kernel_size=(1,9), strides=(1,2), sn=False) g3 = conv2d(g2, 256, kernel_size=(1,7), strides=(1,2), sn=False) g4 = Flatten()(g3) g5 = Dense(vec_len)(g4) return Model(inp, g5, name='S') #Discriminator (Critic) Network def build_critic(input_shape): h,w,c = input_shape inp = Input(shape=input_shape) g1 = conv2d(inp, 512, kernel_size=(h,3), strides=1, padding='valid', bnorm=False) g2 = conv2d(g1, 512, kernel_size=(1,9), strides=(1,2), bnorm=False) g3 = conv2d(g2, 512, kernel_size=(1,7), strides=(1,2), bnorm=False) g4 = Flatten()(g3) g4 = DenseSN(1, kernel_initializer=init)(g4) return Model(inp, g4, name='C') #@title Save in training loop checkpoint_save_directory = "/content/MelGAN-VC/checkpoint" #@param {type:"string"} #Load past models from path to resume training or test def load(path): gen = build_generator((hop,shape,1)) siam = build_siamese((hop,shape,1)) critic = build_critic((hop,3*shape,1)) gen.load_weights(path+'/gen.h5') critic.load_weights(path+'/critic.h5') siam.load_weights(path+'/siam.h5') return gen,critic,siam #Build models def build(): gen = build_generator((hop,shape,1)) siam = build_siamese((hop,shape,1)) critic = build_critic((hop,3*shape,1)) #the discriminator accepts as input spectrograms of triple the width of those generated by the generator return gen,critic,siam #Generate a random batch to display current training results def testgena(): sw = True while sw: a = np.random.choice(aspec) if a.shape[1]//shape!=1: sw=False dsa = [] if a.shape[1]//shape>6: num=6 else: num=a.shape[1]//shape rn = np.random.randint(a.shape[1]-(num*shape)) for i in range(num): im = a[:,rn+(i*shape):rn+(i*shape)+shape] im = np.reshape(im, (im.shape[0],im.shape[1],1)) dsa.append(im) return np.array(dsa, dtype=np.float32) #Show results mid-training def save_test_image_full(path): a = testgena() print(a.shape) ab = gen(a, training=False) ab = testass(ab) a = testass(a) abwv = deprep(ab) awv = deprep(a) sf.write(path+'/new_file.wav', abwv, sr) IPython.display.display(IPython.display.Audio(np.squeeze(abwv), rate=sr)) IPython.display.display(IPython.display.Audio(np.squeeze(awv), rate=sr)) fig, axs = plt.subplots(ncols=2) axs[0].imshow(np.flip(a, -2), cmap=None) axs[0].axis('off') axs[0].set_title('Source') axs[1].imshow(np.flip(ab, -2), cmap=None) axs[1].axis('off') axs[1].set_title('Generated') plt.show() #Save in training loop def save_end(epoch,gloss,closs,mloss,n_save=3,save_path=checkpoint_save_directory): #use custom save_path (i.e. Drive '../content/drive/My Drive/') if epoch % n_save == 0: print('Saving...') path = f'{save_path}/MELGANVC-{str(gloss)[:9]}-{str(closs)[:9]}-{str(mloss)[:9]}' os.mkdir(path) gen.save_weights(path+'/gen.h5') critic.save_weights(path+'/critic.h5') siam.save_weights(path+'/siam.h5') save_test_image_full(path) #@title Losses #Losses def mae(x,y): return tf.reduce_mean(tf.abs(x-y)) def mse(x,y): return tf.reduce_mean((x-y)**2) def loss_travel(sa,sab,sa1,sab1): l1 = tf.reduce_mean(((sa-sa1) - (sab-sab1))**2) l2 = tf.reduce_mean(tf.reduce_sum(-(tf.nn.l2_normalize(sa-sa1, axis=[-1]) * tf.nn.l2_normalize(sab-sab1, axis=[-1])), axis=-1)) return l1+l2 def loss_siamese(sa,sa1): logits = tf.sqrt(tf.reduce_sum((sa-sa1)**2, axis=-1, keepdims=True)) return tf.reduce_mean(tf.square(tf.maximum((delta - logits), 0))) def d_loss_f(fake): return tf.reduce_mean(tf.maximum(1 + fake, 0)) def d_loss_r(real): return tf.reduce_mean(tf.maximum(1 - real, 0)) def g_loss_f(fake): return tf.reduce_mean(- fake) #@title Get models and optimizers & Set up learning rate #Get models and optimizers def get_networks(shape, load_model=False, path=None): if not load_model: gen,critic,siam = build() else: gen,critic,siam = load(path) print('Built networks') opt_gen = Adam(0.0001, 0.5) opt_disc = Adam(0.0001, 0.5) return gen,critic,siam, [opt_gen,opt_disc] #Set learning rate def update_lr(lr): opt_gen.learning_rate = lr opt_disc.learning_rate = lr #@title Training Functions set to Voice Modality #Training Functions #Train Generator, Siamese and Critic @tf.function def train_all(a,b): #splitting spectrogram in 3 parts aa,aa2,aa3 = extract_image(a) bb,bb2,bb3 = extract_image(b) with tf.GradientTape() as tape_gen, tf.GradientTape() as tape_disc: #translating A to B fab = gen(aa, training=True) fab2 = gen(aa2, training=True) fab3 = gen(aa3, training=True) #identity mapping B to B COMMENT THESE 3 LINES IF THE IDENTITY LOSS TERM IS NOT NEEDED fid = gen(bb, training=True) fid2 = gen(bb2, training=True) fid3 = gen(bb3, training=True) #concatenate/assemble converted spectrograms fabtot = assemble_image([fab,fab2,fab3]) #feed concatenated spectrograms to critic cab = critic(fabtot, training=True) cb = critic(b, training=True) #feed 2 pairs (A,G(A)) extracted spectrograms to Siamese sab = siam(fab, training=True) sab2 = siam(fab3, training=True) sa = siam(aa, training=True) sa2 = siam(aa3, training=True) #identity mapping loss loss_id = (mae(bb,fid)+mae(bb2,fid2)+mae(bb3,fid3))/3. #loss_id = 0. IF THE IDENTITY LOSS TERM IS NOT NEEDED #loss_id = 0. #travel loss loss_m = loss_travel(sa,sab,sa2,sab2)+loss_siamese(sa,sa2) #generator and critic losses loss_g = g_loss_f(cab) loss_dr = d_loss_r(cb) loss_df = d_loss_f(cab) loss_d = (loss_dr+loss_df)/2. #generator+siamese total loss lossgtot = loss_g+10.*loss_m+0.5*loss_id #CHANGE LOSS WEIGHTS HERE (COMMENT OUT +w*loss_id IF THE IDENTITY LOSS TERM IS NOT NEEDED) #computing and applying gradients grad_gen = tape_gen.gradient(lossgtot, gen.trainable_variables+siam.trainable_variables) opt_gen.apply_gradients(zip(grad_gen, gen.trainable_variables+siam.trainable_variables)) grad_disc = tape_disc.gradient(loss_d, critic.trainable_variables) opt_disc.apply_gradients(zip(grad_disc, critic.trainable_variables)) return loss_dr,loss_df,loss_g,loss_id #Train Critic only @tf.function def train_d(a,b): aa,aa2,aa3 = extract_image(a) with tf.GradientTape() as tape_disc: fab = gen(aa, training=True) fab2 = gen(aa2, training=True) fab3 = gen(aa3, training=True) fabtot = assemble_image([fab,fab2,fab3]) cab = critic(fabtot, training=True) cb = critic(b, training=True) loss_dr = d_loss_r(cb) loss_df = d_loss_f(cab) loss_d = (loss_dr+loss_df)/2. grad_disc = tape_disc.gradient(loss_d, critic.trainable_variables) opt_disc.apply_gradients(zip(grad_disc, critic.trainable_variables)) return loss_dr,loss_df #@title Training Functions set to Music Modality #Training Functions #Train Generator, Siamese and Critic @tf.function def train_all(a,b): #splitting spectrogram in 3 parts aa,aa2,aa3 = extract_image(a) bb,bb2,bb3 = extract_image(b) with tf.GradientTape() as tape_gen, tf.GradientTape() as tape_disc: #translating A to B fab = gen(aa, training=True) fab2 = gen(aa2, training=True) fab3 = gen(aa3, training=True) #identity mapping B to B COMMENT THESE 3 LINES IF THE IDENTITY LOSS TERM IS NOT NEEDED #fid = gen(bb, training=True) #fid2 = gen(bb2, training=True) #fid3 = gen(bb3, training=True) #concatenate/assemble converted spectrograms fabtot = assemble_image([fab,fab2,fab3]) #feed concatenated spectrograms to critic cab = critic(fabtot, training=True) cb = critic(b, training=True) #feed 2 pairs (A,G(A)) extracted spectrograms to Siamese sab = siam(fab, training=True) sab2 = siam(fab3, training=True) sa = siam(aa, training=True) sa2 = siam(aa3, training=True) #identity mapping loss #loss_id = (mae(bb,fid)+mae(bb2,fid2)+mae(bb3,fid3))/3. #loss_id = 0. IF THE IDENTITY LOSS TERM IS NOT NEEDED loss_id = 0. #travel loss loss_m = loss_travel(sa,sab,sa2,sab2)+loss_siamese(sa,sa2) #generator and critic losses loss_g = g_loss_f(cab) loss_dr = d_loss_r(cb) loss_df = d_loss_f(cab) loss_d = (loss_dr+loss_df)/2. #generator+siamese total loss lossgtot = loss_g+10.*loss_m #+0.5*loss_id #CHANGE LOSS WEIGHTS HERE (COMMENT OUT +w*loss_id IF THE IDENTITY LOSS TERM IS NOT NEEDED) #computing and applying gradients grad_gen = tape_gen.gradient(lossgtot, gen.trainable_variables+siam.trainable_variables) opt_gen.apply_gradients(zip(grad_gen, gen.trainable_variables+siam.trainable_variables)) grad_disc = tape_disc.gradient(loss_d, critic.trainable_variables) opt_disc.apply_gradients(zip(grad_disc, critic.trainable_variables)) return loss_dr,loss_df,loss_g,loss_id #Train Critic only @tf.function def train_d(a,b): aa,aa2,aa3 = extract_image(a) with tf.GradientTape() as tape_disc: fab = gen(aa, training=True) fab2 = gen(aa2, training=True) fab3 = gen(aa3, training=True) fabtot = assemble_image([fab,fab2,fab3]) cab = critic(fabtot, training=True) cb = critic(b, training=True) loss_dr = d_loss_r(cb) loss_df = d_loss_f(cab) loss_d = (loss_dr+loss_df)/2. grad_disc = tape_disc.gradient(loss_d, critic.trainable_variables) opt_disc.apply_gradients(zip(grad_disc, critic.trainable_variables)) return loss_dr,loss_df #@title Training Loop #Training Loop def train(epochs, batch_size=16, lr=0.0001, n_save=6, gupt=5): update_lr(lr) df_list = [] dr_list = [] g_list = [] id_list = [] c = 0 g = 0 for epoch in range(epochs): bef = time.time() for batchi,(a,b) in enumerate(zip(dsa,dsb)): if batchi%gupt==0: dloss_t,dloss_f,gloss,idloss = train_all(a,b) else: dloss_t,dloss_f = train_d(a,b) df_list.append(dloss_f) dr_list.append(dloss_t) g_list.append(gloss) id_list.append(idloss) c += 1 g += 1 if batchi%600==0: print(f'[Epoch {epoch}/{epochs}] [Batch {batchi}] [D loss f: {np.mean(df_list[-g:], axis=0)} ', end='') print(f'r: {np.mean(dr_list[-g:], axis=0)}] ', end='') print(f'[G loss: {np.mean(g_list[-g:], axis=0)}] ', end='') print(f'[ID loss: {np.mean(id_list[-g:])}] ', end='') print(f'[LR: {lr}]') g = 0 nbatch=batchi print(f'Time/Batch {(time.time()-bef)/nbatch}') save_end(epoch,np.mean(g_list[-n_save*c:], axis=0),np.mean(df_list[-n_save*c:], axis=0),np.mean(id_list[-n_save*c:], axis=0),n_save=n_save) print(f'Mean D loss: {np.mean(df_list[-c:], axis=0)} Mean G loss: {np.mean(g_list[-c:], axis=0)} Mean ID loss: {np.mean(id_list[-c:], axis=0)}') c = 0 #@title Build models and initialize optimizers. If resume_model=True, specify the path where the models are saved resume_model = True #@param {type:"boolean"} model_checkpoints_directory = "/content/MelGAN-VC/checkpoint" #@param {type:"string"} #Build models and initialize optimizers #If load_model=True, specify the path where the models are saved gen,critic,siam, [opt_gen,opt_disc] = get_networks(shape, load_model=resume_model, path=model_checkpoints_directory) #@title Training. epoch_save = how many epochs between each saving and displaying of results. n_epochs = how many epochs the model will train epoch_save = 10#@param {type:"integer"} n_epochs = 3000 #@param {type:"integer"} #Training #n_save = how many epochs between each saving and displaying of results #gupt = how many discriminator updates for generator+siamese update train(n_epochs, batch_size=bs, lr=0.0002, n_save=epoch_save, gupt=3) #@title After Training, use these functions to convert data with the generator and save the results #After Training, use these functions to convert data with the generator and save the results #Assembling generated Spectrogram chunks into final Spectrogram def specass(a,spec): but=False con = np.array([]) nim = a.shape[0] for i in range(nim-1): im = a[i] im = np.squeeze(im) if not but: con=im but=True else: con = np.concatenate((con,im), axis=1) diff = spec.shape[1]-(nim*shape) a = np.squeeze(a) con = np.concatenate((con,a[-1,:,-diff:]), axis=1) return np.squeeze(con) #Splitting input spectrogram into different chunks to feed to the generator def chopspec(spec): dsa=[] for i in range(spec.shape[1]//shape): im = spec[:,i*shape:i*shape+shape] im = np.reshape(im, (im.shape[0],im.shape[1],1)) dsa.append(im) imlast = spec[:,-shape:] imlast = np.reshape(imlast, (imlast.shape[0],imlast.shape[1],1)) dsa.append(imlast) return np.array(dsa, dtype=np.float32) #Converting from source Spectrogram to target Spectrogram def towave(spec, name, path='../content/', show=False): specarr = chopspec(spec) print(specarr.shape) a = specarr print('Generating...') ab = gen(a, training=False) print('Assembling and Converting...') a = specass(a,spec) ab = specass(ab,spec) awv = deprep(a) abwv = deprep(ab) print('Saving...') pathfin = f'{path}/{name}' os.mkdir(pathfin) sf.write(pathfin+'/AB.wav', abwv, sr) sf.write(pathfin+'/A.wav', awv, sr) print('Saved WAV!') IPython.display.display(IPython.display.Audio(np.squeeze(abwv), rate=sr)) IPython.display.display(IPython.display.Audio(np.squeeze(awv), rate=sr)) if show: fig, axs = plt.subplots(ncols=2) axs[0].imshow(np.flip(a, -2), cmap=None) axs[0].axis('off') axs[0].set_title('Source') axs[1].imshow(np.flip(ab, -2), cmap=None) axs[1].axis('off') axs[1].set_title('Generated') plt.show() return abwv #@title Generator and wav to wav conversion input_wav = "/content/flautaindigena/23.wav" #@param {type:"string"} output_name = "flauta_to_AntonioZepeda" #@param {type:"string"} output_directory = "/content/MelGAN-VC" #@param {type:"string"} #Wav to wav conversion wv, sr = librosa.load(input_wav, sr=44100) #Load waveform print(wv.shape) speca = prep(wv) #Waveform to Spectrogram plt.figure(figsize=(50,1)) #Show Spectrogram plt.imshow(np.flip(speca, axis=0), cmap=None) plt.axis('off') plt.show() abwv = towave(speca, name=output_name, path=output_directory) #Convert and save wav ```
github_jupyter
# VQE for Unitary Coupled Cluster using tket In this tutorial, we will focus on:<br> - building parameterised ansätze for variational algorithms;<br> - compilation tools for UCC-style ansätze. This example assumes the reader is familiar with the Variational Quantum Eigensolver and its application to electronic structure problems through the Unitary Coupled Cluster approach.<br> <br> To run this example, you will need `pytket` and `pytket-qiskit`, as well as `openfermion`, `scipy`, and `sympy`.<br> <br> We will start with a basic implementation and then gradually modify it to make it faster, more general, and less noisy. The final solution is given in full at the bottom of the notebook.<br> <br> Suppose we have some electronic configuration problem, expressed via a physical Hamiltonian. (The Hamiltonian and excitations in this example were obtained using `qiskit-aqua` version 0.5.2 and `pyscf` for H2, bond length 0.75A, sto3g basis, Jordan-Wigner encoding, with no qubit reduction or orbital freezing.) ``` from openfermion import QubitOperator hamiltonian = ( -0.8153001706270075 * QubitOperator("") + 0.16988452027940318 * QubitOperator("Z0") + -0.21886306781219608 * QubitOperator("Z1") + 0.16988452027940323 * QubitOperator("Z2") + -0.2188630678121961 * QubitOperator("Z3") + 0.12005143072546047 * QubitOperator("Z0 Z1") + 0.16821198673715723 * QubitOperator("Z0 Z2") + 0.16549431486978672 * QubitOperator("Z0 Z3") + 0.16549431486978672 * QubitOperator("Z1 Z2") + 0.1739537877649417 * QubitOperator("Z1 Z3") + 0.12005143072546047 * QubitOperator("Z2 Z3") + 0.04544288414432624 * QubitOperator("X0 X1 X2 X3") + 0.04544288414432624 * QubitOperator("X0 X1 Y2 Y3") + 0.04544288414432624 * QubitOperator("Y0 Y1 X2 X3") + 0.04544288414432624 * QubitOperator("Y0 Y1 Y2 Y3") ) nuclear_repulsion_energy = 0.70556961456 ``` We would like to define our ansatz for arbitrary parameter values. For simplicity, let's start with a Hardware Efficient Ansatz. ``` from pytket import Circuit ``` Hardware efficient ansatz: ``` def hea(params): ansatz = Circuit(4) for i in range(4): ansatz.Ry(params[i], i) for i in range(3): ansatz.CX(i, i + 1) for i in range(4): ansatz.Ry(params[4 + i], i) return ansatz ``` We can use this to build the objective function for our optimisation. ``` from pytket.extensions.qiskit import AerBackend from pytket.utils import expectation_from_counts backend = AerBackend() ``` Naive objective function: ``` def objective(params): energy = 0 for term, coeff in hamiltonian.terms.items(): if not term: energy += coeff continue circ = hea(params) circ.add_c_register("c", len(term)) for i, (q, pauli) in enumerate(term): if pauli == "X": circ.H(q) elif pauli == "Y": circ.V(q) circ.Measure(q, i) backend.compile_circuit(circ) counts = backend.run_circuit(circ, n_shots=4000).get_counts() energy += coeff * expectation_from_counts(counts) return energy + nuclear_repulsion_energy ``` This objective function is then run through a classical optimiser to find the set of parameter values that minimise the energy of the system. For the sake of example, we will just run this with a single parameter value. ``` arg_values = [ -7.31158201e-02, -1.64514836e-04, 1.12585591e-03, -2.58367544e-03, 1.00006068e00, -1.19551357e-03, 9.99963988e-01, 2.53283285e-03, ] energy = objective(arg_values) print(energy) ``` The HEA is designed to cram as many orthogonal degrees of freedom into a small circuit as possible to be able to explore a large region of the Hilbert space whilst the circuits themselves can be run with minimal noise. These ansätze give virtually-optimal circuits by design, but suffer from an excessive number of variational parameters making convergence slow, barren plateaus where the classical optimiser fails to make progress, and spanning a space where most states lack a physical interpretation. These drawbacks can necessitate adding penalties and may mean that the ansatz cannot actually express the true ground state.<br> <br> The UCC ansatz, on the other hand, is derived from the electronic configuration. It sacrifices efficiency of the circuit for the guarantee of physical states and the variational parameters all having some meaningful effect, which helps the classical optimisation to converge.<br> <br> This starts by defining the terms of our single and double excitations. These would usually be generated using the orbital configurations, so we will just use a hard-coded example here for the purposes of demonstration. ``` from pytket.pauli import Pauli, QubitPauliString from pytket.circuit import Qubit q = [Qubit(i) for i in range(4)] xyii = QubitPauliString([q[0], q[1]], [Pauli.X, Pauli.Y]) yxii = QubitPauliString([q[0], q[1]], [Pauli.Y, Pauli.X]) iixy = QubitPauliString([q[2], q[3]], [Pauli.X, Pauli.Y]) iiyx = QubitPauliString([q[2], q[3]], [Pauli.Y, Pauli.X]) xxxy = QubitPauliString(q, [Pauli.X, Pauli.X, Pauli.X, Pauli.Y]) xxyx = QubitPauliString(q, [Pauli.X, Pauli.X, Pauli.Y, Pauli.X]) xyxx = QubitPauliString(q, [Pauli.X, Pauli.Y, Pauli.X, Pauli.X]) yxxx = QubitPauliString(q, [Pauli.Y, Pauli.X, Pauli.X, Pauli.X]) yyyx = QubitPauliString(q, [Pauli.Y, Pauli.Y, Pauli.Y, Pauli.X]) yyxy = QubitPauliString(q, [Pauli.Y, Pauli.Y, Pauli.X, Pauli.Y]) yxyy = QubitPauliString(q, [Pauli.Y, Pauli.X, Pauli.Y, Pauli.Y]) xyyy = QubitPauliString(q, [Pauli.X, Pauli.Y, Pauli.Y, Pauli.Y]) singles_a = {xyii: 1.0, yxii: -1.0} singles_b = {iixy: 1.0, iiyx: -1.0} doubles = { xxxy: 0.25, xxyx: -0.25, xyxx: 0.25, yxxx: -0.25, yyyx: -0.25, yyxy: 0.25, yxyy: -0.25, xyyy: 0.25, } ``` Building the ansatz circuit itself is often done naively by defining the map from each term down to basic gates and then applying it to each term. ``` def add_operator_term(circuit: Circuit, term: QubitPauliString, angle: float): qubits = [] for q, p in term.map.items(): if p != Pauli.I: qubits.append(q) if p == Pauli.X: circuit.H(q) elif p == Pauli.Y: circuit.V(q) for i in range(len(qubits) - 1): circuit.CX(i, i + 1) circuit.Rz(angle, len(qubits) - 1) for i in reversed(range(len(qubits) - 1)): circuit.CX(i, i + 1) for q, p in term.map.items(): if p == Pauli.X: circuit.H(q) elif p == Pauli.Y: circuit.Vdg(q) ``` Unitary Coupled Cluster Singles & Doubles ansatz: ``` def ucc(params): ansatz = Circuit(4) # Set initial reference state ansatz.X(1).X(3) # Evolve by excitations for term, coeff in singles_a.items(): add_operator_term(ansatz, term, coeff * params[0]) for term, coeff in singles_b.items(): add_operator_term(ansatz, term, coeff * params[1]) for term, coeff in doubles.items(): add_operator_term(ansatz, term, coeff * params[2]) return ansatz ``` This is already quite verbose, but `pytket` has a neat shorthand construction for these operator terms using the `PauliExpBox` construction. We can then decompose these into basic gates using the `DecomposeBoxes` compiler pass. ``` from pytket.circuit import PauliExpBox from pytket.passes import DecomposeBoxes def add_excitation(circ, term_dict, param): for term, coeff in term_dict.items(): qubits, paulis = zip(*term.map.items()) pbox = PauliExpBox(paulis, coeff * param) circ.add_pauliexpbox(pbox, qubits) ``` UCC ansatz with syntactic shortcuts: ``` def ucc(params): ansatz = Circuit(4) ansatz.X(1).X(3) add_excitation(ansatz, singles_a, params[0]) add_excitation(ansatz, singles_b, params[1]) add_excitation(ansatz, doubles, params[2]) DecomposeBoxes().apply(ansatz) return ansatz ``` The objective function can also be simplified using a utility method for constructing the measurement circuits and processing for expectation value calculations. ``` from pytket.utils.operators import QubitPauliOperator from pytket.utils import get_operator_expectation_value hamiltonian_op = QubitPauliOperator.from_OpenFermion(hamiltonian) ``` Simplified objective function using utilities: ``` def objective(params): circ = ucc(params) return ( get_operator_expectation_value(circ, hamiltonian_op, backend, n_shots=4000) + nuclear_repulsion_energy ) arg_values = [-3.79002933e-05, 2.42964799e-05, 4.63447157e-01] energy = objective(arg_values) print(energy) ``` This is now the simplest form that this operation can take, but it isn't necessarily the most effective. When we decompose the ansatz circuit into basic gates, it is still very expensive. We can employ some of the circuit simplification passes available in `pytket` to reduce its size and improve fidelity in practice.<br> <br> A good example is to decompose each `PauliExpBox` into basic gates and then apply `FullPeepholeOptimise`, which defines a compilation strategy utilising all of the simplifications in `pytket` that act locally on small regions of a circuit. We can examine the effectiveness by looking at the number of two-qubit gates before and after simplification, which tends to be a good indicator of fidelity for near-term systems where these gates are often slow and inaccurate. ``` from pytket import OpType from pytket.passes import FullPeepholeOptimise test_circuit = ucc(arg_values) print("CX count before", test_circuit.n_gates_of_type(OpType.CX)) print("CX depth before", test_circuit.depth_by_type(OpType.CX)) FullPeepholeOptimise().apply(test_circuit) print("CX count after FPO", test_circuit.n_gates_of_type(OpType.CX)) print("CX depth after FPO", test_circuit.depth_by_type(OpType.CX)) ``` These simplification techniques are very general and are almost always beneficial to apply to a circuit if you want to eliminate local redundancies. But UCC ansätze have extra structure that we can exploit further. They are defined entirely out of exponentiated tensors of Pauli matrices, giving the regular structure described by the `PauliExpBox`es. Under many circumstances, it is more efficient to not synthesise these constructions individually, but simultaneously in groups. The `PauliSimp` pass finds the description of a given circuit as a sequence of `PauliExpBox`es and resynthesises them (by default, in groups of commuting terms). This can cause great change in the overall structure and shape of the circuit, enabling the identification and elimination of non-local redundancy. ``` from pytket.passes import PauliSimp test_circuit = ucc(arg_values) print("CX count before", test_circuit.n_gates_of_type(OpType.CX)) print("CX depth before", test_circuit.depth_by_type(OpType.CX)) PauliSimp().apply(test_circuit) print("CX count after PS", test_circuit.n_gates_of_type(OpType.CX)) print("CX depth after PS", test_circuit.depth_by_type(OpType.CX)) FullPeepholeOptimise().apply(test_circuit) print("CX count after PS+FPO", test_circuit.n_gates_of_type(OpType.CX)) print("CX depth after PS+FPO", test_circuit.depth_by_type(OpType.CX)) ``` To include this into our routines, we can just add the simplification passes to the objective function. The `get_operator_expectation_value` utility handles compiling to meet the requirements of the backend, so we don't have to worry about that here. Objective function with circuit simplification: ``` def objective(params): circ = ucc(params) PauliSimp().apply(circ) FullPeepholeOptimise().apply(circ) return ( get_operator_expectation_value(circ, hamiltonian_op, backend, n_shots=4000) + nuclear_repulsion_energy ) ``` These circuit simplification techniques have tried to preserve the exact unitary of the circuit, but there are ways to change the unitary whilst preserving the correctness of the algorithm as a whole.<br> <br> For example, the excitation terms are generated by trotterisation of the excitation operator, and the order of the terms does not change the unitary in the limit of many trotter steps, so in this sense we are free to sequence the terms how we like and it is sensible to do this in a way that enables efficient synthesis of the circuit. Prioritising collecting terms into commuting sets is a very beneficial heuristic for this and can be performed using the `gen_term_sequence_circuit` method to group the terms together into collections of `PauliExpBox`es and the `GuidedPauliSimp` pass to utilise these sets for synthesis. ``` from pytket.passes import GuidedPauliSimp from pytket.utils import gen_term_sequence_circuit def ucc(params): singles_params = {qps: params[0] * coeff for qps, coeff in singles.items()} doubles_params = {qps: params[1] * coeff for qps, coeff in doubles.items()} excitation_op = QubitPauliOperator({**singles_params, **doubles_params}) reference_circ = Circuit(4).X(1).X(3) ansatz = gen_term_sequence_circuit(excitation_op, reference_circ) GuidedPauliSimp().apply(ansatz) FullPeepholeOptimise().apply(ansatz) return ansatz ``` Adding these simplification routines doesn't come for free. Compiling and simplifying the circuit to achieve the best results possible can be a difficult task, which can take some time for the classical computer to perform.<br> <br> During a VQE run, we will call this objective function many times and run many measurement circuits within each, but the circuits that are run on the quantum computer are almost identical, having the same gate structure but with different gate parameters and measurements. We have already exploited this within the body of the objective function by simplifying the ansatz circuit before we call `get_operator_expectation_value`, so it is only done once per objective calculation rather than once per measurement circuit.<br> <br> We can go even further by simplifying it once outside of the objective function, and then instantiating the simplified ansatz with the parameter values needed. For this, we will construct the UCC ansatz circuit using symbolic (parametric) gates. ``` from sympy import symbols ``` Symbolic UCC ansatz generation: ``` syms = symbols("p0 p1 p2") singles_a_syms = {qps: syms[0] * coeff for qps, coeff in singles_a.items()} singles_b_syms = {qps: syms[1] * coeff for qps, coeff in singles_b.items()} doubles_syms = {qps: syms[2] * coeff for qps, coeff in doubles.items()} excitation_op = QubitPauliOperator({**singles_a_syms, **singles_b_syms, **doubles_syms}) ucc_ref = Circuit(4).X(1).X(3) ucc = gen_term_sequence_circuit(excitation_op, ucc_ref) GuidedPauliSimp().apply(ucc) FullPeepholeOptimise().apply(ucc) ``` Objective function using the symbolic ansatz: ``` def objective(params): circ = ucc.copy() sym_map = dict(zip(syms, params)) circ.symbol_substitution(sym_map) return ( get_operator_expectation_value(circ, hamiltonian_op, backend, n_shots=4000) + nuclear_repulsion_energy ) ``` We have now got some very good use of `pytket` for simplifying each individual circuit used in our experiment and for minimising the amount of time spent compiling, but there is still more we can do in terms of reducing the amount of work the quantum computer has to do. Currently, each (non-trivial) term in our measurement hamiltonian is measured by a different circuit within each expectation value calculation. Measurement reduction techniques exist for identifying when these observables commute and hence can be simultaneously measured, reducing the number of circuits required for the full expectation value calculation.<br> <br> This is built in to the `get_operator_expectation_value` method and can be applied by specifying a way to partition the measuremrnt terms. `PauliPartitionStrat.CommutingSets` can greatly reduce the number of measurement circuits by combining any number of terms that mutually commute. However, this involves potentially adding an arbitrary Clifford circuit to change the basis of the measurements which can be costly on NISQ devices, so `PauliPartitionStrat.NonConflictingSets` trades off some of the reduction in circuit number to guarantee that only single-qubit gates are introduced. ``` from pytket.partition import PauliPartitionStrat ``` Objective function using measurement reduction: ``` def objective(params): circ = ucc.copy() sym_map = dict(zip(syms, params)) circ.symbol_substitution(sym_map) return ( get_operator_expectation_value( circ, operator, backend, n_shots=4000, partition_strat=PauliPartitionStrat.CommutingSets, ) + nuclear_repulsion_energy ) ``` At this point, we have completely transformed how our VQE objective function works, improving its resilience to noise, cutting the number of circuits run, and maintaining fast runtimes. In doing this, we have explored a number of the features `pytket` offers that are beneficial to VQE and the UCC method:<br> - high-level syntactic constructs for evolution operators;<br> - utility methods for easy expectation value calculations;<br> - both generic and domain-specific circuit simplification methods;<br> - symbolic circuit compilation;<br> - measurement reduction for expectation value calculations. For the sake of completeness, the following gives the full code for the final solution, including passing the objective function to a classical optimiser to find the ground state: ``` from openfermion import QubitOperator from scipy.optimize import minimize from sympy import symbols from pytket.extensions.qiskit import AerBackend from pytket.circuit import Circuit, Qubit from pytket.partition import PauliPartitionStrat from pytket.passes import GuidedPauliSimp, FullPeepholeOptimise from pytket.pauli import Pauli, QubitPauliString from pytket.utils import get_operator_expectation_value, gen_term_sequence_circuit from pytket.utils.operators import QubitPauliOperator ``` Obtain electronic Hamiltonian: ``` hamiltonian = ( -0.8153001706270075 * QubitOperator("") + 0.16988452027940318 * QubitOperator("Z0") + -0.21886306781219608 * QubitOperator("Z1") + 0.16988452027940323 * QubitOperator("Z2") + -0.2188630678121961 * QubitOperator("Z3") + 0.12005143072546047 * QubitOperator("Z0 Z1") + 0.16821198673715723 * QubitOperator("Z0 Z2") + 0.16549431486978672 * QubitOperator("Z0 Z3") + 0.16549431486978672 * QubitOperator("Z1 Z2") + 0.1739537877649417 * QubitOperator("Z1 Z3") + 0.12005143072546047 * QubitOperator("Z2 Z3") + 0.04544288414432624 * QubitOperator("X0 X1 X2 X3") + 0.04544288414432624 * QubitOperator("X0 X1 Y2 Y3") + 0.04544288414432624 * QubitOperator("Y0 Y1 X2 X3") + 0.04544288414432624 * QubitOperator("Y0 Y1 Y2 Y3") ) nuclear_repulsion_energy = 0.70556961456 hamiltonian_op = QubitPauliOperator.from_OpenFermion(hamiltonian) ``` Obtain terms for single and double excitations: ``` q = [Qubit(i) for i in range(4)] xyii = QubitPauliString([q[0], q[1]], [Pauli.X, Pauli.Y]) yxii = QubitPauliString([q[0], q[1]], [Pauli.Y, Pauli.X]) iixy = QubitPauliString([q[2], q[3]], [Pauli.X, Pauli.Y]) iiyx = QubitPauliString([q[2], q[3]], [Pauli.Y, Pauli.X]) xxxy = QubitPauliString(q, [Pauli.X, Pauli.X, Pauli.X, Pauli.Y]) xxyx = QubitPauliString(q, [Pauli.X, Pauli.X, Pauli.Y, Pauli.X]) xyxx = QubitPauliString(q, [Pauli.X, Pauli.Y, Pauli.X, Pauli.X]) yxxx = QubitPauliString(q, [Pauli.Y, Pauli.X, Pauli.X, Pauli.X]) yyyx = QubitPauliString(q, [Pauli.Y, Pauli.Y, Pauli.Y, Pauli.X]) yyxy = QubitPauliString(q, [Pauli.Y, Pauli.Y, Pauli.X, Pauli.Y]) yxyy = QubitPauliString(q, [Pauli.Y, Pauli.X, Pauli.Y, Pauli.Y]) xyyy = QubitPauliString(q, [Pauli.X, Pauli.Y, Pauli.Y, Pauli.Y]) ``` Symbolic UCC ansatz generation: ``` syms = symbols("p0 p1 p2") singles_syms = {xyii: syms[0], yxii: -syms[0], iixy: syms[1], iiyx: -syms[1]} doubles_syms = { xxxy: 0.25 * syms[2], xxyx: -0.25 * syms[2], xyxx: 0.25 * syms[2], yxxx: -0.25 * syms[2], yyyx: -0.25 * syms[2], yyxy: 0.25 * syms[2], yxyy: -0.25 * syms[2], xyyy: 0.25 * syms[2], } excitation_op = QubitPauliOperator({**singles_syms, **doubles_syms}) ucc_ref = Circuit(4).X(0).X(2) ucc = gen_term_sequence_circuit(excitation_op, ucc_ref) ``` Circuit simplification: ``` GuidedPauliSimp().apply(ucc) FullPeepholeOptimise().apply(ucc) ``` Connect to a simulator/device: ``` backend = AerBackend() ``` Objective function: ``` def objective(params): circ = ucc.copy() sym_map = dict(zip(syms, params)) circ.symbol_substitution(sym_map) return ( get_operator_expectation_value( circ, hamiltonian_op, backend, n_shots=4000, partition_strat=PauliPartitionStrat.CommutingSets, ) + nuclear_repulsion_energy ).real ``` Optimise against the objective function: ``` initial_params = [1e-4, 1e-4, 4e-1] result = minimize(objective, initial_params, method="Nelder-Mead") print("Final parameter values", result.x) print("Final energy value", result.fun) ``` Exercises:<br> - Replace the `get_operator_expectation_value` call with its implementation and use this to pull the analysis for measurement reduction outside of the objective function, so our circuits can be fully determined and compiled once. This means that the `symbol_substitution` method will need to be applied to each measurement circuit instead of just the state preparation circuit.<br> - Use the `SpamCorrecter` class to add some mitigation of the measurement errors. Start by running the characterisation circuits first, before your main VQE loop, then apply the mitigation to each of the circuits run within the objective function.<br> - Change the `backend` by passing in a `Qiskit` `NoiseModel` to simulate a noisy device. Compare the accuracy of the objective function both with and without the circuit simplification. Try running a classical optimiser over the objective function and compare the convergence rates with different noise models. If you have access to a QPU, try changing the `backend` to connect to that and compare the results to the simulator.
github_jupyter
![seQuencing logo](../images/sequencing-logo.svg) # Sequences In some cases, one may want to intersperse ideal unitary gates within a sequence of time-dependent operations. This is possible using an object called a [Sequence](../api/classes.rst#Sequence). A `Sequence` is essentially a list containing [PulseSequences](../api/classes.rst#PulseSequence), [Operations](../api/classes.rst#Operation), and unitary operators. When `Sequence.run(init_state)` is called, the `Sequence` iterates over its constituent `PulseSequences`, `Operations`, and unitaries, applying each to the resulting state of the last. `Sequence` is designed to behave like a Python [list](https://docs.python.org/3/tutorial/datastructures.html), so it has the following methods defined: - `append()` - `extend()` - `insert()` - `pop()` - `clear()` - `__len__()` - `__getitem__()` - `__iter__()` **Notes:** - Just like a `PulseSequence` or `CompiledPulseSequence`, a `Sequence` must be associated with a `System`. - Whereas `PulseSequence.run()` and `CompiledPulseSequence.run()` return an instance of `qutip.solver.Result`, `Sequence.run()` returns a [SequenceResult](../api/classes.rst#SequenceResult) object, which behaves just like `qutip.solver.Result`. `SequenceResult.states` stores the quantum `states` after each stage of the simulation (`states[0]` is `init_state` and `states[-1]` is the final state of the system). ``` %config InlineBackend.figure_formats = ['svg'] %matplotlib inline import matplotlib.pyplot as plt import numpy as np import qutip from sequencing import Transmon, Cavity, System, Sequence qubit = Transmon('qubit', levels=3, kerr=-200e-3) cavity = Cavity('cavity', levels=10, kerr=-10e-6) system = System('system', modes=[qubit, cavity]) system.set_cross_kerr(cavity, qubit, chi=-2e-3) qubit.gaussian_pulse.drag = 5 ``` ## Interleave pulses and unitaries Here we perform a "$\pi$-pulse" composed of $20$ interleaved $\frac{\pi}{40}$-pulses and unitary rotations. ``` init_state = system.ground_state() # calculate expectation value of |qubit=1, cavity=0> e_ops = [system.fock_dm(qubit=1)] n_rotations = 20 theta = np.pi / n_rotations seq = Sequence(system) for _ in range(n_rotations): # Capture a PulseSequence qubit.rotate_x(theta/2) # # Alternatively, we can append an Operation # operation = qubit.rotate_x(theta/2, capture=False) # seq.append(operation) # Append a unitary seq.append(qubit.Rx(theta/2)) result = seq.run(init_state, e_ops=e_ops, full_evolution=True, progress_bar=True) states = result.states ``` ### Inspect the sequence `Sequence.plot_coefficients()` plots Hamiltonian coefficients vs. time. Instantaneous unitary operations are represented by dashed vertical lines. If multiple unitaries occur at the same time, only a single dashed line is drawn. ``` fig, ax = seq.plot_coefficients(subplots=False) ax.set_xlabel('Time [ns]') ax.set_ylabel('Hamiltonian coefficient [GHz]') fig.set_size_inches(8,4) fig.tight_layout() fig.subplots_adjust(top=0.9) print('len(states):', len(states)) print(f'state fidelity: {qutip.fidelity(states[-1], qubit.Rx(np.pi) * init_state)**2:.4f}') ``` ### Plot the results ``` e_pops = result.expect[0] # probability of measuring the state |qubit=1, cavity=0> fig, ax = plt.subplots(figsize=(8,4)) ax.plot(result.times, e_pops, '.') ax.scatter(result.times[:1], e_pops[:1], marker='s', color='k', label='init_state') # draw vertical lines at the location of each unitary rotation for i in range(1, result.times.size // (2*n_rotations) + 1): t = 2 * n_rotations * i - 1 label = 'unitaries' if i == 1 else None ax.axvline(t, color='k', alpha=0.25, ls='--', lw=1.5, label=label) ax.axhline(0, color='k', lw=1) ax.axhline(1, color='k', lw=1) ax.set_ylabel('$P(|e\\rangle)$') ax.set_xlabel('Times [ns]') ax.set_title('Interleaved pulses and unitaries') ax.legend(loc=0); print(result) from qutip.ipynbtools import version_table version_table() ```
github_jupyter
``` import numpy as np import pandas as pd import os # import matplotlib.pyplot as plt # from PIL import Image, ImageDraw, ImageEnhance from tqdm.notebook import tqdm # import cv2 import re import time import sys sys.path.append('../') from retinanet import coco_eval from retinanet import csv_eval from retinanet import model # from retinanet import retina from retinanet.dataloader import * from retinanet.anchors import Anchors from retinanet.losses import * from retinanet.scheduler import * from retinanet.parallel import DataParallelModel, DataParallelCriterion # from sklearn.model_selection import train_test_split # from sklearn.preprocessing import LabelEncoder #Torch import torch import torch.nn as nn from torch.utils.data import Dataset,DataLoader from torch.utils.data.sampler import SequentialSampler, RandomSampler from torch.optim import Adam, lr_scheduler import torch.optim as optim # device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # print ('Available devices ', torch.cuda.device_count()) # print ('Current cuda device ', torch.cuda.current_device()) # print(torch.cuda.get_device_name(device)) # GPU 할당 변경하기 GPU_NUM = 5 # 원하는 GPU 번호 입력 device = torch.device(f'cuda:{GPU_NUM}' if torch.cuda.is_available() else 'cpu') torch.cuda.set_device(device) # change allocation of current GPU print(device) print ('Current cuda device ', torch.cuda.current_device()) # check device_ids = [5,6] # device_ids = [4,3,2] # # torch.load(PATH_TO_WEIGHTS, map_location=device) # %time # PATH_TO_WEIGHTS = '../coco_resnet_50_map_0_335_state_dict.pt' # retinanet = model.resnet50(num_classes=2, device=device) # retinanet.load_state_dict(torch.load(PATH_TO_WEIGHTS, map_location=device), strict=False) # state_dict = model.state_dict() # state_dict['classifier.weight'] = torch.randn(10, 10) # model.load_state_dict(state_dict) # state_dict = pretrained_retinanet.state_dict() # state_dict['bn1.bias'] = torch.zeros([64]) # state_dict['bn1.bias'] # pretrained_retinanet.load_state_dict(state_dict) # pretrained_retinanet.state_dict()['bn1.bias'] %time PATH_TO_WEIGHTS = '../coco_resnet_50_map_0_335_state_dict.pt' pre_retinanet = model.resnet50(num_classes=80, device=device) pre_retinanet.load_state_dict(torch.load(PATH_TO_WEIGHTS, map_location=device), strict=False) pre_retinanet.classificationModel.output = nn.Conv2d(256, 18, kernel_size=3, padding=1) retinanet = model.resnet50(num_classes=2, device=device) retinanet.load_state_dict(pre_retinanet.state_dict(), strict=False) del pre_retinanet state_dict = retinanet.residualafterFPN.state_dict() # state_dict = retinanet.state_dict() for s in state_dict: if 'bn' in s : if 'weight' in s : print(s) shape = state_dict[s].shape state_dict[s] = torch.zeros(shape) elif 'bias' in s : print(s) shape = state_dict[s].shape # state_dict[s] = torch.zeros(shape) state_dict[s] = torch.ones(shape) # print(residual_state_dict[s]) retinanet.residualafterFPN.load_state_dict(state_dict) # retinanet.to(device) retinanet = torch.nn.DataParallel(retinanet, device_ids = [5,6], output_device=GPU_NUM).to(device) # retinanet = DataParallelModel(retinanet, device_ids = device_ids) #retinanet.to(device) # retinanet.cuda() # retinanet.module.freeze_ex_bn() #retinanet.module.freeze_ex_bn(False) #retinanet.freeze_ex_bn(False) # for n, p in retinanet.named_parameters(): # #print(n) # if 'bn' not in n : # if 'fpn' not in n and 'residualafterFPN' not in n and 'regressionModel' not in n and 'classificationModel' not in n : # #print(param) # print(n) # p.requires_grad = False # for k, p in zip(retinanet.module.state_dict(), retinanet.module.parameters()) : # if 'bn' not in k : # # print(k) # p.requires_grad = False # # print(p) # train_info = np.load('../data/train.npy', allow_pickle=True, encoding='latin1').item() # train_info batch_size = 32 dataset_train = PapsDataset('../data/', set_name='train_2class', transform=train_transforms) train_data_loader = DataLoader( dataset_train, batch_size=batch_size, shuffle=True, num_workers=16, pin_memory=True, prefetch_factor=1, collate_fn=collate_fn ) criterion = FocalLoss(device) criterion = criterion.to(device) retinanet.training = True # https://gaussian37.github.io/dl-pytorch-lr_scheduler/ optimizer = optim.Adam(retinanet.parameters(), lr = 1e-8) scheduler = CosineAnnealingWarmUpRestarts(optimizer, T_0=20, T_mult=2, eta_max=0.0008, T_up=5, gamma=0.5) # CosineAnnealingWarmRestarts # state_dict = retinanet.module.residualafterFPN.state_dict() # for s in state_dict: # if 'bn' in s : # if 'weight' in s : # print(s) # print(state_dict[s]) # elif 'bias' in s : # print(s) # print(state_dict[s]) retinanet.module.freeze_ex_bn(False) #for i, data in enumerate(tqdm(train_data_loader)) : EPOCH_NUM = 160 loss_per_epoch = 0.6 optimizer.param_groups[0]["lr"] = 0.00002 for epoch in range(EPOCH_NUM) : if epoch == int(EPOCH_NUM *0.2) : retinanet.module.freeze_ex_bn(True) total_loss = 0 tk0 = tqdm(train_data_loader, total=len(train_data_loader), leave=False) EPOCH_LEARING_RATE = optimizer.param_groups[0]["lr"] start_time = time.time() # print("*****{}th epoch, learning rate {}".format(epoch, EPOCH_LEARING_RATE)) for step, data in enumerate(tk0) : if step > len(train_data_loader)/4 and epoch < int(EPOCH_NUM*0.8) : break images, box, label, targets = data batch_size = len(images) c, h, w = images[0].shape images = torch.cat(images).view(-1, c, h, w).to(device) targets = [ t.to(device) for t in targets] outputs = retinanet([images, targets]) classification, regression, anchors, annotations = (outputs) classification_loss, regression_loss = criterion(classification, regression, anchors, annotations) classification_loss = classification_loss.mean() regression_loss = regression_loss.mean() loss = classification_loss + regression_loss total_loss += loss.item() if step % 5 == 0: tk0.set_postfix(lr=optimizer.param_groups[0]["lr"], batch_loss=loss.item(), cls_loss=classification_loss.item(), reg_loss=regression_loss.item(), avg_loss=total_loss/(step+1)) optimizer.zero_grad() loss.backward() torch.nn.utils.clip_grad_norm_(retinanet.parameters(), 0.02) optimizer.step() print('{}th epochs loss is {}'.format(epoch, total_loss/(step+1))) if loss_per_epoch > total_loss/(step+1): print('best model is saved') torch.save(retinanet.state_dict(), '../trained_models/resnet50_320_ex_bn/best_model.pt') loss_per_epoch = total_loss/(step+1) scheduler.step() # print('epoch training time is ', time.time() - start_time) torch.save(retinanet.state_dict(), '../trained_models/resnet50_320_ex_bn/model.pt') # for n, p in retinanet.named_parameters(): # #print(n) # if 'bn' not in n : # if 'fpn' not in n and 'residualafterFPN' not in n and 'regressionModel' not in n and 'classificationModel' not in n : # #print(param) # print(n) # print(p[0]) # #p.requires_grad = False # for n, p in retinanet.named_parameters(): # #print(n) # if 'bn' not in n : # if 'fpn' not in n and 'residualafterFPN' not in n and 'regressionModel' not in n and 'classificationModel' not in n : # #print(param) # print(n) # print(p[0]) # #p.requires_grad = False # state_dict = retinanet.residualafterFPN.state_dict() # for s in state_dict: # if 'bn' in s : # if 'weight' in s : # print(s) # print(state_dict[s]) # elif 'bias' in s : # print(s) # print(state_dict[s]) dataset_val = PapsDataset('../data/', set_name='val_2class', transform=val_transforms) val_data_loader = DataLoader( dataset_val, batch_size=2, shuffle=False, num_workers=4, collate_fn=collate_fn ) # retinanet.load_state_dict(torch.load('../trained_models/resnet50_320_ex_bn/model.pt')) from pycocotools.cocoeval import COCOeval import json import torch retinanet.eval() start_time = time.time() threshold = 0.1 results = [] GT_results = [] image_ids = [] cnt = 0 scores_list = [] for index, data in enumerate(tqdm(val_data_loader)) : if cnt > 50 : break cnt += 1 with torch.no_grad(): images, tbox, tlabel, targets = data batch_size = len(images) # print(tbox) # print(len(tbox[0])) c, h, w = images[0].shape images = torch.cat(images).view(-1, c, h, w).to(device) outputs = retinanet(images) scores, labels, boxes = (outputs) scores = scores.cpu() labels = labels.cpu() boxes = boxes.cpu() scores_list.append(scores) if boxes.shape[0] > 0: # change to (x, y, w, h) (MS COCO standard) boxes[:, 2] -= boxes[:, 0] boxes[:, 3] -= boxes[:, 1] # print(boxes) # compute predicted labels and scores #for box, score, label in zip(boxes[0], scores[0], labels[0]): for box_id in range(boxes.shape[0]): score = float(scores[box_id]) label = int(labels[box_id]) box = boxes[box_id, :] # scores are sorted, so we can break if score < threshold: break # append detection for each positively labeled class image_result = { 'image_id' : dataset_val.image_ids[index], 'category_id' : dataset_val.label_to_coco_label(label), 'score' : float(score), 'bbox' : box.tolist(), } # append detection to results results.append(image_result) if len(tbox[0]) > 0: # compute predicted labels and scores #for box, score, label in zip(boxes[0], scores[0], labels[0]): for box_id in range(len(tbox[0])): score = float(0.99) label = (tlabel[0][box_id]) box = list(tbox[0][box_id]) box[2] -= box[0] box[3] -= box[1] # append detection for each positively labeled class image_result = { 'image_id' : dataset_val.image_ids[index], 'category_id' : dataset_val.label_to_coco_label(label), 'score' : float(score), 'bbox' : list(box), } # append detection to results GT_results.append(image_result) # append image to list of processed images image_ids.append(dataset_val.image_ids[index]) # print progress print('{}/{}'.format(index, len(dataset_val)), end='\r') if not len(results): print('No object detected') print('GT_results', len(GT_results)) print('pred_results', len(results)) # write output json.dump(results, open('../trained_models/resnet50_320_ex_bn/{}_bbox_results.json'.format(dataset_val.set_name), 'w'), indent=4) # write GT json.dump(GT_results, open('../trained_models/resnet50_320_ex_bn/{}_GTbbox_results.json'.format(dataset_val.set_name), 'w'), indent=4) print('validation time :', time.time() - start_time) # load results in COCO evaluation tool coco_true = dataset_val.coco coco_pred = coco_true.loadRes('../trained_models/resnet50_320_ex_bn/{}_bbox_results.json'.format(dataset_val.set_name)) coco_gt = coco_true.loadRes('../trained_models/resnet50_320_ex_bn/{}_GTbbox_results.json'.format(dataset_val.set_name)) # run COCO evaluation # coco_eval = COCOeval(coco_true, coco_pred, 'bbox') coco_eval = COCOeval(coco_gt, coco_pred, 'bbox') coco_eval.params.imgIds = image_ids # coco_eval.params.catIds = [0] coco_eval.evaluate() coco_eval.accumulate() coco_eval.summarize() coco_eval.params.catIds coco_eval = COCOeval(coco_gt, coco_pred, 'bbox') coco_eval.params.imgIds = image_ids coco_eval.params.catIds = [0] coco_eval.evaluate() coco_eval.accumulate() coco_eval.summarize() coco_eval = COCOeval(coco_gt, coco_pred, 'bbox') coco_eval.params.imgIds = image_ids coco_eval.params.catIds = [1] coco_eval.evaluate() coco_eval.accumulate() coco_eval.summarize() ```
github_jupyter
``` import pandas as pd import numpy as np import os from collections import Counter from tqdm import tqdm ``` # Data Analysis ``` data = pd.read_csv("test.csv",engine = 'python') data.tail() colum = data.columns for i in colum: print(f'{len(set(data[i]))} different values in the {i} column') print(f"\ntotal number of examples {len(data)}") #Host, link, Time(ET), Time(GMT),is of no use for trainig the function data = data.drop(["Host", "Link", "Date(ET)", "Time(ET)", "time(GMT)"], axis=1) colum = data.columns for i in colum: print(f'{len(set(data[i]))} different values in the {i} column') print(f"\ntotal number of examples {len(data)}") list(set(data["Source"])) # differnet values in "Source" column # repalcing FACEBOOK to Facebook data.replace(to_replace='FACEBOOK', value='Facebook',inplace=True) # Now there are only 4 different values in "Source" column Counter(data.loc[:,"Source"]) # # distribution of differnet values in "Source" column Counter(data.iloc[:,[-1]]['Patient_Tag']) # distribution of labels in the "Patien_Tag" column # It's an unbalanced data dummy = {} for i in list(set(data["Source"])): print(i,"---", Counter(data.iloc[:,[0,-1]][data['Source'] == i]['Patient_Tag'])) # distribution of labels with reference to each values in "Source" column replace_ = {} for index, i in enumerate(list(set(data["Source"])),start=1): replace_[index] = i data.replace(to_replace=i, value=index,inplace=True) data.fillna('UNK',inplace=True) list(set(data["Source"])) data.fillna('UNK',inplace=True) ``` # Vocab creation ``` import re rep_with = ['.', '?', '/', '\n', '(', ')','[', ']', '{', '}', '-','"','!', '|' ] def rep_(sent): for i in rep_with: sent = sent.replace(i,' ').replace('$', ' ').replace(',','').replace("'",'') return sent import re import num2words def n2w(text): return re.sub(r"(\d+)", lambda x: num2words.num2words(int(x.group(0))), text) def preprocess(data,pos): sent = [] for i in range(len(data)): try:sent.append(n2w(rep_(data.iloc[i,pos]))) except:print(data.iloc[i,pos]) return sent sent = preprocess(data, 2) import nltk from nltk.corpus import stopwords from nltk.tokenize import word_tokenize stop_words = set(stopwords.words('english')) sent_preprocess = [] for i in sent: sent_preprocess.append([w for w in word_tokenize(i) if not w in stop_words]) sent = sent_preprocess # sent = [i.split(' ') for i in sent] train = [[sent[i], data.loc[:,'Patient_Tag'][i]] for i in range(len(sent))] train = sorted(train, key = lambda c: len(c[0])) # sorted train using the len of x {helps in minibatching} train.pop(0) train_len = [] # len of each example for i in train: train_len.append(len(i[0])) import pickle try: with open("elmo_st.pkl", "rb") as f: print("loading embeddings") embeddings = pickle.load(f) except: print("creating embeddings ...it will take time") from allennlp.commands.elmo import ElmoEmbedder elmo = ElmoEmbedder( options_file='https://s3-us-west-2.amazonaws.com/allennlp/models/elmo/2x4096_512_2048cnn_2xhighway_5.5B/elmo_2x4096_512_2048cnn_2xhighway_5.5B_options.json', weight_file='https://s3-us-west-2.amazonaws.com/allennlp/models/elmo/2x4096_512_2048cnn_2xhighway_5.5B/elmo_2x4096_512_2048cnn_2xhighway_5.5B_weights.hdf5', cuda_device=1) #define max token length, 2187 is the max max_tokens=1024 #input sentences sentences = [] # x = [i[0] for i in train] for i in range(0,len(sent),16): sentences.append(sent[i:i+16]) #create a pretrained elmo model (requires internet connection) embeddings=[] #loop through the input sentences for k,j in enumerate(sentences): print(k) for i, elmo_embedding in enumerate(elmo.embed_sentences(j)): # Average the 3 layers returned from Elmo avg_elmo_embedding = np.average(elmo_embedding, axis=0) padding_length = max_tokens - avg_elmo_embedding.shape[0] if(padding_length>0): avg_elmo_embedding =np.append(avg_elmo_embedding, np.zeros((padding_length, avg_elmo_embedding.shape[1])), axis=0) else: avg_elmo_embedding=avg_elmo_embedding[:max_tokens] embeddings.append(avg_elmo_embedding) with open("test_elmo.pkl", "wb") as f: pickle.dump(embeddings,f) len(embeddings) ``` # Training ``` import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim device = torch.device("cuda:0") class EncoderRNN(nn.Module): def __init__(self, hidden_size, num_layers,directions,bidirectonal,out): super(EncoderRNN, self).__init__() self.hidden_size = hidden_size self.num_layers = num_layers self.directions = directions self.gru = nn.GRU(1024, hidden_size, num_layers,bidirectional=bidirectonal) self.linear1 = nn.Linear(hidden_size*directions, 32) self.linear2 = nn.Linear(32, out, bias = True) self.drop = nn.Dropout(p=0.7, inplace=False) self.sigmoid = nn.Sigmoid() def forward(self, inp, hidden): out,h = self.gru(inp,hidden) out = self.linear1(out)#.view(-1,2,out.shape[2])) out = self.linear2(self.drop(out)) return self.sigmoid(out) def init_hidden(self, batch_size): print() return torch.zeros(self.num_layers*self.directions, batch_size, self.hidden_size, dtype=torch.double) model = EncoderRNN(hidden_size=256,num_layers=1,directions=1,bidirectonal=False,out=1) model.to(device).double() y = [i[1] for i in train] import pickle with open("out.pkl", "wb") as f: pickle.dump(y,f) loss_function = nn.BCELoss() optimizer = torch.optim.Adam(model.parameters(), lr=0.01) batch = 64 for epoch in range(5): running_loss = 0 for i in range(0,len(embeddings),batch): h = model.init_hidden(len(embeddings[i:i+batch])).to(device) target = torch.tensor(y[i:i+batch],dtype=torch.double).to(device) inp = torch.tensor(embeddings[i:i+batch],dtype=torch.double).view(1830,len(embeddings[i:i+batch]),1024).to(device) out = model(inp,h) loss = loss_function(out[-1,:,:],target) nn.utils.clip_grad_norm_(model.parameters(), 50) running_loss+=loss.item() print(loss.item()) loss.backward() optimizer.step() print("loss", running_loss/len(embeddings)) ```
github_jupyter
# recreating the paper with tiny imagenet First we're going to take a stab at the most basic version of DeViSE: learning a mapping between image feature vectors and their corresponding labels' word vectors for imagenet classes. Doing this with the entirety of imagenet feels like overkill, so we'll start with tiny imagenet. ## tiny imagenet Tiny imagenet is a subset of imagenet which has been preprocessed for the stanford computer vision course CS231N. It's freely available to download and ideal for putting together quick and easy tests and proof-of-concept work in computer vision. From [their website](https://tiny-imagenet.herokuapp.com/): > Tiny Imagenet has 200 classes. Each class has 500 training images, 50 validation images, and 50 test images. Images are also resized to 64x64px, making the whole dataset small and fast to load. We'll use it to demo the DeViSE idea here. Lets load in a few of the packages we'll use in the project - plotting libraries, numpy, pandas etc, and pytorch, which we'll use to construct our deep learning models. ``` %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns sns.set_style("white") plt.rcParams["figure.figsize"] = (20, 20) import os import io import numpy as np import pandas as pd from PIL import Image from scipy.spatial.distance import cdist import torch from torch import nn, optim from torch.utils.data import Dataset, DataLoader from torchvision import models, transforms from tqdm._tqdm_notebook import tqdm_notebook as tqdm device = torch.device("cuda" if torch.cuda.is_available() else "cpu") base_path = "/mnt/efs/images/tiny-imagenet-200/" ``` # wordvectors We're going to use the [fasttext](https://fasttext.cc/docs/en/english-vectors.html) word vectors trained on [common crawl](http://commoncrawl.org) as the target word vectors throughout this work. Let's load them into memory ``` wv_path = "/mnt/efs/nlp/word_vectors/fasttext/crawl-300d-2M.vec" wv_file = io.open(wv_path, "r", encoding="utf-8", newline="\n", errors="ignore") fasttext = { line.split()[0]: np.array(line.split()[1:]).astype(np.float) for line in tqdm(list(wv_file)) } vocabulary = set(fasttext.keys()) ``` # wordnet We're also going to need to load the wordnet classes and ids from tiny-imagenet ``` clean = lambda x: x.lower().strip().replace(" ", "-").split(",-") with open(base_path + "wnids.txt") as f: wnids = np.array([id.strip() for id in f.readlines()]) wordnet = {} with open(base_path + "words.txt") as f: for line in f.readlines(): wnid, raw_words = line.split("\t") words = [word for word in clean(raw_words) if word in vocabulary] if wnid in wnids and len(words) > 0: wordnet[wnid] = words wnid_to_wordvector = { wnid: (np.array([fasttext[word] for word in words]).mean(axis=0)) for wnid, words in wordnet.items() } wnids = list(wnid_to_wordvector.keys()) ``` # example data here's an example of what we've got inside tiny-imagenet: one tiny image and its corresponding class ``` wnid = np.random.choice(wnids) image_path = base_path + "train/" + wnid + "/images/" + wnid + "_{}.JPEG" print(" ".join(wordnet[wnid])) Image.open(image_path.format(np.random.choice(500))) ``` # datasets and dataloaders Pytorch allows you to explicitly write out how batches of data are assembled and fed to a network. Especially when dealing with images, I've found it's best to use a pandas dataframe of simple paths and pointers as the base structure for assembling data. Instead of loading all of the images and corresponding word vectors into memory at once, we can just store the paths to the images with their wordnet ids. Using pandas also gives us the opportunity to do all sorts of work to the structure of the data without having to use much memory. Here's how that dataframe is put together: ``` df = {} for wnid in wnids: wnid_path = base_path + "train/" + wnid + "/images/" image_paths = [wnid_path + file_name for file_name in os.listdir(wnid_path)] for path in image_paths: df[path] = wnid df = pd.Series(df).to_frame().reset_index() df.columns = ["path", "wnid"] ``` Pandas is great for working with this kind of structured data - we can quickly shuffle the dataframe: ``` df = df.sample(frac=1).reset_index(drop=True) ``` and split it into 80:20 train:test portions. ``` split_ratio = 0.8 train_size = int(split_ratio * len(df)) train_df = df.loc[:train_size] test_df = df.loc[train_size:] ``` n.b. tiny-imagenet already has `train/`, `test/`, and `val/` directories set up which we could have used here instead. However, we're just illustrating the principle in this notebook so the data itself isn't important, and we'll use this kind of split later on when incorporating non-toy data. Now we can define how our `Dataset` object will transform the initial, simple data when it's called on to produce a batch. Images are generated by giving a path to `PIL`, and word vectors are looked up in our `wnid_to_wordvector` dictionary. Both objects are then transformed into pytorch tensors and handed over to the network. ``` class ImageDataset(Dataset): def __init__(self, dataframe, wnid_to_wordvector, transform=transforms.ToTensor()): self.image_paths = dataframe["path"].values self.wnids = dataframe["wnid"].values self.wnid_to_wordvector = wnid_to_wordvector self.transform = transform def __getitem__(self, index): image = Image.open(self.image_paths[index]).convert("RGB") if self.transform is not None: image = self.transform(image) target = torch.Tensor(wnid_to_wordvector[self.wnids[index]]) return image, target def __len__(self): return len(self.wnids) ``` We can also apply transformations to the images as they move through the pipeline (see the `if` statement above in `__getitem__()`). The torchvision package provides lots of fast, intuitive utilities for this kind of thing which can be strung together as follows. Note that we're not applying any flips or grayscale to the test dataset - the test data should generally be left as raw as possible, with distortions applied at train time to increase the generality of the network's knowledge. ``` train_transform = transforms.Compose( [ transforms.Resize(224), transforms.RandomHorizontalFlip(), transforms.RandomRotation(15), transforms.RandomGrayscale(0.25), transforms.ToTensor(), ] ) test_transform = transforms.Compose([transforms.Resize(224), transforms.ToTensor()]) ``` Now all we need to do is pass our dataframe, dictionary of word vectors, and the desired image transforms to the `ImageDataset` object to define our data pipeline for training and testing. ``` train_dataset = ImageDataset(train_df, wnid_to_wordvector, train_transform) test_dataset = ImageDataset(test_df, wnid_to_wordvector, test_transform) ``` Pytorch then requires that you pass the `Dataset` through a `DataLoader` to handle the batching etc. The `DataLoader` manages the pace and order of the work, while the `Dataset` does the work itself. The structure of these things is very predictable, and we don't have to write anything custom at this point. ``` batch_size = 128 train_loader = DataLoader( dataset=train_dataset, batch_size=batch_size, num_workers=5, shuffle=True ) test_loader = DataLoader(dataset=test_dataset, batch_size=batch_size, num_workers=5) ``` # building the model Our model uses a pre-trained backbone to extract feature vectors from the images. This biases our network to perform well on imagenet-style images and worse on others, but hey, we're searching on imagenet in this example! Later on, when working in some less imagenet-y images, we'll make some attempts to compensate for the backbone's biases. ``` backbone = models.vgg16_bn(pretrained=True).features ``` We don't want this backbone to be trainable, so we switch off the gradients for its weight and bias tensors. ``` for param in backbone.parameters(): param.requires_grad = False ``` Now we can put together the DeViSE network itself, which embeds image features into word vector space. The output of our backbone network is a $[512 \times 7 \times 7]$ tensor, which we then flatten into a 25088 dimensional vector. That vector is then fed through a few fully connected layers and ReLUs, while compressing the dimensionality down to our target size (300, to match the fasttext word vectors). ``` class DeViSE(nn.Module): def __init__(self, backbone, target_size=300): super(DeViSE, self).__init__() self.backbone = backbone self.head = nn.Sequential( nn.Linear(in_features=(25088), out_features=target_size * 2), nn.ReLU(inplace=True), nn.Dropout(), nn.Linear(in_features=target_size * 2, out_features=target_size), nn.ReLU(inplace=True), nn.Dropout(), nn.Linear(in_features=target_size, out_features=target_size), ) def forward(self, x): x = self.backbone(x) x = x.view(x.size(0), -1) x = self.head(x) x = x / x.max() return x devise_model = DeViSE(backbone, target_size=300).to(device) ``` # train loop Pytorch requires that we write our own training loops - this is rough skeleton structure that I've got used to. For each batch, the inputs and target tensors are first passed to the GPU. The inputs are then passed through the network to generate a set of predictions, which are compared to the target using some appropriate loss function. Those losses are used to inform the backpropagation of tweaks to the network's weights and biases, before repeating the whole process with a new batch. We also display the network's current loss through in the progress bar which tracks the speed and progress of the training. We can also specify the number of epochs in the parameters for the train function. ``` losses = [] flags = torch.ones(batch_size).cuda() def train(model, train_loader, loss_function, optimiser, n_epochs): for epoch in range(n_epochs): model.train() loop = tqdm(train_loader) for images, targets in loop: images = images.cuda(non_blocking=True) targets = targets.cuda(non_blocking=True) optimiser.zero_grad() predictions = model(images) loss = loss_function(predictions, targets, flags) loss.backward() optimiser.step() loop.set_description("Epoch {}/{}".format(epoch + 1, n_epochs)) loop.set_postfix(loss=loss.item()) losses.append(loss.item()) ``` Here we define the optimiser, loss function and learning rate which we'll use. ``` trainable_parameters = filter(lambda p: p.requires_grad, devise_model.parameters()) loss_function = nn.CosineEmbeddingLoss() optimiser = optim.Adam(trainable_parameters, lr=0.001) ``` Let's do some training! ``` train( model=devise_model, n_epochs=3, train_loader=train_loader, loss_function=loss_function, optimiser=optimiser, ) ``` When that's done, we can take a look at how the losses are doing. ``` loss_data = pd.Series(losses).rolling(window=15).mean() ax = loss_data.plot() ax.set_xlim( 0, ) ax.set_ylim(0, 1); ``` # evaluate on test set The loop below is very similar to the training one above, but evaluates the network's loss against the test set and stores the predictions. Obviously we're only going to loop over the dataset once here as we're not training anything. The network only has to see an image once to process it. ``` preds = [] test_loss = [] flags = torch.ones(batch_size).cuda() devise_model.eval() with torch.no_grad(): test_loop = tqdm(test_loader) for images, targets in test_loop: images = images.cuda(non_blocking=True) targets = targets.cuda(non_blocking=True) predictions = devise_model(images) loss = loss_function(predictions, targets, flags) preds.append(predictions.cpu().data.numpy()) test_loss.append(loss.item()) test_loop.set_description("Test set") test_loop.set_postfix(loss=np.mean(test_loss[-5:])) preds = np.concatenate(preds).reshape(-1, 300) np.mean(test_loss) ``` # run a search on the predictions Now we're ready to use our network to perform image searches! Each of the test set's images has been assigned a position in word vector space which the network believes is a reasonable numeric description of its features. We can use the complete fasttext dictionary to find the position of new, unseen words, and then return the nearest images to our query. ``` def search(query, n=5): image_paths = test_df["path"].values distances = cdist(fasttext[query].reshape(1, -1), preds) closest_n_paths = image_paths[np.argsort(distances)].squeeze()[:n] close_images = [ np.array(Image.open(image_path).convert("RGB")) for image_path in closest_n_paths ] return Image.fromarray(np.concatenate(close_images, axis=1)) search("bridge") ``` It works! The network has never seen the word 'bridge', has never been told what a bridge might look like, and has never seen any of the test set's images, but thanks to the combined subtlety of the word vector space which we're embedding our images in and the dexterity with which a neural network can manipulate manifolds like these, the machine has enough knowledge to make a very good guess at what a bridge might be. This has been trained on a tiny, terribly grainy set of data but it's enough to get startlingly good results.
github_jupyter
``` import pandas as pd import numpy as np from matplotlib import pyplot as plt %matplotlib inline import matplotlib matplotlib.rcParams['figure.figsize']=(20,10) df1 = pd.read_csv('Bengaluru_House_Data.csv') df1.head() df1.shape df1.groupby('area_type')['area_type'].agg('count') df2 = df1.drop(['area_type','availability','society','balcony'],axis = 'columns') df2.head() df2.isnull().sum() df3 = df2.dropna() df3.isnull().sum() df3.shape df3['size'].unique() df3['BHK'] = df3['size'].apply(lambda x : int(x.split(' ')[0])) df3.head() df3['BHK'].unique() df3[df3.BHK>20] df3.total_sqft.unique() def is_float(x): try: float(x) except: return False return True df3[~df3['total_sqft'].apply(is_float)].head() def convert_sqft_to_num(x): tokens = x.split('-') if len(tokens) == 2: return (float(tokens[0])+float(tokens[1]))/2 try: return float(x) except: return None convert_sqft_to_num('2186') convert_sqft_to_num('2100-2850') convert_sqft_to_num('34.46Sq. Meter') df4 = df3.copy() df4['total_sqft'] = df4['total_sqft'].apply(convert_sqft_to_num) df4.head() df4.loc[30] (2100+2850)/2 df4.head() df5 = df4.copy() df5['price_per_sqft'] = df5['price']*100000/df5['total_sqft'] df5.head() len(df5.location.unique()) df5.location = df5.location.apply(lambda x: x.strip()) location_stats = df5.groupby('location')['location'].agg('count').sort_values(ascending=False) location_stats len(location_stats[location_stats<=10]) location_stats_less_than_10 = location_stats[location_stats<=10] location_stats_less_than_10 len(df5.location.unique()) df5.location = df5.location.apply(lambda x: 'others' if x in location_stats_less_than_10 else x) len(df5.location.unique()) df5.head(10) df5[df5.total_sqft/df5.BHK<300].head() df5.shape df6 = df5[~(df5.total_sqft/df5.BHK<300)] df6.shape df6.price_per_sqft.describe() def remove_pps_outliers(df): df_out = pd.DataFrame() for key, subdf in df.groupby('location'): m = np.mean(subdf.price_per_sqft) st = np.std(subdf.price_per_sqft) reduced_df = subdf[(subdf.price_per_sqft>(m-st)) & (subdf.price_per_sqft<=(m+st))] df_out = pd.concat([df_out,reduced_df],ignore_index=True) return df_out df7 = remove_pps_outliers(df6) df7.shape def plot_scatter_chart(df,location): BHK2 = df[(df.location==location) & (df.BHK==2)] BHK3 = df[(df.location==location) & (df.BHK==3)] matplotlib.rcParams['figure.figsize'] = (15,10) plt.scatter(BHK2.total_sqft,BHK2.price, color = 'blue', label='2 BHK', s=50) plt.scatter(BHK3.total_sqft,BHK3.price, marker='+', color = 'green', label='3 BHK', s=50) plt.xlabel("Total Square Feet Area") plt.ylabel("Price") plt.title(location) plt.legend() plot_scatter_chart(df7,"Hebbal") def remove_bhk_outliers(df): exclude_indices = np.array([]) for location, location_df in df.groupby('location'): BHK_stats = {} for BHK, BHK_df in location_df.groupby('BHK'): BHK_stats[BHK] = { 'mean' : np.mean(BHK_df.price_per_sqft), 'std' : np.std(BHK_df.price_per_sqft), 'count' : BHK_df.shape[0] } for BHK, BHK_df in location_df.groupby('BHK'): stats = BHK_stats.get(BHK-1) if stats and stats['count']>5: exclude_indices = np.append(exclude_indices, BHK_df[BHK_df.price_per_sqft<(stats['mean'])].index.values) return df.drop(exclude_indices,axis='index') df8 = remove_bhk_outliers(df7) df8.shape plot_scatter_chart(df8,"Hebbal") import matplotlib matplotlib.rcParams["figure.figsize"] = (20,30) plt.hist(df8.price_per_sqft,rwidth =0.8) plt.xlabel("price per square feet") plt.ylabel("count") df8.bath.unique() df8[df8.bath>10] df2 = df1.drop(['area_type','society','balcony','availability'],axis='columns') df2.shape plt.hist(df8.bath,rwidth =0.8) plt.xlabel("number of bathroom") plt.ylabel("count") df8[df8.bath>df8.BHK+2] df9 = df8[df8.bath<df8.BHK+2] df9.shape df10 = df9.drop(['size','price_per_sqft'],axis='columns') df10.head() dummies = pd.get_dummies(df10.location) dummies.head(3) df11 = pd.concat([df10,dummies.drop('others',axis='columns')],axis='columns') df11.head() df12 = df11.drop('location',axis='columns') df12.head(2) df12.shape X = df12.drop('price',axis='columns') X.head() Y = df12.price Y.head() from sklearn.model_selection import train_test_split X_train, X_test,Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=10) from sklearn.linear_model import LinearRegression lr_clf = LinearRegression() lr_clf.fit(X_train, Y_train) lr_clf.score(X_test, Y_test) from sklearn.model_selection import ShuffleSplit from sklearn.model_selection import cross_val_score cv = ShuffleSplit(n_splits= 5, test_size=0.2, random_state=0) cross_val_score(LinearRegression(), X, Y, cv=cv) from sklearn.model_selection import GridSearchCV from sklearn.linear_model import Lasso from sklearn.tree import DecisionTreeRegressor def find_best_model_using_gridsearchcv(X,Y): algos = { 'linear_regression' : { 'model' : LinearRegression(), 'params' : { 'normalize' : [True, False] } }, 'lasso' :{ 'model' : Lasso(), 'params' : { 'alpha' : [1,2], 'selection' : ['random', 'cyclic'] } }, 'decision_tree' : { 'model' : DecisionTreeRegressor(), 'params' : { 'criterion' : ['mse', 'friedman_mse'], 'splitter' : ['best', 'random'] } } } scores = [] cv = ShuffleSplit(n_splits= 5, test_size=0.2, random_state=0) for algo_name, config in algos.items(): gs = GridSearchCV(config['model'], config['params'], cv=cv, return_train_score=False) gs.fit(X,Y) scores.append({ 'model' : algo_name, 'best_score' : gs.best_score_, 'best_params' : gs.best_params_ }) return pd.DataFrame(scores, columns=['model','best_score','best_params']) find_best_model_using_gridsearchcv(X,Y) def predict_price(location, sqft, bath, BHK): loc_index = np.where(X.columns==location)[0][0] x = np.zeros(len(X.columns)) x[0]=sqft x[1]=bath x[2]=BHK if loc_index >= 0: x[loc_index] =1 return lr_clf.predict([x])[0] predict_price('1st Phase JP Nagar', 1000, 2, 2) predict_price('1st Phase JP Nagar', 1000, 3, 3) predict_price('Indira Nagar', 1000, 2, 2) predict_price('Indira Nagar', 1000, 3, 3) import pickle with open('banglore_home_prices_model.pickle','wb') as f: pickle.dump(lr_clf,f) import json columns = { 'data_columns' : [col.lower() for col in X.columns] } with open('columns.json','w') as f: f.write(json.dumps(columns)) ```
github_jupyter
# Machine Learning and Statistics for Physicists Material for a [UC Irvine](https://uci.edu/) course offered by the [Department of Physics and Astronomy](https://www.physics.uci.edu/). Content is maintained on [github](github.com/dkirkby/MachineLearningStatistics) and distributed under a [BSD3 license](https://opensource.org/licenses/BSD-3-Clause). [Table of contents](Contents.ipynb) ``` %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns; sns.set() import numpy as np import pandas as pd from sklearn import mixture ``` ## Probability Theory Probability theory is a mathematical language for reasoning about uncertain outcomes. Possible sources of uncertainty include: - Inherent randomness in a physical process, e.g., arising from [quantum phenomena](http://algassert.com/quirk#circuit={"cols":[]}) or a noisy measurement process. - Incomplete information, e.g., due to a measurement that only observes the partial state of a system or a model that only represents partial state. Also, we sometimes chose to make an uncertain statement for convenience. For example, the statement **traveling faster than the speed of light is impossible** needs some unwieldy qualifiers to avoid any uncertainty, so it is convenient to instead state that **traveling faster than the speed of light is impossible under most circumstances**. Probability theory enables us to build quantitative models that describe our data, both seen and not yet seen, so plays an important role in machine learning. A precise formulation is very technical since it must deal with edge cases that we never encounter in practical work. We will skip over most of the technical details here while still introducing the main concepts that are useful to understand the foundations of machine learning. ### Axioms of Probability There are different (equally valid) approaches to formulating a theory of probability. Here we follow the approach of Kolmogorov based on set theory, which has three ingredients: 1. A **sample space** $\Omega$ that defines the set of all possible uncertain outcomes. 2. An **event space** $\cal F$ of combinations of outcomes (subsets of $\Omega$). 3. A **probability measure** $P: {\cal F}\rightarrow [0,1]$ that assigns numerical probabilities to each event. The tuple $(\Omega, {\cal F}, P)$ is a **probability space**. For a concrete example, consider an electron with the following **probability space**: 1. We are interested in a single electron that we can only observe via its spin. Therefore the **sample space** consists of its two possible spins: $\uparrow$ and $\downarrow$. 2. Our **event space** consists of all subsets of the sample space: { }, {$\uparrow$}, {$\downarrow$}, {$\uparrow, \downarrow$}. 3. Our **probability measure** assigns the probabilities: $P(\{\,\}) = 0$, $P(\{\uparrow\}) = P(\{\downarrow\}) = 0.5$, $P(\{\uparrow, \downarrow\}) = 1$. A probability space defines an uncertain process that you can think of as a black box that generate outcomes $\omega_1, \omega_2, \ldots \in \Omega$. After each outcome $\omega_i$, all events containing $\omega_i$ are said to have **occurred** (so, in general, multiple events occur simultaneously). Events $A, B, \ldots$ occur with probabilities $P(A), P(B), \ldots$, so the probability measure $P$ encodes the dynamics of the uncertain process. Recall the basic operations of set theory that we will use frequently below. The box represents the set of all possible outcomes, $\Omega$, with individual outcomes $\omega$ indicated with dots. The labels show some possible subsets within the event space, constructed using the union ($\cup$), intersection ($\cap$) and complement ($\setminus$) operations (in logic, union and and intersection are called OR and AND): ![Set Theory Operations](img/Probability/SetOperations.png) The choice of **sample space** is completely up to you and defines the "universe" you are considering. In the example, we decided to ignore the electron's position and momentum. Should the sample space for a coin toss include the possibility of the coin landing on its edge? It is up to you. The choice of **event space** is more constrained since it must satisfy the following conditions: - **R1:** If event $A$ is included, then so is its complement $\Omega \setminus A$. Therefore an event space containing {$\uparrow$} must also contain {$\downarrow$}. - **R2:** If events $A_1$ and $A_2$ are included, then so is their union $A_1 \cup A_2$. Therefore an event space containing {$\uparrow$} and {$\downarrow$} must also contain {{$\uparrow$,$\downarrow$}}. If you start with the events you care about and then repeatedly apply the rules above, you will automatically satisfy the additional conditions that: - The "everything" event $A = \Omega$ is included (as the union of all other subset events). - The "nothing" event $A =$ {} is included (as the complement of the "everything" event). The set of all possible subsets of $\Omega$ is always a valid event space, but other (simpler) choices are possible when you don't care about some subsets (or don't know how to assign probabilities to them). **EXERCISE:** Use the rules above to create the smallest possible event space containing {a} for a sample space consisting of the four possible outcomes {a,b,c,d}. One way to apply the rules is: - R1: {a} => {b,c,d} - R2: {a}, {b,c,d} => {a,b,c,d} - R1: {a,b,c,d} => {} The complete event space is then: {}, {a}, {b,c,d}, {a,b,c,d}. **EXERCISE:** Use the rules above to create the smallest possible event space containing {a} and {b} for the same sample space. One way to apply the rules is: - R1: {a} => {b,c,d} - R1: {b} => {a,c,d} - R2: {a}, {b} => {a,b} - R1: {a,b} => {c,d} - R2: {a,b}, {c,d} => {a,b,c,d} - R1: {a,b,c,d} => {} The complete event space is then: {}, {a}, {b}, {a,b}, {c,d}, {b,c,d}, {a,c,d}, {a,b,c,d}. Note that both of these examples allow us to reason about the probabilities of some outcomes without ever needing specify the probabilities of other outcomes. That's why we need the second Kolmogorov axiom. Once you have specified your sample and event spaces, you are ready to assign probabilities to each event. This where you make quantitative statements that define how your probability universe works. In the example above we set $P(\{\uparrow\}) = P(\{\downarrow\}) = 0.5$, but you could equally well define an alternate reality where $P(\{\uparrow\}) = 0.2$ and $P(\{\downarrow\}) = 0.8$. The Kolmogorov axioms are that: - For any event $A$, $P(A) \ge 0$. - $P(\Omega) = 1$ ("everything" event). - If events $A_1, A_2, \ldots$ have no outcomes in common (i.e., they are *disjoint* $A_i \cap A_j = \{\}$), then: $$ P(A_1 \cup A_2 \cup \ldots) = P(A_1) + P(A_2) + \ldots \; . $$ **DISCUSS:** How might you formulate a probability space for an electron whose spin is time dependent, e.g., because it is in an energy eigenstate that mixes the two spin states. We first need to define all possible outcomes. Since outcomes are the results of measurements, we need to specify when measurements are performed and whether multiple measurements might be performed on the same electron. Suppose measurements are always made at a fixed $t_1$ and $t_2 > t_1$, then there are four possible outcomes: (u,u), (u,d), (d,u), (d,d). Next, build an event space containing the outcomes you care about (as in the exercises above). Finally, assign each event's probability using quantum mechanics. This construction could be easily generalized to more measurements at predetermined times, but if measurements are allowed at arbitrary times we need a different approach. In the most general case, the possible measurements are specified by a sequence of $M$ increasing times $0 \le t_1 \le t_2 \le \ldots \le t_M$, where $M = 1, 2, 3, \ldots$. This leads to an infinite (but enumerable) set of resulting possible outcomes. However, we could still chose a relatively simple event space, for example: - a: nothing event - b: at least one measurement before $t = 1\,\mu$s - c: no measurements before $t = 1\,\mu$s - d: everything event. The three axioms above are sufficient to derive many useful properties of a probability measure $P$, including: 1. $P(A) + P(\Omega\setminus A) = 1$ 2. $A\subseteq B \implies P(A) \le P(B)$ 3. $P(A\cap B) \le \min(P(A), P(B))$ 4. $P(A\cup B) = P(A) + P(B) - P(A\cap B)$ These all make sense when translated into corresponding Venn diagrams (try it, to convince yourself). The last property is useful for replacing the probability of **A or B** with the probability of **A and B** in an expression (or vice versa). We have already seen one special case of the third property above: $$ A, B\, \text{disjoint}\,\Rightarrow P(A\cap B) = 0 \; . $$ Another important special case is: $$ P(A\cap B) = P(A) P(B) \; . $$ In this case, we say the events $A$ and $B$ are **independent**. This is the formal definition of **independence** that was missing when we [earlier described](Dimensionality.ipynb) the *Independent Component Analysis (ICA)* method of linear decomposition. In the following we will introduce several new concepts related to probability, but keep in mind that probability is only defined on subsets of outcomes (events), so any new concept must translate to a statement about events. ### Conditional Probability and Bayes' Rule The probability of event $A$ **given that $B$ has occurred**, written $P(A\mid B)$, is a central concept in machine learning but does not appear above. Since $P$ is only defined for events, and $A\mid B$ is not an event, the notation does not even make sense! Instead, it is shorthand for this ratio of valid probabilities: $$ \boxed{ P(A\mid B) \equiv \frac{P(A\cap B)}{P(B)} \;. } $$ This definition requires that $P(B) > 0$, which is not true for all events $B$, but then necessarily has a value between zero and one (draw a Venn diagram to convince yourself), so makes sense to describe as a **probability**. Note that we are introducing conditional probability as a *definition*, not a result of some calculation, but there are other ways to formulate probability theory in which $P(A\mid B)$ is included in the initial axioms. A conditional probability effectively shrinks the sample space $\Omega$ to the outcomes in $B$, resulting in a new probability space with renormalized probabilities. **EXERCISE:** Study this [visualization](http://students.brown.edu/seeing-theory/compound-probability/index.html#section3) of conditional probability. 1. What is the full sample space of outcomes $\Omega$? 2. Explain how the horizontal bars represent events. Are they are complete event space? 3. Explain how the histogram values represent event probabilities or conditional probabilities. Answers: 1. The full sample space consists of all possible horizontal positions for a single ball. (We could also define a multi-ball sample space, but that's not what this visualization is intended for). 2. Each horizontal bar represents a set of outcomes where the horizontal position lies in some interval. The three events shown are not a complete event space since, for example, they are missing the "nothing" and "everything" events. 3. With the "Universe" button selected, the histogram shows event probabilities. With any other button select, the histogram shows conditional probabilities. When $A$ and $B$ are independent events, the conditional probability ratio simplifies to: $$ A, B\,\text{independent}\implies P(A\mid B) = P(A) \; . $$ If we compare $P(A\mid B)$ and $P(B\mid A)$ we find that: $$ \boxed{ P(A\mid B) = P(B\mid A) \frac{P(A)}{P(B)}\; ,} $$ so $P(A\mid B) \ll P(B\mid A)$ when $P(A) \ll P(B)$. However, there is a [natural tendency](https://en.wikipedia.org/wiki/Confusion_of_the_inverse) to assume that $P(A\mid B) \simeq P(B\mid A)$ in informal reasoning, so be careful! This relationship between $P(A\mid B)$ and $P(B\mid A)$ is known as **Bayes' rule**. Although there is some controversy and debate surrounding *Bayesian statistics*, Bayes' rule follows directly from the definition of conditional probability and is firmly established. (The Bayesian controversy, which we will discuss later, is over what constitutes a valid $A$ or $B$). ### Random Variables A probability space connects sets of possible outcomes with numerical probabilities, but we also need a way to characterize the outcomes themselves numerically. **Random variables** fill this gap. A random variable $X: \Omega\rightarrow\mathbb{R}$ labels each possible outcome $\omega\in\Omega$ with a real number $x = X(\omega)$. The probability $P(x)$ of a specific random variable value $x$ is then *defined* to be: $$ \boxed{ P(X=x) \equiv P\left(\{ \omega: X(\omega) = x \}\right) \; . } $$ We often write $P(x)$ as shorthand for $P(X=x)$. Note that, as with $P(A|B)$ earlier, this is a *definition*, not a result, which translates a new notation into a probability assigned to an event. *Technical points:* - *We are assuming that $X$ varies continuously, since that is the most common case in scientific data. Random variables can also be discrete, leading to a set of parallel definitions but with some different notation.* - *$P$ is only defined for events, but what if the set $\{ \omega: X(\omega) = x \}$ is not in the event space? There are some restrictions on $X(\omega)$ that prevent this happening.* **DISCUSS:** Try this [visual demonstration](http://students.brown.edu/seeing-theory/probability-distributions/index.html#section1) of how a random variable is simply an arbitrary labeling of possible outcomes: - Are the numerical values on the histogram's horizontal axis supplied by $X$ or $P$? - Are the numerical values on the histogram's vertical axis supplied by $X$ or $P$? - Is $X(\omega)$ invertible? Answers: - The random variable $X$ provides the horizontal numerical values. - The probability measure $P$ provides the vertical numerical values. - The function $X(\omega)$ is not invertible, which is not a problem. We can generalize the equality condition above, $X(\omega) = x$, to any well-defined condition, for example: $$ P(a\le X \le b) \equiv P\left(\{ \omega: a \le X(\omega) \le b \}\right) \; . $$ The result will always be in the interval $[0,1]$ because it reduces to the probability assigned to some event. One particularly useful condition yields the **cumulative distribution function (CDF)**: $$ F_X(x) \equiv P\left(\{ \omega: X(\omega) \le x\} \right) \; . $$ The CDF always rises monotonically from 0 to 1 and is always well defined. When the CDF is differentiable everywhere, we can also calculate the **probability density function (PDF)**: $$ f_X(x) \equiv \frac{d}{dx} F_X(x) \; . $$ Note that, while CDF is a true probability and always in $[0,1]$, this is not true of the PDF, for which we can only say that PDF $\ge 0$. Also, the PDF will, in general, have dimensions introduced by the derivative. A PDF is a *density* in the sense that: $$ \boxed{ P\left(\{\omega: x \le X \le x + \Delta x\}\right) \simeq f_X(x)\, \Delta x} $$ with $f_X(x) \Delta x$ in $[0,1]$ since the LHS is the probability of a single event. (We will use this result several times below.) We can recover the CDF from a PDF with integration, $$ F_X(x) = \int_{-\infty}^x\, f_X(x') dx' \; , $$ or, in equivalent set theory notation, $$ \begin{aligned} F_X(x) &= \lim_{\Delta x\rightarrow 0}\, \sum_i f_X(x_i)\,\Delta x \\ &= \lim_{\Delta x\rightarrow 0}\, \sum_i P\left( \{\omega: x_i \le X(\omega) \le x_i + \Delta x\} \right) \\ &= \lim_{\Delta x\rightarrow 0}\, P\left( \cup_i \{\omega: x_i \le X(\omega) \le x_i + \Delta x\} \right) \; . \end{aligned} $$ where the last line uses the fact that the sets $\{\omega: x_i \le X(\omega) \le x_i + \Delta x\}$ are all disjoint and combine to cover the full sample space $\Omega$. Random variables are conventionally denoted with capital letters near the end of the alphabet. We have already used $X$ and $Y$ to denote arrays of data samples or latent variables, but that was no accident. Think of a dataset $X$ as a sequence of random outcomes $\omega_i$ in the "universe" mapped via a random variable $X_j(\omega)$ for each feature. The elements $X_{ij}$ of the dataset are then just $X_j(\omega_i)$. Similarly, when you perform dimensionality reduction $X\rightarrow Y$, you are effectively adopting new random variables $Y_j(\omega_i)$. ### Joint, Marginal and Conditional Probability Density When data is described by multiple random variables (features), $x_0, x_1, \ldots$, it has a **joint CDF**: $$ F_{X_0,X_1,\ldots}(x_0, x_1, \ldots) \equiv P\left( \{\omega: X_0(\omega) \le x_0\} \cap \{\omega: X_1(\omega) \le x_1\} \cap \ldots \right) \; . $$ Note how each random variable translates to a set of outcomes in the same underlying sample space $\Omega$, whose intersection specifies a single event from ${\cal F}$. In the following, we will restrict to the 2D case $F(x,y)$ and drop the subscript on $F$, to simplify the notation, but you can replace $x = x_0$ and $y = x_1, x_2, \ldots$ throughout. The **joint PDF** corresponding to a joint CDF is: $$ f(x, y) \equiv \frac{\partial}{\partial x}\frac{\partial}{\partial y}\, F(x, y) \; . $$ The total integral of the joint PDF is one, $$ 1 = \int dx dy \ldots f(x, y) \; , $$ but we can also integrate out a single random variable, yielding a **marginal PDF**, e.g. $$ f(x) = \int dy\, f(x, y) \; . $$ The set theory "proof" of this result is: $$ \begin{aligned} \int dy\, f(x, y) &= \lim_{\Delta y\rightarrow 0}\, \sum_i\, f(x, y_i)\,\Delta y \\ &= \lim_{\Delta y\rightarrow 0}\, \sum_i \frac{\partial}{\partial x} P\left( \{ \omega: X(x) \le x\} \cap \{ \omega: y_i \le Y(y) \le y_i + \Delta y\}\right)\\ &= \lim_{\Delta y\rightarrow 0}\, \frac{\partial}{\partial x} P\left( \bigcup_i \{ \omega: X(x) \le x\} \cap \{ \omega: y_i \le Y(y) \le y_i + \Delta y\}\right)\\ &= \frac{\partial}{\partial x} P\left(\{ \omega: X(x) \le x\} \right) \\ &= f(x) \; , \end{aligned} $$ where the fourth line follows from the third Kolmogorov axiom, since the sets $\{ \omega: y_i \le Y(y) \le y_i + \Delta y\}$ are all disjoint and combine to cover the full sample space $\Omega$. In other words, **marginalizing out** a random variable yields exactly the same joint probability we would have obtained if we had never introduced it in the first place. Finally, a **conditional PDF** is defined in terms of the following conditional probability: $$ f(x\mid y) \equiv \frac{\partial}{\partial x} \lim_{\Delta y\rightarrow 0} P\left( \{\omega: X(\omega) \le x\} \mid \{\omega: y \le Y(\omega) \le y + \Delta y\}\right) \; . $$ Using the definition of **conditional probability** above, we find: $$ \begin{aligned} f(x\mid y) &= \lim_{\Delta y\rightarrow 0}\, \frac{\partial}{\partial x} \frac{P\left( \{\omega: X(\omega) \le x\} \cap \{\omega: y \le Y(\omega) \le y + \Delta y\}\right)} {P\left( \{\omega: y \le Y(\omega) \le y + \Delta y\}\right)} \\ &= \lim_{\Delta y\rightarrow 0}\, \frac{\partial}{\partial x} \frac{\frac{\partial}{\partial y} P\left( \{\omega: X(\omega) \le x\} \cap \{\omega: Y(\omega) \le y\} \right) \Delta y} {\frac{\partial}{\partial y} P\left( \{\omega: Y(\omega) \le y\}\right) \Delta y} \\ &= \frac{\frac{\partial}{\partial x} \frac{\partial}{\partial y} P\left( \{\omega: X(\omega) \le x\} \cap \{\omega: Y(\omega) \le y\} \right)} {\frac{\partial}{\partial y} P\left( \{\omega: Y(\omega) \le y\}\right)} \\ &=\frac{f(x, y)}{f(y)} \; . \end{aligned} $$ Rewritten in a slightly different form, this is also known as the "chain rule" of probability: $$ f(x,y) = f(x\mid y)\, f(y) \; . $$ Comparing $f(x\mid y)$ with $f(y\mid x)$ we derive the random-variable version of Bayes' rule, $$ \boxed{ f(x\mid y) = \frac{f(y\mid x)\,f(x)}{f(y)} = \frac{f(y\mid x)\,f(x)}{\int dx\, f(x,y)} \; ,} $$ where we have written out the conditional PDF $f(y)$ as an integral in the last expression. **SUMMARY:** - Commas signal a **joint** probability formed by set intersections (logical *AND*). - Missing random variables signal a **marginal** probability with the missing variables "integrated out". - A vertical bar $(\mid)$ signals a **conditional** probability with variables on the RHS fixed. As always, a picture is worth a thousand words: ``` def prob2d(XY, lim=(-2.5,+2.5), n=100): grid = np.linspace(*lim, n) xy = np.stack(np.meshgrid(grid, grid)).reshape(2, -1).T data = pd.DataFrame(XY, columns=['x', 'y']) fitxy = mixture.GaussianMixture(n_components=1).fit(data) fitx = mixture.GaussianMixture(n_components=1).fit(data.drop(columns='y')) fity = mixture.GaussianMixture(n_components=1).fit(data.drop(columns='x')) pdfxy = np.exp(fitxy.score_samples(xy)).reshape(n, n) pdfx = np.exp(fitx.score_samples(grid.reshape(-1, 1))).reshape(-1) pdfy = np.exp(fity.score_samples(grid.reshape(-1, 1))).reshape(-1) xmarg = pdfxy[:, n // 3].copy() xmarg /= np.trapz(xmarg, grid) ymarg = pdfxy[n // 2, :].copy() ymarg /= np.trapz(ymarg, grid) g = sns.JointGrid('x', 'y', data, ratio=2, xlim=lim, ylim=lim, size=8) g.ax_joint.imshow(pdfxy, extent=lim+lim, origin='lower', interpolation='none') g.ax_joint.text(-1.6, 1.4, 'A', color='w', fontsize=18) g.ax_marg_x.plot(grid, pdfx, label='B') g.ax_marg_x.plot(grid, ymarg, 'r--', label='C') g.ax_marg_x.legend(fontsize='x-large') g.ax_marg_y.plot(pdfy, grid, label='D') g.ax_marg_y.plot(xmarg, grid, 'r--', label='E') g.ax_marg_y.legend(fontsize='x-large') gen = np.random.RandomState(seed=123) prob2d(gen.multivariate_normal([0,0], [[2,1],[1,1]], size=5000)) ``` **EXERCISE:** The plot above shows probability densities in $x$ and $y$. - Write down the appropriate joint / marginal / conditional expressions for A-E. - How is each quantity A-E normalized? Answer: - A is the joint PDF $f(x,y)$, normalized in 2D over $(x,y)$. - B is the marginal PDF $f(x)$, normalized in 1D over $x$. - C is the conditional PDF $f(x|y)$ with $y \simeq -0.7$, normalized in 1D over $x$. - D is the marginal PDF $f(y)$, normalized in 1D over $y$. - E is the conditional PDF $f(y|x)$ with $x \simeq 0.0$, , normalized in 1D over $y$. We say that random variables $X$ and $Y$ are **independent** if $$ F(x, y) = F(x) F(y) \; , $$ which leads to $$ f(x, y) = f(x) f(y) $$ and $$ f(x\mid y) = f(x) \quad , \quad f(y\mid x) = f(y) \; . $$ The corresponding picture is: ``` gen = np.random.RandomState(seed=123) prob2d(gen.multivariate_normal([0,0], [[1,0],[0,0.4]], size=5000)) ``` ### Practical Probability Calculus It is often useful to use probability densities that are hybrids of the fully joint / marginal / conditional cases, such as $f(x\mid y, z)$ and $f(x, y\mid z)$, but these do not require any new formalism. In the following, we adopt a slightly more abstract notation with the following conventions: - $P(\ldots)$ is a generic probability (density). - $A_i$ and $B_j$ are generic random variables or, more generically, logical propositions about outcomes. - $D$ represents generic data features. - $\Theta$ represents generic model parameters. - $M$ represents generic model hyperparameters. A practical calculus for such expressions boils down to the following transformation rules: **Rule-1**: the order of arguments on either side of $\mid$ is not significant: $$ P(A_1, A_2, \ldots\mid B_1, B_2\ldots) = P(A_2, A_1, \ldots\mid B_1, B_2\ldots) = P(A_1, A_2, \ldots\mid B_2, B_1\ldots) = \ldots $$ **Rule-2**: use the definition of conditional probability to move a variable from the LHS to the RHS: $$ P(A_2,\ldots\mid A_1,B_1,B_2,\ldots) = \frac{P(A_1,A_2,\ldots\mid B_1,B_2\ldots)}{P(A_1\mid B_1,B_2\ldots)} \; . $$ **Rule-3**: use the chain rule to move a variable from the RHS to the LHS (really just a restatement of Rule-2): $$ P(B_1,A_1,A_2,\ldots\mid B_2,\ldots) = P(A_1,A_2,\ldots\mid B_1,B_2,\ldots)\,P(B_1\mid B_2,\ldots) \; . $$ **Rule-4**: use a marginalization integral to remove a variable from the LHS: $$ P(A_2,\ldots\mid B_1,B_2,\ldots) = \int d A_1'\, P(A_1', A_2, \ldots\mid B_1, B_2\ldots) \; . $$ **Rule-5**: combine Rule-3 and Rule-4 to remove a variable from the RHS: $$ P(A_1,A_2,\ldots\mid B_2,\ldots) = \int d B_1'\, P(A_1,A_2,\ldots\mid B_1',B_2,\ldots)\,P(B_1'\mid B_2,\ldots) \; . $$ **EXERCISE:** Use these rules to show that: $$ P(\Theta_M \mid D,M) = \frac{P(D\mid\Theta_M ,M)\, P(\Theta_M,M)}{P(D,M)} \; . $$ We will use this result later when we discuss Bayesian inference. Apply the rules to the LHS in order to make it look more like the RHS: $$ \begin{aligned} P(\Theta_M \mid D,M) &= \frac{P(D,\Theta_M\mid M)}{P(D\mid M)} & \text{Rule-2} \\ &= \frac{P(D\mid\Theta_M,M)\,P(\Theta_M|M)}{P(D\mid M)} & \text{Rule-3} \\ &= \frac{P(D\mid\Theta_M,M)\left[ P(\Theta_M,M) / P(M)\right]}{\left[ P(D,M) / P(M)\right]} & \text{Rule-3} \\ &= \frac{P(D\mid\Theta_M,M)\, P(\Theta_M,M)}{P(D,M)} & \text{simplify} \end{aligned} $$
github_jupyter
# CS375 - Assignment 2: Shallow bottleneck and sparse shallow bottleneck In this notebook I implemented the shallow bottleneck and sparse variants and trained them on CIFAR-10. I also trained a shallow bottleneck on the imagenet dataset with poor overall results but much better categorization compared to the models trained on CIFAR. ## ImageNet training and testing ``` %matplotlib inline import os import numpy as np import tensorflow as tf import pymongo as pm import gridfs import cPickle import scipy.signal as signal import matplotlib.pyplot as plt from tqdm import tqdm_notebook, trange from dldata.metrics.utils import compute_metric_base ``` ### Getting data from the database Let's connect to the database and pull the data training and test data that is stored while training our network. In order to find the right experiment id, it is useful to display which experiments are stored in the database first. ``` # connect to database dbname = 'final' collname = 'yolo' exp_id = 'imagenet' exp_idc = 'combined_2' exp_idn = 'combined_nosize' port = 24444 conn = pm.MongoClient(port = port) coll = conn[dbname][collname + '.files'] # print out saved experiments in collection coll print(coll.distinct('exp_id')) #coll.delete_many({'exp_id':exp_idn}) ``` This shows us all stored experiments. In case you want to delete a particular experiment because you are running out of disk space, you can uncomment and use the following line. You could also just drop the entire collection or even the entire database if you want to get of all of them, but I recommend removing them one by one. ### Plotting the training curve Now we are interested to see the training curve for exp_id='experiment_1' for example. So the first thing we have to do is to pull the training loss from the database and then we can plot it. I implemented a function that will pull and return the training loss per iteration for you. Your first task is to take the training loss and plot 1.) the training loss and 2.) a smoothed version of the training loss which you can effectively get by convolving the loss with a vector of ones kernel. You might find the function 'scipy.signal.convolve' useful to solve this task. Experiment with various kernel lengths and describe what you see. ``` from scipy.signal import convolve def smooth_signal(lst, smooth=5): return convolve(lst, np.ones((smooth))/smooth, 'valid') def get_losses(coll, exp_id): """ Gets all loss entries from the database and concatenates them into a vector """ q_train = {'exp_id' : exp_id, 'train_results' : {'$exists' : True}} return np.array([_r['loss'] for r in coll.find(q_train, projection = ['train_results']) for _r in r['train_results']]) loss = get_losses(coll, exp_id) lossc = get_losses(coll, exp_idc) lossn = get_losses(coll, exp_idn) # Plot the training loss plt.figure() plt.title('Imagenet loss') plt.plot(loss[0:150000]) plt.figure() plt.title('Combined loss') plt.plot(smooth_signal(lossc,smooth=100)) plt.ylim((0, 40)) plt.figure() plt.title('Combined: nosize loss') plt.plot(smooth_signal(lossn,smooth=100)) plt.ylim((0,30)) ``` We found that all three models were able to be trained on CIFAR-10 and we were also able to train a model on imagenet. Loss functions bottomed out very suddenly with very few epochs. ### Plotting the validation results After our train_imagenet function has evaluated the Image Net validation set for the time we can have a look at the validation results of for example exp_id='experiment_1'. Again, you need to pull the validation data from the database first. The validation data consists of the top1 and top5 accuracy that you have implemented previously. We have provided a function that pulls the necessary data from the database. Your task is to plot the validation curve of the top1 and top5 accuracy. Label the graphs respectively and describe what you see. ``` def get_validation_data(coll, exp_id): """ Gets the validation data from the database (except for gridfs data) """ q_val = {'exp_id' : exp_id, 'validation_results' : {'$exists' : True}, 'validates' : {'$exists' : False}} val_steps = coll.find(q_val, projection = ['validation_results', 'step']) top1 = [val_steps[i]['validation_results']['topn_val']['top1'] for i in range(val_steps.count())] top5 = [val_steps[i]['validation_results']['topn_val']['top5'] for i in range(val_steps.count())] steps = [val_steps[i]['step'] for i in range(val_steps.count())] return top1, top5, steps top1, top5, steps = get_validation_data(coll, exp_id) #top1c, top5c, stepsc = get_validation_data(coll, exp_idc) ### PLOT VALIDATION RESULTS HERE plt.plot(steps, top1, label='top1') #plt.plot(steps, top1, label='top1c') plt.plot(steps, top5, label='top5') #plt.plot(steps, top1, label='top5c') plt.legend() top5c ``` ## Neural analysis Now let's move on to fetching and displaying the computations and tests that you ran in the neural_analysis agg_func. We will first pull the data which was stored in the validation results in the database. Therefore, we call the function 'get_neural_validation_data'. The returned 'validation_data' is a list of dictionaries that contain your validation results. It's keys contain amongst others the 'exp_id' of your experiment, the evaluated 'step', and the actual 'validation_results'. In part 2 of this assignment, you should have evaluated your model at different iteration steps. In the following, your task will be to plot your evaluations at different iteration steps. Therefore, index the data list with the appropriate indices, plot the results and mark all of the following plots with the iteration step. ``` def get_neural_validation_data(coll,exp_id): q_val = {'exp_id' : exp_id, 'validation_results' : {'$exists' : True}, 'validates': {'$exists' : True}} val_steps = coll.find(q_val, projection = ['validation_results', 'validates', 'exp_id']) results = [val_steps[i] for i in range(val_steps.count())] for res in results: res['step'] = coll.find({'_id': res['validates']})[0]['step'] return results vd = get_neural_validation_data(coll,exp_id=exp_id) vdc = get_neural_validation_data(coll,exp_id=exp_idc) print('data keys:') print(vd[1]['validation_results'].keys()) print(vdc[0]['validation_results'].keys()) """ You will need to EDIT this part. Please subselect 'validation_data' with 'idx' to pick the data entry for your desired iteration step. 1.) Assign data = 'validation_data[idx]['validation_results']['valid0']' and step = validation_data[idx]['step'] 2.) Choose the target_layers you want to evaluate on. """ target_layers = ['conv_1','conv_2','conv_3','conv_4','conv_5','conv_6','conv_7','conv_8','conv_9','fc1', 'fc2'] idx = 1 ### YOUR idx HERE data_all = vd[idx]['validation_results']['VAll'] data_6 = vd[idx]['validation_results']['V6'] step = vd[idx]['step'] idxc = 0 data_allc = vdc[idxc]['validation_results']['VAll'] data_6c = vdc[idxc]['validation_results']['V6'] stepc = vdc[idxc]['step'] ``` ### Analyzing the regression results We will now display the results of the regression test. Please print (1 - data['it\_regression_"insert_target_layer_here"']['noise_corrected_multi_rsquared_loss']) for each layer and step and label the print out with the layer name and step. Describe what you observe. ``` def plot_regression_results(data, target_layers, step): """ Prints out the noise corrected multi rsquared loss for each layer. You will need to EDIT this function. """ perf = [] for layer in target_layers: k = 'it_regression_%s' % layer regression_results = data[k] ### YOUR CODE HERE performance = 1-regression_results['noise_corrected_multi_rsquared_loss'] perf.append(performance) #print('layer: %s, step: %s, performance: %.2f' % (layer, step, performance)) ### END OF YOUR CODE return(perf) print('********** V 6 *********************') p6 = plot_regression_results(data_6, target_layers, step) pall = plot_regression_results(data_all, target_layers, step) p6c = plot_regression_results(data_6c, target_layers, stepc) pallc = plot_regression_results(data_allc, target_layers, stepc) plt.figure() plt.plot(p6) plt.plot(p6c) plt.xticks(np.arange(11),('c1','c2','c3','c4','c5','c6','c7','c8','c9','fc1','fc2')) plt.figure() plt.plot(pall) plt.plot(pallc) plt.xticks(np.arange(11),('c1','c2','c3','c4','c5','c6','c7','c8','c9','fc1','fc2')) ``` The autoencoder wasn't able to successfully do regression in any case. ``` def plot_imagenet_results(data, target_layers, step): """ Plots the confusion matrix and the average classification accuracy for each layer. You will need to EDIT this section. """ for i, layer in enumerate(target_layers): k = 'imagenet_%s' % layer categorization_results = data[k]['result_summary'] ### YOUR CODE HERE labels = categorization_results['labelset'] acc = 2*(np.mean(categorization_results['accbal'])-0.5) print('{name}: avg_accuracy: {acc:.5f}; step: {step}'.format( name=layer, acc=acc, step=step, )) ```
github_jupyter
## Instrucciones generales 1. Forme un grupo de **máximo tres estudiantes** 1. Versione su trabajo usando un **repositorio <font color="red">privado</font> de github**. Agregue a sus compañeros y a su profesor (usuario github: phuijse) en la pestaña *Settings/Manage access*. No se aceptarán consultas si la tarea no está en github. No se evaluarán tareas que no estén en github. 1. Se evaluará el **resultado, la profundidad de su análisis y la calidad/orden de sus códigos** en base al último commit antes de la fecha y hora de entrega". Se bonificará a quienes muestren un método de trabajo incremental y ordenado según el histórico de *commits* 1. Sean honestos, ríganse por el [código de ética de la ACM](https://www.acm.org/about-acm/code-of-ethics-in-spanish) # Mi primera Red Neuronal Bayesiana Las redes neuronales son modelos del estado del arte para hacer regresión y clasificación con datos complejos Generalmente estos modelos requieren de una gran cantidad de datos para poder entrenarlos de forma efectiva y sin que se sobreajusten. Sin embargo, en algunos problemas los datos disponibles son simplemente muy escasos o muy difíciles de obtener. Adicionalmente, no es directo tomar decisiones en base al modelo, y se requiere un paso adicional de calibración. ¿Cómo podemos confiar en las decisiones del modelo? Podemos intentar solucionar estos problemas escribiendo la red neuronal como un modelo bayesiano y aprender el posterior de sus parámetros con un método de Markov Chain Monte Carlo (siempre y cuando el modelo sea simple). Incorporando priors el modelo estará regularizado y en lugar de estimadores puntuales tendremos la distribución a posteriori completa. Esta rica información extra nos permite medir la confianza del modelo sobre sus predicciones (el modelo sabe cuando no sabe) facilitando la tarea de calibración. ## Formulación clásica En esta tarea se pide que programen un modelo de red neuronal para clasificación de datos bidimensionales, de dos clases, con una capa oculta y con función de activación sigmoidal Sea el conjunto de datos y etiquetas $$ \mathcal{D} = \{(x, y)^{(i)}, i=1,2,\ldots,N\} \quad x^{(i)} \in \mathbb{R}^2, y^{(i)} \in \{0, 1\} $$ Consideremos ahora una tupla en particular $(X, Y)$. La salida de la capa oculta en notación matricial es $$ Z = \text{sigmoide}( W_Z X + B_Z) $$ donde $W_Z \in \mathbb{R}^{M \times 2}$, $B_Z \in \mathbb{R}^{M}$ y $M$ es el tamaño de la capa oculta La salida de la capa visible (última capa) en notación matricial es $$ Y = \text{sigmoide}( W_Y Z + B_Y) $$ donde $W_Y \in \mathbb{R}^{1 \times M}$, $B_Z \in \mathbb{R}$ La función sigmoide se define como $$ \text{sigmoide}(x) = \frac{1}{1+ e^{-x}} $$ Luego $Z$ es un vector de largo $M$ con valores en $[0, 1]$ e $Y$ es un escalar con valor en el rango $[0, 1]$ ## Formulación bayesiana Para darle un toque bayesiano a este modelo debemos - Definir priors para $W_Z$, $B_Z$, $W_Y$ y $B_Y$. Se pide que utilice priors **normales con media cero y desviación estándar diez**. - Definir una verosimilitud para le problema. Dado que el problema es de clasificación binaria, utilice una distribución de **Bernoulli** con $p=Y$ - Considere los datos $X$ como una variable determínista. ## Indicaciones Utilice - El atributo `shape` para darle la dimensión correcta a cada variable cada uno - El atributo `observed` para asignar las etiquetas reales a esta variable aleatoria observada - `pm.Data` para la variable independiente - `theano.tensor.sigmoid` para calcular la función sigmoide - `A.dot(B)` para calcular el producto matricial entre `A` y `B` ## Instrucciones específicas - Considere el dataset sintético `two-moons` que se muestra a continuación. Se pide que realice dos experimentos variando el valor de `n_samples`, primero a $100$ y finalmente a $10$ - Implemente el modelo de red neuronal bayesiana en `pymc3` dejando $M$ como un argumento. Para cada valor de `n_samples` entrene tres modelos con $M=1$, $M=3$ y $M=10$ - Seleccione y calibre un algoritmo de MCMC para entrenar este modelo. Justifique y respalde sus decisiones en base al comportamiento de las trazas, al estadístico Gelman-Rubin y a la función de autocorrelación - Estudie el posterior de los parámetros y evalue el posterior predictivo sobre los datos de prueba. Muestre graficamente la media y la varianza del posterior predictivo en el espacio de los datos. Haga observaciones y comparaciones entre los 6 casos (3 valores de $M$ y 2 valores de `n_samples`) ``` %matplotlib notebook import matplotlib.pyplot as plt import numpy as np from sklearn.datasets import make_moons x, y = make_moons(n_samples=100, # Varie este parámetro shuffle=True, noise=0.2, random_state=123456) x = (x - np.mean(x, keepdims=True))/np.std(x, keepdims=True) fig, ax = plt.subplots(figsize=(6, 3), tight_layout=True) ax.scatter(x[y==0, 0], x[y==0, 1], marker='o') ax.scatter(x[y==1, 0], x[y==1, 1], marker='x') x1, x2 = np.meshgrid(np.linspace(-3, 3, 100), np.linspace(-3, 3, 100)) x_test = np.vstack([x1.ravel(), x2.ravel()]).T ``` Hint: Si `model_preds` es el posterior predictivo en el conjunto de test donde la primera dimensión son las muestras y la segunda dimensión los ejemplos, podemos graficar la media de ese posterior como: ``` fig, ax = plt.subplots(figsize=(6, 3), tight_layout=True) cmap = ax.pcolormesh(x1, x2, np.mean(model_preds, axis=0).reshape(len(x1), len(x2)), cmap=plt.cm.RdBu_r, shading='gouraud', vmin=0, vmax=1) plt.colorbar(cmap, ax=ax) ax.scatter(x[y==0, 0], x[y==0, 1], c='k', marker='o') ax.scatter(x[y==1, 0], x[y==1, 1], c='k', marker='x') ```
github_jupyter
# ConsPortfolioModel Documentation [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/econ-ark/DemARK/master?filepath=notebooks%2FConsPortfolioModelDoc.ipynb) ``` # Setup stuff import HARK.ConsumptionSaving.ConsPortfolioModel as cpm import HARK.ConsumptionSaving.ConsumerParameters as param import copy import matplotlib.pyplot as plt import numpy as np import warnings warnings.filterwarnings('ignore') from HARK.ConsumptionSaving.ConsPortfolioModel import PortfolioSolution ``` We implement three different ways to allow portfolio choice. The agent can choose * any portfolio share ('continuous choice') * only a specified set of portfolio shares ('discrete choice') * With probability 1 (agent always gets to choose) * With probability 0 < p < 1 (stochastic chance to choose) We allow two choices for the description of the distribution of the stochastic variable: 1. A generic discrete probability distribution * Nodes and their probabilities are specified 2. A true lognormal distribution * The mean return and the standard deviation are specified In the discrete portfolio shares case, the user also must input a function that *draws* from the distribution in drawRiskyFunc Other assumptions: * distributions are time constant * probability of being allowed to reoptimize is time constant * If p < 1, you must specify the PortfolioSet discretely ``` # Set up the model # Parameters from Mehra and Prescott (1985): Avg = 1.08 # equity premium Std = 0.20 # standard deviation of rate-of-return shocks RiskyDstnFunc = cpm.RiskyDstnFactory(RiskyAvg=Avg, RiskyStd=Std) # Generates nodes for integration RiskyDrawFunc = cpm.LogNormalRiskyDstnDraw(RiskyAvg=Avg, RiskyStd=Std) # Generates draws from a lognormal distribution init_portfolio = copy.copy(param.init_idiosyncratic_shocks) # Default parameter values for inf horiz model init_portfolio['approxRiskyDstn'] = RiskyDstnFunc init_portfolio['drawRiskyFunc'] = RiskyDrawFunc init_portfolio['RiskyCount'] = 2 # Number of points in the approximation; 2 points is minimum init_portfolio['RiskyShareCount'] = 25 # How many discrete points to allow in the share approximation init_portfolio['Rfree'] = 1.0 # Riskfree return factor is 1 (interest rate is zero) init_portfolio['CRRA'] = 6.0 # Relative risk aversion # Uninteresting technical parameters: init_portfolio['aXtraMax'] = 100 init_portfolio['aXtraCount'] = 50 init_portfolio['BoroCnstArt'] = 0.0 # important for theoretical reasons # init_portfolio['vFuncBool'] = True # We do not need value function for purposes here init_portfolio['DiscFac'] = 0.90 # Create portfolio choice consumer type pcct = cpm.PortfolioConsumerType(**init_portfolio) # Solve the model under the given parameters pcct.solve() aMin = 0 # Minimum ratio of assets to income to plot aMax = 10 # Maximum ratio of assets to income to plot aPts = 100 # Number of points to plot # Campbell-Viceira (2002) approximation to optimal portfolio share in Merton-Samuelson (1969) model pcct.MertSamCampVicShare = pcct.RiskyShareLimitFunc(RiskyDstnFunc(init_portfolio['RiskyCount'])) eevalgrid = np.linspace(0,aMax,aPts) # range of values of assets for the plot plt.plot(eevalgrid, pcct.solution[0].RiskyShareFunc[0][0](eevalgrid)) plt.axhline(pcct.MertSamCampVicShare, c='r') # The Campbell-Viceira approximation plt.ylim(0,1.05) plt.text((aMax-aMin)/4,0.45,r'$\uparrow$ limit as $m \uparrow \infty$',fontsize = 22,fontweight='bold') plt.show() # Simulate 20 years of behavior for a set of consumers SimPer = 20 pcct.track_vars = ['aNrmNow', 't_age', 'RiskyShareNow'] pcct.T_sim = SimPer pcct.initializeSim() pcct.simulate() pcct.RiskyShareNow_hist from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.set_zlim(pcct.MertSamCampVicShare,1.0) ax.scatter(pcct.aNrmNow_hist, pcct.t_age_hist, pcct.RiskyShareNow_hist) plt.show() # The consumers are very impatient and so even if they start rich they end up as buffer stock savers # But with all of their buffer stock savings in the stock market # Solve the specialized / simple version for which there is a good approximation # This is the version for which Campbell and Viceira provide an approximate formula # assuming log normally distributed shocks init_lognormportfolio = copy.deepcopy(init_portfolio) # Use same parameter values init_lognormportfolio['RiskyAvg'] = Avg init_lognormportfolio['RiskyStd'] = Std init_lognormportfolio['RiskyCount'] = 11 # Eleven is enough points to do justice to the distribution lnpcct = cpm.LogNormalPortfolioConsumerType(**init_lognormportfolio) lnpcct.solve() lnpcct.MertSamCampVicShare = lnpcct.RiskyShareLimitFunc(RiskyDstnFunc(init_portfolio['RiskyCount'])) plt.plot(eevalgrid, lnpcct.solution[0].RiskyShareFunc[0][0](eevalgrid)) plt.axhline(lnpcct.MertSamCampVicShare, c='r') plt.ylim(0,1.05) plt.text((aMax-aMin)/4,lnpcct.MertSamCampVicShare-0.1,r'$\uparrow$ limit as $m \uparrow \infty$',fontsize = 22,fontweight='bold') plt.show() # Again simulate a few periods lnpcct.track_vars = ['aNrmNow', 't_age', 'RiskyShareNow'] lnpcct.T_sim = SimPer lnpcct.initializeSim() lnpcct.simulate() lnpcct.RiskyShareNow_hist fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter(lnpcct.aNrmNow_hist, lnpcct.t_age_hist, lnpcct.RiskyShareNow_hist) ax.set_zlim(lnpcct.MertSamCampVicShare,1.0) plt.show() # Version where only discrete values of portfolio share of risky assets are allowed init_portfolio_prb = copy.deepcopy(init_portfolio) init_portfolio_prb['AdjustPrb'] = 1.0 init_portfolio_prb['PortfolioDomain'] = cpm.DiscreteDomain([0.0, 0.5, 0.6, 1.0]) pcct_prb = cpm.PortfolioConsumerType(**init_portfolio_prb) pcct_prb.solve() eevalgrid = np.linspace(0,100,100) plt.plot(eevalgrid, pcct_prb.solution[0].RiskyShareFunc[0][0](eevalgrid)) plt.axhline(pcct_prb.RiskyShareLimitFunc(RiskyDstnFunc(init_portfolio['RiskyCount'])), c='r') plt.ylim(0,1.05) plt.show() # Version where you can choose your portfolio share only with some 0 < p < 1 init_portfolio_prb = copy.deepcopy(init_portfolio) init_portfolio_prb['AdjustPrb'] = 0.5 init_portfolio_prb['PortfolioDomain'] = cpm.DiscreteDomain([0.0, 0.6, 1.0]) pcct_prb = cpm.PortfolioConsumerType(**init_portfolio_prb) pcct_prb.solve() plt.plot(eevalgrid, pcct_prb.solution[0].RiskyShareFunc[0][0](eevalgrid)) plt.show() pcct_prb.track_vars = ['aNrmNow', 't_age', 'RiskyShareNow', 'CantAdjust'] pcct_prb.T_sim = 10 pcct_prb.AgentCount = 30 pcct_prb.initializeSim() pcct_prb.simulate() pcct_prb.RiskyShareNow_hist fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter(pcct_prb.aNrmNow_hist, pcct_prb.t_age_hist, pcct_prb.RiskyShareNow_hist) plt.show() ```
github_jupyter
# Тест. Практика проверки гипотез По данным опроса, 75% работников ресторанов утверждают, что испытывают на работе существенный стресс, оказывающий негативное влияние на их личную жизнь. Крупная ресторанная сеть опрашивает 100 своих работников, чтобы выяснить, отличается ли уровень стресса работников в их ресторанах от среднего. 67 из 100 работников отметили высокий уровень стресса. Посчитайте достигаемый уровень значимости, округлите ответ до четырёх знаков после десятичной точки. ``` from __future__ import division import numpy as np import pandas as pd from scipy import stats import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = "all" n = 100 prob = 0.75 F_H0 = stats.binom(n, prob) x = np.linspace(0,100,101) plt.bar(x, F_H0.pmf(x), align = 'center') plt.xlim(60, 90) plt.show() print('p-value: %.4f' % stats.binom_test(67, 100, prob)) ``` <b> Представим теперь, что в другой ресторанной сети только 22 из 50 работников испытывают существенный стресс. Гипотеза о том, что 22/50 соответствует 75% по всей популяции, методом, который вы использовали в предыдущей задаче, отвергается. Чем это может объясняться? Выберите все возможные варианты. ``` print('p-value: %.10f' % stats.binom_test(22, 50, prob)) ``` <b> The Wage Tract — заповедник в округе Тома, Джорджия, США, деревья в котором не затронуты деятельностью человека со времён первых поселенцев. Для участка заповедника размером 200х200 м имеется информация о координатах сосен (sn — координата в направлении север-юг, we — в направлении запад-восток, обе от 0 до 200). pines.txt Проверим, можно ли пространственное распределение сосен считать равномерным, или они растут кластерами. Загрузите данные, поделите участок на 5х5 одинаковых квадратов размера 40x40 м, посчитайте количество сосен в каждом квадрате (чтобы получить такой же результат, как у нас, используйте функцию scipy.stats.binned_statistic_2d). Если сосны действительно растут равномерно, какое среднее ожидаемое количество сосен в каждом квадрате? В правильном ответе два знака после десятичной точки. ``` pines_data = pd.read_table('pines.txt') pines_data.describe() pines_data.head() sns.pairplot(pines_data, size=4); sn_num, we_num = 5, 5 trees_bins = stats.binned_statistic_2d(pines_data.sn, pines_data.we, None, statistic='count', bins=[sn_num, we_num]) trees_squares_num = trees_bins.statistic trees_squares_num trees_bins.x_edge trees_bins.y_edge mean_trees_num = np.sum(trees_squares_num) / 25 print(mean_trees_num) ``` <b> Чтобы сравнить распределение сосен с равномерным, посчитайте значение статистики хи-квадрат для полученных 5х5 квадратов. Округлите ответ до двух знаков после десятичной точки. ``` stats.chisquare(trees_squares_num.flatten(), ddof = 0) ```
github_jupyter
``` import os md_dir = os.path.join(os.getcwd(), 'mds') md_filenames = [os.path.join(os.getcwd(), 'mds', filename) for filename in os.listdir(md_dir)] print(md_filenames) from collections import namedtuple LineStat = namedtuple('LineStat', 'source cleaned line_num total_lines_in_text is_header') lines = [] for f in md_filenames: with open(f, 'rt', encoding='utf-8') as f: file_lines = f.read().splitlines() for i, line in enumerate(file_lines): source = line.strip() if source=='': continue cleaned = source is_header = False if line.startswith('# ') or line.startswith('## ') or line.startswith('### '): splitted_header = source.split(' ', 1) if len(splitted_header)<2: continue cleaned = splitted_header[1] cleaned = cleaned.strip() is_header = True line_stat = LineStat(source=source, cleaned=cleaned, line_num=i, total_lines_in_text=len(file_lines), is_header=is_header) lines.append(line_stat) print(len(lines)) print('\n'.join([str(l) for l in lines[:10]])) print(sum(l.source.startswith('### ') for l in lines)) print(sum(l.is_header for l in lines)) # divide to learn and test set from random import shuffle shuffle(lines) threshold = int(len(lines) * 0.7) lines_learn = lines[:threshold] lines_test = lines[threshold:] print(f"Total lines: {len(lines)}, learn set: {len(lines_learn)}, lines_test: {len(lines_test)}") import csv csv.field_size_limit(1000000) def save_as_csv(filename, data): with open(filename, 'wt', encoding='utf-8', newline='') as f: fieldnames = LineStat._fields writer = csv.DictWriter(f, fieldnames=fieldnames) writer.writeheader() writer.writerows([r._asdict() for r in data]) print(LineStat._fields) save_as_csv('learn.csv', lines_learn) save_as_csv('test.csv', lines_test) def naive_is_header(line: LineStat): return False def short_is_header(line: LineStat): return True if len(line.cleaned)<32 else False def check_measures(classifier): tp, tn, fp, fn = 0, 0, 0, 0 for l in lines: l_wo_res = LineStat(source='', cleaned=l.cleaned, line_num=l.line_num, is_header=False) res = classifier(l_wo_res) if res: if l.is_header: tp += 1 else: fp += 1 print(l.source) else: if l.is_header: fn += 1 else: tn += 1 print(f"TP={tp}, TN={tn}, FP={fp}, FN={fn}") prec = tp / (tp+fp+1e-6) recall = tp / (tp+fn+1e-6) f1 = 2 * prec * recall /(prec + recall+1e-6) print(f"Precision={prec}, recall={recall}, F1={f1}") check_measures(naive_is_header) check_measures(short_is_header) bad_chars = set('#=./<>|(){}:[];') def rules_classifier(line: LineStat): text: str = line.cleaned numbers = sum(c.isdigit() for c in text) if numbers*2>len(text): return False if not text[0].isalnum(): return False if text[0].isalnum() and text[0].islower(): return False if any((c in bad_chars) for c in text): return False if len(text)>120: return False if line.line_num<2: return True if len(text)<32: return True if text.istitle(): return True return False check_measures(rules_classifier) ```
github_jupyter
Internet Resources: [Python Programming.net - machine learning episodes 39-42](https://pythonprogramming.net/hierarchical-clustering-mean-shift-machine-learning-tutorial/) ``` import matplotlib.pyplot as plt from matplotlib import style style.use('ggplot') import numpy as np from sklearn.datasets import make_blobs X, y = make_blobs(n_samples=25, centers=3, n_features=2, random_state=42) ##X = np.array([[1, 2], ## [1.5, 1.8], ## [5, 8], ## [8, 8], ## [1, 0.6], ## [9, 11], ## [8, 2], ## [10, 2], ## [9, 3]]) ##plt.scatter(X[:, 0],X[:, 1], marker = "x", s=150, linewidths = 5, zorder = 10) ##plt.show() #X = np.array([[-5, -4], [4,5], [3,-2], [-2,1]]) colors = 10*["g","r","c","b","k"] plt.scatter(X[:,0], X[:,1], s=50) plt.show() ``` The goal is to find clusters in the dataset. The first implementation of this algorithm still requires the user to input a radius parameter. **Training algorithm for mean shift with fixed bandwitdth** - 1. at start every data point is a centroid Repeat until optimized: for every centroid: - 2. for every data point: calculate distance to centroid - 3. new centroid = mean of all data points where distance of centroid and data point < radius **Prediction** - query is classified as class of nearest centroid ![](notes_screenshots/MeanShift1.png) ``` # mean shift without dynamic bandwidth class Mean_Shift_With_Fixed_Bandwidth: def __init__(self, radius): self.radius = radius def fit(self, data): centroids = {} # 1. every data point is initialized as centroid for i in range(len(data)): centroids[i] = data[i] # Repeat until optimized while True: new_centroids = [] # for every centroid for i in centroids: # i is centroid index in_bandwidth = [] # list of all data points that are within a proximity of self.radius of centroid centroid = centroids[i] # 2. for every data point: calculate distance to centroid for featureset in data: if np.linalg.norm(featureset-centroid) < self.radius: in_bandwidth.append(featureset) # 3. new centroid = mean of all data points where distance of centroid and data point < self.radius new_centroid = np.average(in_bandwidth,axis=0) new_centroids.append(tuple(new_centroid)) # casts nparray to tuple # get rid of any duplicate centroids uniques = sorted(list(set(new_centroids))) # need previous centroids to check if optimized prev_centroids = dict(centroids) # set new centroids (=uniques) as current centroids centroids = {i:np.array(uniques[i]) for i in range(len(uniques))} # is optimized if centroids are not moving anymore optimized = True for i in centroids: if not np.array_equal(centroids[i], prev_centroids[i]): optimized = False if not optimized: break if optimized: break self.centroids = centroids mean_shift = Mean_Shift_With_Fixed_Bandwidth(radius=3) mean_shift.fit(X) mean_shift_centroids = mean_shift.centroids plt.scatter(X[:,0], X[:,1], s=150) for c in mean_shift_centroids: plt.scatter(mean_shift_centroids[c][0], mean_shift_centroids[c][1], color='k', marker='*', s=150) plt.show() ``` Mean shift with dynamic bandwidth differs from the implementation with fixed bandwidth in that it no longer requires a set bandwidth from the user. Instead it estimates a fitting radius. Additionally when calculating new means, each data point is weighted depending how near or far its away from the current mean. **Training algorithm for mean shift with dynamic bandwitdth** - 1. at start every data point is a centroid - 2. estimate radius: radius = mean(distance of every datapoint to mean of entire dataset) Repeat until optimized: for every centroid: - 3. for every data point: calculate distance to centroid and assign weight to it. - 4. calculate new centroid: new centroid = mean of all weighted data points within radius **Prediction:** - query is classified as class of nearest centroid ![](notes_screenshots/MeanShift2.png) ``` class Mean_Shift_With_Dynamic_Bandwith: def __init__(self, radius_norm_step = 100): self.radius_norm_step = radius_norm_step # controls how many discrete wights are used def fit(self,data,max_iter=1000, weight_fkt=lambda x : x**2): # weight_fkt: how to weight distances # 1. every data point is a centroid self.centroids = {i:data[i] for i in range(len(data))} # 2. radius calculation mean_of_entire_data = np.average(data,axis=0) # all_distances= list of distances for ever data point to mean of entire date all_distances = [np.linalg.norm(datapoint-mean_of_entire_data) for datapoint in data] self.radius = np.mean(all_distances) print("radius:", self.radius) # list of discrete weights: let n = self.radius_norm_step -> weights = [n-1,n-2,n-3,...,2,1] weights = [i for i in range(self.radius_norm_step)][::-1] # [::-1] inverts list # do until convergence for count in range(max_iter): new_centroids = [] # for each centroid for centroid_class in self.centroids: centroid = self.centroids[centroid_class] # 3. weigh data points new_centroid_weights = [] for data_point in data: weight_index = int(np.linalg.norm(data_point - centroid)/self.radius * self.radius_norm_step) new_centroid_weights.append(weight_fkt(weights[min(weight_index, self.radius_norm_step)-1])) # calculate new centroid # w: weight, x: sample new_centroid = np.sum([ w*x for w, x in zip(new_centroid_weights, data)], axis=0) / np.sum(new_centroid_weights) new_centroids.append(tuple(new_centroid)) uniques = sorted(list(set(new_centroids))) #remove non uniques for i in uniques: for ii in [i for i in uniques]: # centroid is near enough to another centroid to merge if not i == ii and np.linalg.norm(np.array(i)-np.array(ii)) <= self.radius/self.radius_norm_step: uniques.remove(ii) prev_centroids = dict(self.centroids) self.centroids = {} for i in range(len(uniques)): self.centroids[i] = np.array(uniques[i]) # check if optimized optimized = True for i in self.centroids: if not np.array_equal(self.centroids[i], prev_centroids[i]): optimized = False if optimized: print("Converged @ iteration ", count) break # classify training data self.classifications = {i:[] for i in range(len(self.centroids))} for featureset in data: #compare distance to either centroid distances = [np.linalg.norm(featureset-self.centroids[centroid]) for centroid in self.centroids] classification = (distances.index(min(distances))) # featureset that belongs to that cluster self.classifications[classification].append(featureset) def predict(self,data): #compare distance to either centroid distances = [np.linalg.norm(data-self.centroids[centroid]) for centroid in self.centroids] classification = (distances.index(min(distances))) return classification clf = Mean_Shift_With_Dynamic_Bandwith() clf.fit(X) centroids = clf.centroids print(centroids) colors = 10*['r','g','b','c','k','y'] for classification in clf.classifications: color = colors[classification] for featureset in clf.classifications[classification]: plt.scatter(featureset[0],featureset[1], marker = "x", color=color, s=150, linewidths = 5, zorder = 10) for c in centroids: plt.scatter(centroids[c][0],centroids[c][1], color='k', marker = "*", s=150, linewidths = 5) plt.show() ```
github_jupyter
# Using the same code as before, please solve the following exercises 2. Play around with the learning rate. Values like 0.00001, 0.0001, 0.001, 0.1, 1 are all interesting to observe. Useful tip: When you change something, don't forget to RERUN all cells. This can be done easily by clicking: Kernel -> Restart & Run All If you don't do that, your algorithm will keep the OLD values of all parameters. ## Solution Find the piece of code that chooses the optimization algorithm. Change the learning_rate argument to 0.00001. Here are some takeaways: 1. It takes the algorithm the same time to finish working. 2. The loss is not really minimized. 3. The weights and biases have not reached the desired values. 4. More iterations are needed for this learning rate to solve the problem. 5. The problem IS NOT SOLVED. 6. The final graph looks like a 45-degree line, but if you scale the axes, it would not be a 45-degree line. ## Import the relevant libraries ``` # We must always import the relevant libraries for our problem at hand. NumPy and TensorFlow are required for this example. import numpy as np import matplotlib.pyplot as plt import tensorflow as tf ``` ## Data generation We generate data using the exact same logic and code as the example from the previous notebook. The only difference now is that we save it to an npz file. Npz is numpy's file type which allows you to save numpy arrays into a single .npz file. We introduce this change because in machine learning most often: * you are given some data (csv, database, etc.) * you preprocess it into a desired format (later on we will see methods for preprocesing) * you save it into npz files (if you're working in Python) to access later Nothing to worry about - this is literally saving your NumPy arrays into a file that you can later access, nothing more. ``` # First, we should declare a variable containing the size of the training set we want to generate. observations = 1000 # We will work with two variables as inputs. You can think about them as x1 and x2 in our previous examples. # We have picked x and z, since it is easier to differentiate them. # We generate them randomly, drawing from an uniform distribution. There are 3 arguments of this method (low, high, size). # The size of xs and zs is observations x 1. In this case: 1000 x 1. xs = np.random.uniform(low=-10, high=10, size=(observations,1)) zs = np.random.uniform(-10, 10, (observations,1)) # Combine the two dimensions of the input into one input matrix. # This is the X matrix from the linear model y = x*w + b. # column_stack is a Numpy method, which combines two matrices (vectors) into one. generated_inputs = np.column_stack((xs,zs)) # We add a random small noise to the function i.e. f(x,z) = 2x - 3z + 5 + <small noise> noise = np.random.uniform(-1, 1, (observations,1)) # Produce the targets according to our f(x,z) = 2x - 3z + 5 + noise definition. # In this way, we are basically saying: the weights should be 2 and -3, while the bias is 5. generated_targets = 2*xs - 3*zs + 5 + noise # save into an npz file called "TF_intro" np.savez('TF_intro', inputs=generated_inputs, targets=generated_targets) ``` ## Solving with TensorFlow <i/>Note: This intro is just the basics of TensorFlow which has way more capabilities and depth than that.<i> ``` # Load the training data from the NPZ training_data = np.load('TF_intro.npz') # Declare a variable where we will store the input size of our model # It should be equal to the number of variables you have input_size = 2 # Declare the output size of the model # It should be equal to the number of outputs you've got (for regressions that's usually 1) output_size = 1 # Outline the model # We lay out the model in 'Sequential' # Note that there are no calculations involved - we are just describing our network model = tf.keras.Sequential([ # Each 'layer' is listed here # The method 'Dense' indicates, our mathematical operation to be (xw + b) tf.keras.layers.Dense(output_size, # there are extra arguments you can include to customize your model # in our case we are just trying to create a solution that is # as close as possible to our NumPy model kernel_initializer=tf.random_uniform_initializer(minval=-0.1, maxval=0.1), bias_initializer=tf.random_uniform_initializer(minval=-0.1, maxval=0.1) ) ]) # We can also define a custom optimizer, where we can specify the learning rate custom_optimizer = tf.keras.optimizers.SGD(learning_rate=0.00001) # Note that sometimes you may also need a custom loss function # That's much harder to implement and won't be covered in this course though # 'compile' is the place where you select and indicate the optimizers and the loss model.compile(optimizer=custom_optimizer, loss='mean_squared_error') # finally we fit the model, indicating the inputs and targets # if they are not otherwise specified the number of epochs will be 1 (a single epoch of training), # so the number of epochs is 'kind of' mandatory, too # we can play around with verbose; we prefer verbose=2 model.fit(training_data['inputs'], training_data['targets'], epochs=100, verbose=2) ``` ## Extract the weights and bias Extracting the weight(s) and bias(es) of a model is not an essential step for the machine learning process. In fact, usually they would not tell us much in a deep learning context. However, this simple example was set up in a way, which allows us to verify if the answers we get are correct. ``` # Extracting the weights and biases is achieved quite easily model.layers[0].get_weights() # We can save the weights and biases in separate variables for easier examination # Note that there can be hundreds or thousands of them! weights = model.layers[0].get_weights()[0] weights # We can save the weights and biases in separate variables for easier examination # Note that there can be hundreds or thousands of them! bias = model.layers[0].get_weights()[1] bias ``` ## Extract the outputs (make predictions) Once more, this is not an essential step, however, we usually want to be able to make predictions. ``` # We can predict new values in order to actually make use of the model # Sometimes it is useful to round the values to be able to read the output # Usually we use this method on NEW DATA, rather than our original training data model.predict_on_batch(training_data['inputs']).round(1) # If we display our targets (actual observed values), we can manually compare the outputs and the targets training_data['targets'].round(1) ``` ## Plotting the data ``` # The model is optimized, so the outputs are calculated based on the last form of the model # We have to np.squeeze the arrays in order to fit them to what the plot function expects. # Doesn't change anything as we cut dimensions of size 1 - just a technicality. plt.plot(np.squeeze(model.predict_on_batch(training_data['inputs'])), np.squeeze(training_data['targets'])) plt.xlabel('outputs') plt.ylabel('targets') plt.show() # Voila - what you see should be exactly the same as in the previous notebook! # You probably don't see the point of TensorFlow now - it took us the same number of lines of code # to achieve this simple result. However, once we go deeper in the next chapter, # TensorFlow will save us hundreds of lines of code. ```
github_jupyter
<a id="item31"></a> # 203 - Build a Regression Model in Keras ## Load Libs ``` import numpy as np import pandas as pd from sklearn.metrics import mean_squared_error from sklearn.model_selection import train_test_split import keras from keras.layers import Dense from keras.models import Sequential ``` ## Load dataset ``` concrete_data = pd.read_csv('concrete_data.csv') concrete_data.head() ``` #### Let's check how many data points we have. ``` concrete_data.shape concrete_data.describe() concrete_data.isnull().sum() ``` #### Split data into predictors and target ``` concrete_data_columns = concrete_data.columns predictors = concrete_data[concrete_data_columns[concrete_data_columns != 'Strength']] # all columns except Strength target = concrete_data['Strength'] # Strength column ``` <a id="item2"></a> Let's do a quick sanity check of the predictors and the target dataframes. ``` predictors.head() target.head() ``` Finally, the last step is to normalize the data by substracting the mean and dividing by the standard deviation. Let's save the number of predictors to *n_cols* since we will need this number when building our network. ``` predictors_norm = (predictors - predictors.mean()) / predictors.std() predictors_norm.head() n_cols = predictors_norm.shape[1] # number of predictors n_cols ``` <a id="item1"></a> <a id='item32'></a> ## Train Test Split ``` X_train, X_test, y_train, y_test = train_test_split(predictors_norm, target, test_size=0.3, random_state=42) print ('Train set:', X_train.shape, y_train.shape) print ('Test set:', X_test.shape, y_test.shape) ``` <a id='item33'></a> ## Build a Neural Network ``` # define regression model def regression_model(): # create model model = Sequential() model.add(Dense(10, activation='relu', input_shape=(n_cols,))) model.add(Dense(1)) # compile model model.compile(optimizer='adam', loss='mean_squared_error') return model ``` <a id="item4"></a> <a id='item34'></a> ## Train and Test the Network Let's call the function now to create our model. ``` # build the model model = regression_model() # fit the model model.fit(X_train, y_train, epochs=50, verbose=1) y_predicted = model.predict(X_test) mean_squared_error(y_test, y_predicted) %%time # Applying 50 times to calculate mean and std mean_squared_errors = [] for _ in range(50): model = regression_model() model.fit(X_train, y_train, epochs=100, verbose=0) y_predicted = model.predict(X_test) mse = mean_squared_error(y_test, y_predicted) mean_squared_errors.append(mse) print('mean and the standard deviation of the mean squared errors - mean: {} and std: {}'.format(np.mean(mean_squared_errors), np.std(mean_squared_errors))) print('How does the mean of the mean squared errors compare to that from Step A?') print('before - mean: 349.7189361313099 and std: 95.82097699620797') print('after - mean: {} and std: {}'.format(np.mean(mean_squared_errors), np.std(mean_squared_errors))) ```
github_jupyter
``` # Train number of different models from Flair framework. # With different sized trainin data # save predictions of each model to file # Notice - 1st run may take long as model weights are downloaded # Dataset # https://github.com/t-davidson/hate-speech-and-offensive-language # Paper # https://aaai.org/ocs/index.php/ICWSM/ICWSM17/paper/view/15665 # Their code # https://github.com/t-davidson/hate-speech-and-offensive-language/blob/master/src/Automated%20Hate%20Speech%20Detection%20and%20the%20Problem%20of%20Offensive%20Language%20Python%203.6.ipynb # Code based on https://github.com/zalandoresearch/flair/blob/master/resources/docs/TUTORIAL_4_ELMO_BERT_FLAIR_EMBEDDING.md import pandas as pd import random import os import numpy as np import torch import nltk import string import re from nltk.stem.porter import * import time # Display whole text of dataframe field and don't cut it pd.set_option('display.max_colwidth', -1) print(f'torch version: {torch.__version__}') ``` ``` dataset = 'hatespeech' current = os.getcwd() basefolder = current + '/dataset_'+ dataset+'/' datafolder = basefolder + 'data/' # for example /dataset_businessnews/data/ print(basefolder) infolder = basefolder + 'input/' outfolder = basefolder + 'output/' from flair.data import Sentence from flair.data_fetcher import NLPTaskDataFetcher from flair.embeddings import WordEmbeddings, StackedEmbeddings, DocumentRNNEmbeddings from flair.embeddings import DocumentPoolEmbeddings from flair.embeddings import FlairEmbeddings, BertEmbeddings, ELMoEmbeddings from flair.embeddings import BytePairEmbeddings from flair.embeddings import OpenAIGPTEmbeddings #from flair.embeddings import OpenAIGPT2Embeddings # New DocumentRNNEmbeddings, deprecates DocumentLSTMembeddings # from flair.embeddings import #DocumentLSTMEmbeddings from flair.models import TextClassifier from flair.trainers import ModelTrainer from pathlib import Path # new ones: GPT-1 and GPT-2 # https://github.com/flairNLP/flair/tree/master/resources/docs/embeddings # https://github.com/flairNLP/flair/blob/master/resources/docs/embeddings/TRANSFORMER_EMBEDDINGS.md SEED = 1 # REPEATABILITY def seed_everything(seed=SEED): random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.backends.cudnn.deterministic = True seed_everything() # also called here # TEXT PREPROCESS puncts = [',', '.', '"', ':', ')', '(', '-', '!', '?', '|', ';', "'", '$', '&', '/', '[', ']', '>', '%', '=', '#', '*', '+', '\\', '•', '~', '@', '£', '·', '_', '{', '}', '©', '^', '®', '`', '<', '→', '°', '€', '™', '›', '♥', '←', '×', '§', '″', '′', 'Â', '█', '½', 'à', '…', '“', '★', '”', '–', '●', 'â', '►', '−', '¢', '²', '¬', '░', '¶', '↑', '±', '¿', '▾', '═', '¦', '║', '―', '¥', '▓', '—', '‹', '─', '▒', ':', '¼', '⊕', '▼', '▪', '†', '■', '’', '▀', '¨', '▄', '♫', '☆', 'é', '¯', '♦', '¤', '▲', 'è', '¸', '¾', 'Ã', '⋅', '‘', '∞', '∙', ')', '↓', '、', '│', '(', '»', ',', '♪', '╩', '╚', '³', '・', '╦', '╣', '╔', '╗', '▬', '❤', 'ï', 'Ø', '¹', '≤', '‡', '√', ] def clean_text(x): x = str(x) for punct in puncts: if punct in x: # comparison makes faster x = x.replace(punct, f' {punct} ') return x quotes = ['″', '′', '"'] # apostrophe "'" def mark_quotes(x): x = str(x) for quote in quotes: if quote in x: # comparison makes faster x = x.replace(quote, f'quote') return x def preprocess(text_string): """ Accepts a text string and replaces: 1) urls with URLHERE 2) lots of whitespace with one instance 3) mentions with MENTIONHERE This allows us to get standardized counts of urls and mentions Without caring about specific people mentioned """ space_pattern = '\s+' giant_url_regex = ('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|' '[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+') mention_regex = '@[\w\-]+' #add #, mention, e.g. &#8120 mention_regex2 = '&#[0-9]*' parsed_text = re.sub(space_pattern, ' ', text_string) parsed_text = re.sub(giant_url_regex, ' URL ', parsed_text) parsed_text = re.sub(mention_regex, ' MENTION', parsed_text) parsed_text = re.sub(mention_regex2, ' MENTION', parsed_text) return parsed_text def tokenize(tweet): """Removes punctuation & excess whitespace, sets to lowercase, and stems tweets. Returns a list of stemmed tokens.""" tweet = " ".join(re.split("[^a-zA-Z]*", tweet.lower())).strip() tokens = [stemmer.stem(t) for t in tweet.split()] return tokens def basic_tokenize(tweet): """Same as tokenize but without the stemming""" # *needed to be removed or outputs a list of letters #tweet = " ".join(re.split("[^a-zA-Z.,!?]*", tweet.lower())).strip() tweet = " ".join(re.split("[^a-zA-Z.,!?]", tweet.lower())).strip() #tweet = " ".join(re.split(r'\s+', tweet.lower())).strip() return tweet.split() ``` ``` def loadData(): train = pd.read_csv(basefolder+'input/train.csv',sep='\t', header = None) dev = pd.read_csv(basefolder+'input/dev.csv' ,sep='\t', header = None) test = pd.read_csv(basefolder+'input/test.csv' ,sep='\t', header = None) train.columns = ['id','label','text'] dev.columns = ['id','label', 'text'] test.columns = ['id','label', 'text'] return train, dev, test def preprosess_hatespeech(df): df.text = df.text.apply(lambda x: preprocess(x)) #URL, @mention etc df["text"] = df["text"].apply(lambda x: clean_text(x)) df["text"] = df["text"].apply(lambda x: mark_quotes(x)) #df.text = df.text.apply(lambda x: basic_tokenize(x)) return df # Turn label from digit into Fasttext format __label__. "1" into "__label__1" def toFasttext(df): df['label'] = '__label__' + df['label'].astype(str) return df data_folder = infolder # randomize # Load data train, dev, test = loadData() train = train.iloc[np.random.permutation(len(train))] #Test smaller trainsize = len(train) '''SET TRAINSIZE HERE''' # 100, 200, 500, 1k, 3k, 7k, 18k trainsize = 100 train = train[0:trainsize] print(len(train)) print(len(dev)) print(len(test)) ``` ### Preprocess ``` train = preprosess_hatespeech(train) dev = preprosess_hatespeech(dev) test = preprosess_hatespeech(test) train = toFasttext(train) dev = toFasttext(dev) test = toFasttext(test) train.head() # Id in start of line is not Fasttext format: remove id train.drop(['id'], axis=1, inplace=True) dev.drop(['id'], axis=1, inplace=True) test.drop(['id'], axis=1, inplace=True) # Write to Flairs input csv files train.to_csv(basefolder+'input/flair_train.csv',sep='\t', index = False, header = False) dev.to_csv(basefolder+'input/flair_dev.csv' ,sep='\t', index = False, header = False) test.to_csv(basefolder+'input/flair_test.csv',sep='\t', index = False, header = False) ``` ### Flair ### Stacked embeddings ``` # Embeddings # https://github.com/zalandoresearch/flair/blob/master/resources/docs/TUTORIAL_4_ELMO_BERT_FLAIR_EMBEDDING.md # 'multi-forward', multi-lang English, German, French, Italian, Dutch, Polish, # Mix of corpora (Web, Wikipedia, Subtitles, News) # 'mix-forward'English, Forward LM embeddings over mixed corpus (Web, Wikipedia, Subtitles) ``` `StackedEmbeddings` are currently a `WordEmbeddings` class, so they cannot directly be used to classify documents. They can only be used for sequence labeling. However, you can put a stack of word embeddings into one of the `DocumentEmbeddings` classes such as `DocumentPoolEmbeddings` or `DocumentLSTMEmbeddings`. This way, you are specifying how to aggregate word embeddings for text classification So `DocumentPoolEmbeddings` will simply average them, while `DocumentLSTMEmbeddings` will train an LSTM over them. https://github.com/zalandoresearch/flair/issues/414 *update depracated: DocumentLSTMEmbeddings. (The functionality of this class is moved to 'DocumentRNNEmbeddings') ``` # OR average # document_embeddings = DocumentPoolEmbeddings(word_embeddings) ``` #### Model ``` # https://towardsdatascience.com/text-classification-with-state-of-the-art-nlp-library-flair-b541d7add21f # https://github.com/zalandoresearch/flair/blob/master/resources/docs/TUTORIAL_7_TRAINING_A_MODEL.md #data_folder = infolder data_folder corpus = NLPTaskDataFetcher.load_classification_corpus(data_folder, test_file='flair_test.csv', dev_file='flair_dev.csv', train_file='flair_train.csv') print(corpus) #print(len(corpus.train)) # 2. create the label dictionary label_dict = corpus.make_label_dictionary() #print(label_dict) ### Individual model only, skip when in batch ``` ``` # classifier = TextClassifier(stacked_embeddings, label_dictionary=corpus.make_label_dictionary(), # multi_label=False) ``` ``` # Glove alone 0.902 # Winners: Fasttext: en-crawl, 0.9129 solo # word embeddings pooled:glove+fasttext 'test_score': 0.8892, # glove, fasttext:en-crawl, flair-multi-forward, elmo('original') f1-score 0.9155 # ELMO(original) test_score': 0.9002 (f-score 0.9145 ) # flair-news-forward WITHOUT TOKENIZATION, 'test_score': 0.8526 # flair-news-forward: 'test_score': 0.8741 # BERT only + RNN 256, bidir=True, 'test_score': 0.904, # Tweet + Bert same, not very great, used 128 rnn? #. # 0.8911 flair + BPE ############################## #NEW BEST adding preprocess puncts+quotes, glove, en-twitter, en-crawl: test_score': 0.9242, # no stemming # BEST glove, en-twitter, en-crawl, flair-multi-forward: f1-score 0.9129 # add stemming f-score 0.7808 Breaking down, very bad score # --------------------- # Added Preprosessing, no stemming # 'test_score': 0.9072 glove, en-twitter , flair-multi-forward # Add to this, en-crawl Fastext # f1-score 0.9129 BEST # Adding Kominov embedding: 'test_score': 0.8868 -> weaker considerably, by 0.03 # ---------------------------- # Compare single embeddings # en-twitter 'test_score': 0.8943 # en-crawl, Fasttext 'test_score': 0.9064, # flai-multi-forward: 'test_score': 0.7738 WEAK! WHY? Also slow # ---------------------------- # Glove, en-twitter, en-crawl: 'test_score': 0.8865, (20 epoch) # Glove, en-twitter, en-crawl: same + 2-way FLAIR 'test_score': 0.8854 - weaker, but 15 epoch # bert only, no glove: slow, 'test_score': 0.7329 # Flair only, no glove: 'test_score': 0.8158 (0.06 lower than with Glove) # Glove, Flair-multi 2ways, Bert-base-cased : OOM # test_score': 0.8763, Glove + doc-embedding multi # test_score': 0.8731, Glove + doc-embedding news # trainer.train('./', max_epochs=10) ``` ### Predict ``` def saveResults(savelist, name='all_default'): import shelve # file to be used filename= name+'.shlf' shelf = shelve.open(outfolder+filename) #shelf = shelve.open("all_flair.shlf") # serializing #shelf["all_flair"] = all_flair shelf[name] = savelist shelf.close() # you must close the shelve file!!! def loadResults(name='all_default'): import shelve filename= name+'.shlf' shelf = shelve.open(outfolder+filename) new = shelf[name] shelf.close() return new ''' Train with each embedding in the list, predict, add results to the list Parameters: word_embeddings, eg WordEmbeddings('glove') modelname and modeldesc - text to be added in results savelist : list where results are appended. Can be empty or already including results epohcs: epochs to run ''' def train_and_predict(embeddings, modelname, modeldesc, savelist, epochs=15, batch_size=32): print(modelname) start = time.time() # PREPARE document_embeddings = DocumentRNNEmbeddings(word_embeddings, hidden_size=512, bidirectional = False, rnn_type='LSTM', reproject_words=True, reproject_words_dimension=256 ) seed_everything(SEED) corpus = NLPTaskDataFetcher.load_classification_corpus(data_folder, test_file='flair_test.csv', dev_file='flair_dev.csv', train_file='flair_train.csv') seed_everything(SEED) label_dict = corpus.make_label_dictionary() seed_everything(SEED) classifier = TextClassifier(document_embeddings, label_dictionary=corpus.make_label_dictionary(), multi_label=False) trainer = ModelTrainer(classifier, corpus) # TRAINING seed_everything(SEED) trainer.train('./', learning_rate=0.1, mini_batch_size=batch_size, # 32 # BERT OOM even with 16 batch -> need 8. others run on 32 or even more anneal_factor=0.5, patience=5, max_epochs=epochs, #15 ) #max_epochs=150 duration_train = time.time()-start # PREDICT start_pred = time.time() # turn text into Flairs "Sentence object" test['flair_sentence'] = test['text'].apply(lambda x: Sentence(x)) # discard output, result is put into object itself _ = test['flair_sentence'].apply(lambda x: classifier.predict(x)) # sentence.labels returns a list containing flairs Label object that includes a dict. # dig the values for predicted label + confidence from within the dict # the 'value' returns a str, cast it to int test['yhat'] = test['flair_sentence'].apply(lambda x: int(x.labels[0].to_dict()['value'])) test['confidence'] = test['flair_sentence'].apply(lambda x: x.labels[0].to_dict()['confidence']) results = pd.DataFrame(test[['yhat', 'confidence']]) results.columns=['label','confidence'] results.head() # ADD RESULTS TO LIST duration_predict = time.time() - start_pred #print(f'Duration {duration:.2f} s') savelist.append({'model': modelname, 'labels': results['label'], 'confidence': results['confidence'], 'traintime': duration_train, 'predtime3k': duration_predict, 'modeldesc': modeldesc } ) ``` ### function mode ``` savelist = [] # list to save results modeldesc = '512LSTM_15epoch_non-bi' #BATCH_SIZE=32 EPOCHS = 15 ``` #### To use ELMoEmbeddings, please first install with "pip install allennlp" ``` total_time = time.time() word_embeddings = [ WordEmbeddings('glove'), ] modelname = 'glove' train_and_predict(word_embeddings, modelname, modeldesc, savelist=savelist, epochs=EPOCHS) word_embeddings = [ WordEmbeddings('en-crawl'), ] modelname = 'fasttext web-crawl' train_and_predict(word_embeddings, modelname, modeldesc, savelist=savelist, epochs=EPOCHS) word_embeddings = [ WordEmbeddings('en'), ] modelname = 'fasttext news/wiki' train_and_predict(word_embeddings, modelname, modeldesc, savelist=savelist, epochs=EPOCHS) word_embeddings = [ WordEmbeddings('en-twitter'), ] modelname = 'en-twitter' train_and_predict(word_embeddings, modelname, modeldesc, savelist=savelist, epochs=EPOCHS) word_embeddings = [ ELMoEmbeddings('original') ] modelname = 'elmo' train_and_predict(word_embeddings, modelname, modeldesc, savelist=savelist, epochs=EPOCHS) print(time.time() - total_time) # 1289 sec on 100 train (was 2x elmo) # 2403 sec on 18k # 2684 s 18 k ``` ``` # Flair # https://github.com/flairNLP/flair/blob/master/resources/docs/embeddings/FLAIR_EMBEDDINGS.md total_time = time.time() word_embeddings = [ # FlairEmbeddings('multi-forward'), # this is 300 languge, gave very low score # FlairEmbeddings('multi-backward'), FlairEmbeddings('news-forward'), # English Trained with 1 billion word corpus ] #modelname = 'Flair-news-fwd' modelname = 'Flair' train_and_predict(word_embeddings, modelname, modeldesc, savelist=savelist, epochs=EPOCHS) print(time.time() - total_time) # 167s in 100 train # 620s for 18k ``` ``` # BERT OOMs on 32 batch, use 8 total_time = time.time() # Bert Cased - separating lower and upper case, uncased - ignoring case. # Use cased word_embeddings = [ BertEmbeddings('bert-base-cased'), ] modelname = 'bert-base-cased' train_and_predict(word_embeddings, modelname, modeldesc, savelist=savelist, epochs=EPOCHS, batch_size=8) #word_embeddings = [ BertEmbeddings('bert-base-uncased'), ] #modelname = 'bert-base-uncased' #train_and_predict(word_embeddings, modelname, modeldesc, savelist=savelist, epochs=EPOCHS, batch_size=8) #BPE - takes memory - reduce batch size radically! word_embeddings = [ BytePairEmbeddings('en'), ] modelname = 'BytePairEmbedding' train_and_predict(word_embeddings, modelname, modeldesc, savelist=savelist, epochs=EPOCHS, batch_size=8) print(time.time() - total_time) # 450 s 18k # GPT-1 total_time = time.time() #Do we need batchsize 8 here? word_embeddings = [ OpenAIGPTEmbeddings(), ] modelname = 'gpt-1' train_and_predict(word_embeddings, modelname, modeldesc, savelist=savelist, epochs=EPOCHS, batch_size=8) print(time.time() - total_time) # 302 sec 18k ``` ### SAVE ``` #name='all_flair_512LSTM_15ep_8model' name='FINAL_flair_all_trainsz_'+str(trainsize) print(len(savelist)) saveResults(savelist, name=name) len(savelist) trainsize ``` ### DONE ``` # Code for combining results from 2 training times into 1 list etc. ``` ``` # add the 2 last name='all_flair_512LSTM_15ep_model' name = 'FINAL_flair_all_trainsz_'+str(trainsize) te = loadResults(name) #newlist = te+savelist newlist = te len(newlist) # cut doubles away # newlist = newlist[5:] # save combined name='FINAL_flair_all_trainsz_'+str(trainsize) print(len(newlist)) saveResults(newlist, name=name) # move list item 5 to end # te[5] # te.append(te.pop(5)) len(savelist) te = savelist[0:5] + [savelist[9]] + savelist[6:9] len(te) for i in savelist: print(i['model']) for i in te: print(i['model']) savelist[9] savelist[0]['model']='Flair' trainsize te[5] te[5] = savelist[0] te[6] = savelist[1] for i in newlist: print(i['model']) savelist[1] ```
github_jupyter
``` '''Example script to generate text from Nietzsche's writings. At least 20 epochs are required before the generated text starts sounding coherent. It is recommended to run this script on GPU, as recurrent networks are quite computationally intensive. If you try this script on new data, make sure your corpus has at least ~100k characters. ~1M is better. ''' from __future__ import print_function from keras.models import Sequential from keras.layers import Dense, Activation, Dropout from keras.layers import LSTM from keras.optimizers import RMSprop from keras.utils.data_utils import get_file import numpy as np import random import sys path = get_file('nietzsche.txt', origin="https://s3.amazonaws.com/text-datasets/nietzsche.txt") text = open(path).read().lower() print('corpus length:', len(text)) chars = sorted(list(set(text))) print('total chars:', len(chars)) char_indices = dict((c, i) for i, c in enumerate(chars)) indices_char = dict((i, c) for i, c in enumerate(chars)) # cut the text in semi-redundant sequences of maxlen characters maxlen = 40 step = 3 sentences = [] next_chars = [] for i in range(0, len(text) - maxlen, step): sentences.append(text[i: i + maxlen]) next_chars.append(text[i + maxlen]) print('nb sequences:', len(sentences)) print('Vectorization...') X = np.zeros((len(sentences), maxlen, len(chars)), dtype=np.bool) y = np.zeros((len(sentences), len(chars)), dtype=np.bool) for i, sentence in enumerate(sentences): for t, char in enumerate(sentence): X[i, t, char_indices[char]] = 1 y[i, char_indices[next_chars[i]]] = 1 # build the model: 2 stacked LSTM print('Build model...') model = Sequential() model.add(LSTM(128, input_shape=(maxlen, len(chars)))) model.add(Dense(len(chars))) model.add(Activation('softmax')) optimizer = RMSprop(lr=0.01) model.compile(loss='categorical_crossentropy', optimizer=optimizer) def sample(preds, temperature=1.0): # helper function to sample an index from a probability array preds = np.asarray(preds).astype('float64') preds = np.log(preds) / temperature exp_preds = np.exp(preds) preds = exp_preds / np.sum(exp_preds) probas = np.random.multinomial(1, preds, 1) return np.argmax(probas) # train the model, output generated text after each iteration for iteration in range(1, 2): print() print('-' * 50) print('Iteration', iteration) model.fit(X, y, batch_size=128, nb_epoch=1) start_index = random.randint(0, len(text) - maxlen - 1) for diversity in [0.2, 0.5, 1.0, 1.2]: print() print('----- diversity:', diversity) generated = '' sentence = text[start_index: start_index + maxlen] generated += sentence print('----- Generating with seed: "' + sentence + '"') sys.stdout.write(generated) for i in range(400): x = np.zeros((1, maxlen, len(chars))) for t, char in enumerate(sentence): x[0, t, char_indices[char]] = 1. preds = model.predict(x, verbose=0)[0] next_index = sample(preds, diversity) next_char = indices_char[next_index] generated += next_char sentence = sentence[1:] + next_char sys.stdout.write(next_char) sys.stdout.flush() print() ```
github_jupyter
#Plotting Velocities and Tracers on Vertical Planes This notebook contains discussion, examples, and best practices for plotting velocity field and tracer results from NEMO on vertical planes. Topics include: * Plotting colour meshes of velocity on vertical sections through the domain * Using `nc_tools.timestamp()` to get time stamps from results datasets * Plotting salinity as a colour mesh on thalweg section We'll start with the usual imports, and activation of the Matplotlib inline backend: ``` from __future__ import division, print_function import matplotlib.pyplot as plt import netCDF4 as nc import numpy as np from salishsea_tools import ( nc_tools, viz_tools, ) %matplotlib inline ``` Let's look at the results from the 17-Dec-2003 to 26-Dec-2003 spin-up run. We'll also load the bathymetry so that we can plot land masks. ``` u_vel = nc.Dataset('/ocean/dlatorne/MEOPAR/SalishSea/results/spin-up/17dec26dec/SalishSea_1d_20031217_20031226_grid_U.nc') v_vel = nc.Dataset('/ocean/dlatorne/MEOPAR/SalishSea/results/spin-up/17dec26dec/SalishSea_1d_20031217_20031226_grid_V.nc') ugrid = u_vel.variables['vozocrtx'] vgrid = v_vel.variables['vomecrty'] zlevels = v_vel.variables['depthv'] timesteps = v_vel.variables['time_counter'] grid = nc.Dataset('/data/dlatorne/MEOPAR/NEMO-forcing/grid/bathy_meter_SalishSea2.nc') ``` ##Velocity Component Colour Mesh on a Vertical Plane There's really not much new involved in plotting on vertical planes compared to the horizontal plane plots that we've done in the previous notebooks. Here's are plots of the v velocity component crossing a vertical plane defined by a section line running from just north of Howe Sound to a little north of Nanaimo, and the surface current streamlines in the area with the section line shown for orientation. Things to note: * The use of the `invert_yaxis()` method on the vertical plane y-axis to make the depth scale go from 0 at the surface to positive depths below, and the resulting reversal of the limit values passed to the `set_ylim()` method * The use of the `set_axis_bgcolor()` method to make the extension of the axis area below the maximum depth appear consistent with the rest of the non-water regions ``` fig, (axl, axr) = plt.subplots(1, 2, figsize=(16, 8)) land_colour = 'burlywood' # Define the v velocity component slice to plot t, zmax, ylocn = -1, 41, 500 section_slice = np.arange(208, 293) timestamp = nc_tools.timestamp(v_vel, t) # Slice and mask the v array vgrid_tzyx = np.ma.masked_values(vgrid[t, :zmax, ylocn, section_slice], 0) # Plot the v velocity colour mesh cmap = plt.get_cmap('bwr') cmap.set_bad(land_colour) mesh = axl.pcolormesh( section_slice[:], zlevels[:zmax], vgrid_tzyx, cmap=cmap, vmin=-0.1, vmax=0.1, ) axl.invert_yaxis() cbar = fig.colorbar(mesh, ax=axl) cbar.set_label('v Velocity [{.units}]'.format(vgrid)) # Axes labels and title axl.set_xlabel('x Index') axl.set_ylabel('{0.long_name} [{0.units}]'.format(zlevels)) axl.set_title( '24h Average v Velocity at y={y} on {date}' .format(y=ylocn, date=timestamp.format('DD-MMM-YYYY'))) # Axes limits and grid axl.set_xlim(section_slice[1], section_slice[-1]) axl.set_ylim(zlevels[zmax - 2] + 10, 0) axl.set_axis_bgcolor(land_colour) axl.grid() # Define surface current magnitude slice x_slice = np.arange(150, 350) y_slice = np.arange(425, 575) # Slice and mask the u and v arrays ugrid_tzyx = np.ma.masked_values(ugrid[t, 0, y_slice, x_slice], 0) vgrid_tzyx = np.ma.masked_values(vgrid[t, 0, y_slice, x_slice], 0) # "Unstagger" the velocity values by interpolating them to the T-grid points # and calculate the surface current speeds u_tzyx, v_tzyx = viz_tools.unstagger(ugrid_tzyx, vgrid_tzyx) speeds = np.sqrt(np.square(u_tzyx) + np.square(v_tzyx)) max_speed = viz_tools.calc_abs_max(speeds) # Plot section line on surface streamlines map viz_tools.set_aspect(axr) axr.streamplot( x_slice[1:], y_slice[1:], u_tzyx, v_tzyx, linewidth=7*speeds/max_speed, ) viz_tools.plot_land_mask( axr, grid, xslice=x_slice, yslice=y_slice, color=land_colour) axr.plot( section_slice, ylocn*np.ones_like(section_slice), linestyle='solid', linewidth=3, color='black', label='Section Line', ) # Axes labels and title axr.set_xlabel('x Index') axr.set_ylabel('y Index') axr.set_title( '24h Average Surface Streamlines on {date}' .format(date=timestamp.format('DD-MMM-YYYY'))) legend = axr.legend(loc='best', fancybox=True, framealpha=0.25) # Axes limits and grid axr.set_xlim(x_slice[0], x_slice[-1]) axr.set_ylim(y_slice[0], y_slice[-1]) axr.grid() ``` The code above uses the `nc_tools.timestamp()` function to obtain the time stamp of the plotted results from the dataset and formats that value as a date in the axes titles. Documentation for `nc_tools.timestamp()` (and the other functions in the `nc_tools` module) is available at http://salishsea-meopar-tools.readthedocs.org/en/latest/SalishSeaTools/salishsea-tools.html#nc_tools.timestamp and via shift-TAB or the `help()` command in notebooks: ``` help(nc_tools.timestamp) ``` Passing a tuple or list of time indices; e.g. `[0, 3, 6, 9]`, to `nc_tools.timestamp()` causes a list of time stamp values to be returned The time stamp value(s) returned are [Arrow](http://crsmithdev.com/arrow/) instances. The `format()` method can be used to produce a string representation of a time stamp, for example: ``` timestamp.format('YYYY-MM-DD HH:mm:ss') ``` NEMO results are calculated using the UTC time zone but `Arrow` time stamps can easily be converted to other time zones: ``` timestamp.to('Canada/Pacific') ``` Please see the [Arrow](http://crsmithdev.com/arrow/) docs for other useful methods and ways of manipulating dates and times in Python. ##Salinity Colour Mesh on Thalweg Section For this plot we'll look at results from the spin-up run that includes 27-Sep-2003 because it shows deep water renewal in the Strait of Georgia. ``` tracers = nc.Dataset('/ocean/dlatorne/MEOPAR/SalishSea/results/spin-up/18sep27sep/SalishSea_1d_20030918_20030927_grid_T.nc') ``` The salinity netCDF4 variables needs to be changed to a NumPy array. ``` sal = tracers.variables['vosaline'] npsal = sal[:] zlevels = tracers.variables['deptht'] ``` The thalweg is a line that connects the deepest points of successive cross-sections through the model domain. The grid indices of the thalweg are calculated in the [compute_thalweg.ipynb](https://nbviewer.jupyter.org/github/SalishSeaCast/tools/blob/master/analysis_tools/compute_thalweg.ipynb) notebook and stored as `(j, i)` ordered pairs in the `tools/analysis_tools/thalweg.txt/thalweg.txt` file: ``` !head thalweg.txt ``` We use the NumPy `loadtxt()` function to read the thalweg points into a pair of arrays. The `unpack` argument causes the result to be transposed from an array of ordered pairs to arrays of `j` and `i` values. ``` thalweg = np.loadtxt('/data/dlatorne/MEOPAR/tools/bathymetry/thalweg_working.txt', dtype=int, unpack=True) ``` Plotting salinity along the thalweg is an example of plotting a model result quantity on an arbitrary section through the domain. ``` # Set up the figure and axes fig, (axl, axcb, axr) = plt.subplots(1, 3, figsize=(16, 8)) land_colour = 'burlywood' for ax in (axl, axr): ax.set_axis_bgcolor(land_colour) axl.set_position((0.125, 0.125, 0.6, 0.775)) axcb.set_position((0.73, 0.125, 0.02, 0.775)) axr.set_position((0.83, 0.125, 0.2, 0.775)) # Plot thalweg points on bathymetry map viz_tools.set_aspect(axr) cmap = plt.get_cmap('winter_r') cmap.set_bad(land_colour) bathy = grid.variables['Bathymetry'] x_slice = np.arange(bathy.shape[1]) y_slice = np.arange(200, 800) axr.pcolormesh(x_slice, y_slice, bathy[y_slice, x_slice], cmap=cmap) axr.plot( thalweg[1], thalweg[0], linestyle='-', marker='+', color='red', label='Thalweg Points', ) legend = axr.legend(loc='best', fancybox=True, framealpha=0.25) axr.set_xlabel('x Index') axr.set_ylabel('y Index') axr.grid() # Plot 24h average salinity at all depths along thalweg line t = -1 # 27-Dec-2003 smin, smax, dels = 26, 34, 0.5 cmap = plt.get_cmap('rainbow') cmap.set_bad(land_colour) sal_0 = npsal[t, :, thalweg[0], thalweg[1]] sal_tzyx = np.ma.masked_values(sal_0, 0) x, z = np.meshgrid(np.arange(thalweg.shape[1]), zlevels) mesh = axl.pcolormesh(x, z, sal_tzyx.T, cmap=cmap, vmin=smin, vmax=smax) cbar = plt.colorbar(mesh, cax=axcb) cbar.set_label('Practical Salinity') clines = axl.contour(x, z, sal_tzyx.T, np.arange(smin, smax, dels), colors='black') axl.clabel(clines, fmt='%1.1f', inline=True) axl.invert_yaxis() axl.set_xlim(0, thalweg[0][-1]) axl.set_xlabel('x Index') axl.set_ylabel('{0.long_name} [{0.units}]'.format(zlevels)) axl.grid() ```
github_jupyter
**This notebook is an exercise in the [Natural Language Processing](https://www.kaggle.com/learn/natural-language-processing) course. You can reference the tutorial at [this link](https://www.kaggle.com/matleonard/word-vectors).** --- # Vectorizing Language Embeddings are both conceptually clever and practically effective. So let's try them for the sentiment analysis model you built for the restaurant. Then you can find the most similar review in the data set given some example text. It's a task where you can easily judge for yourself how well the embeddings work. ``` %matplotlib inline import matplotlib.pyplot as plt import numpy as np import pandas as pd import spacy # Set up code checking from learntools.core import binder binder.bind(globals()) from learntools.nlp.ex3 import * print("\nSetup complete") # Load the large model to get the vectors nlp = spacy.load('en_core_web_lg') review_data = pd.read_csv('../input/nlp-course/yelp_ratings.csv') review_data.head() ``` Here's an example of loading some document vectors. Calculating 44,500 document vectors takes about 20 minutes, so we'll get only the first 100. To save time, we'll load pre-saved document vectors for the hands-on coding exercises. ``` reviews = review_data[:100] # We just want the vectors so we can turn off other models in the pipeline with nlp.disable_pipes(): vectors = np.array([nlp(review.text).vector for idx, review in reviews.iterrows()]) vectors.shape ``` The result is a matrix of 100 rows and 300 columns. Why 100 rows? Because we have 1 row for each column. Why 300 columns? This is the same length as word vectors. See if you can figure out why document vectors have the same length as word vectors (some knowledge of linear algebra or vector math would be needed to figure this out). Go ahead and run the following cell to load in the rest of the document vectors. ``` # Loading all document vectors from file vectors = np.load('../input/nlp-course/review_vectors.npy') ``` # 1) Training a Model on Document Vectors Next you'll train a `LinearSVC` model using the document vectors. It runs pretty quick and works well in high dimensional settings like you have here. After running the LinearSVC model, you might try experimenting with other types of models to see whether it improves your results. ``` from sklearn.svm import LinearSVC from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(vectors, review_data.sentiment, test_size=0.1, random_state=1) # Create the LinearSVC model model = LinearSVC(random_state=1, dual=False) # Fit the model model.fit(X_train, y_train) # Uncomment and run to see model accuracy print(f'Model test accuracy: {model.score(X_test, y_test)*100:.3f}%') # Uncomment to check your work q_1.check() # Lines below will give you a hint or solution code #q_1.hint() #q_1.solution() # Scratch space in case you want to experiment with other models from sklearn.neural_network import MLPClassifier second_model = MLPClassifier(hidden_layer_sizes=(128,32,), early_stopping=True, random_state=1) second_model.fit(X_train, y_train) print(f'Model test accuracy: {second_model.score(X_test, y_test)*100:.3f}%') ``` # Document Similarity For the same tea house review, find the most similar review in the dataset using cosine similarity. # 2) Centering the Vectors Sometimes people center document vectors when calculating similarities. That is, they calculate the mean vector from all documents, and they subtract this from each individual document's vector. Why do you think this could help with similarity metrics? Run the following line after you've decided your answer. ``` # Check your answer (Run this code cell to receive credit!) #q_2.solution() q_2.check() ``` # 3) Find the most similar review Given an example review below, find the most similar document within the Yelp dataset using the cosine similarity. ``` review = """I absolutely love this place. The 360 degree glass windows with the Yerba buena garden view, tea pots all around and the smell of fresh tea everywhere transports you to what feels like a different zen zone within the city. I know the price is slightly more compared to the normal American size, however the food is very wholesome, the tea selection is incredible and I know service can be hit or miss often but it was on point during our most recent visit. Definitely recommend! I would especially recommend the butternut squash gyoza.""" def cosine_similarity(a, b): return np.dot(a, b)/np.sqrt(a.dot(a)*b.dot(b)) review_vec = nlp(review).vector ## Center the document vectors # Calculate the mean for the document vectors, should have shape (300,) vec_mean = vectors.mean(axis=0) # Subtract the mean from the vectors centered = vectors - vec_mean # Calculate similarities for each document in the dataset # Make sure to subtract the mean from the review vector review_centered = review_vec - vec_mean sims = np.array([cosine_similarity(v, review_centered) for v in centered]) # Get the index for the most similar document most_similar = sims.argmax() # Uncomment to check your work q_3.check() # Lines below will give you a hint or solution code #q_3.hint() #q_3.solution() print(review_data.iloc[most_similar].text) ``` Even though there are many different sorts of businesses in our Yelp dataset, you should have found another tea shop. # 4) Looking at similar reviews If you look at other similar reviews, you'll see many coffee shops. Why do you think reviews for coffee are similar to the example review which mentions only tea? ``` # Check your answer (Run this code cell to receive credit!) #q_4.solution() q_4.check() ``` # Congratulations! You've finished the NLP course. It's an exciting field that will help you make use of vast amounts of data you didn't know how to work with before. This course should be just your introduction. Try a project **[with text](https://www.kaggle.com/datasets?tags=14104-text+data)**. You'll have fun with it, and your skills will continue growing. --- *Have questions or comments? Visit the [Learn Discussion forum](https://www.kaggle.com/learn-forum/161466) to chat with other Learners.*
github_jupyter
# TV Script Generation In this project, you'll generate your own [Simpsons](https://en.wikipedia.org/wiki/The_Simpsons) TV scripts using RNNs. You'll be using part of the [Simpsons dataset](https://www.kaggle.com/wcukierski/the-simpsons-by-the-data) of scripts from 27 seasons. The Neural Network you'll build will generate a new TV script for a scene at [Moe's Tavern](https://simpsonswiki.com/wiki/Moe's_Tavern). ## Get the Data The data is already provided for you. You'll be using a subset of the original dataset. It consists of only the scenes in Moe's Tavern. This doesn't include other versions of the tavern, like "Moe's Cavern", "Flaming Moe's", "Uncle Moe's Family Feed-Bag", etc.. ``` """ DON'T MODIFY ANYTHING IN THIS CELL """ import helper data_dir = './data/simpsons/moes_tavern_lines.txt' text = helper.load_data(data_dir) # Ignore notice, since we don't use it for analysing the data text = text[81:] ``` ## Explore the Data Play around with `view_sentence_range` to view different parts of the data. ``` view_sentence_range = (0, 10) """ DON'T MODIFY ANYTHING IN THIS CELL """ import numpy as np print('Dataset Stats') print('Roughly the number of unique words: {}'.format(len({word: None for word in text.split()}))) scenes = text.split('\n\n') print('Number of scenes: {}'.format(len(scenes))) sentence_count_scene = [scene.count('\n') for scene in scenes] print('Average number of sentences in each scene: {}'.format(np.average(sentence_count_scene))) sentences = [sentence for scene in scenes for sentence in scene.split('\n')] print('Number of lines: {}'.format(len(sentences))) word_count_sentence = [len(sentence.split()) for sentence in sentences] print('Average number of words in each line: {}'.format(np.average(word_count_sentence))) print() print('The sentences {} to {}:'.format(*view_sentence_range)) print('\n'.join(text.split('\n')[view_sentence_range[0]:view_sentence_range[1]])) ``` ## Implement Preprocessing Functions The first thing to do to any dataset is preprocessing. Implement the following preprocessing functions below: - Lookup Table - Tokenize Punctuation ### Lookup Table To create a word embedding, you first need to transform the words to ids. In this function, create two dictionaries: - Dictionary to go from the words to an id, we'll call `vocab_to_int` - Dictionary to go from the id to word, we'll call `int_to_vocab` Return these dictionaries in the following tuple `(vocab_to_int, int_to_vocab)` ``` import numpy as np import problem_unittests as tests def create_lookup_tables(text): """ Create lookup tables for vocabulary :param text: The text of tv scripts split into words :return: A tuple of dicts (vocab_to_int, int_to_vocab) """ # TODO: Implement Function vocab = set(text) #print(vocab) vocab_to_int = {word:index for index, word in enumerate(vocab)} int_to_vocab = {index:word for index, word in enumerate(vocab)} '''print(vocab_to_int) for dic,i in enumerate(vocab_to_int): print(dic,int_to_vocab[dic])''' return vocab_to_int, int_to_vocab """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_create_lookup_tables(create_lookup_tables) ``` ### Tokenize Punctuation We'll be splitting the script into a word array using spaces as delimiters. However, punctuations like periods and exclamation marks make it hard for the neural network to distinguish between the word "bye" and "bye!". Implement the function `token_lookup` to return a dict that will be used to tokenize symbols like "!" into "||Exclamation_Mark||". Create a dictionary for the following symbols where the symbol is the key and value is the token: - Period ( . ) - Comma ( , ) - Quotation Mark ( " ) - Semicolon ( ; ) - Exclamation mark ( ! ) - Question mark ( ? ) - Left Parentheses ( ( ) - Right Parentheses ( ) ) - Dash ( -- ) - Return ( \n ) This dictionary will be used to token the symbols and add the delimiter (space) around it. This separates the symbols as it's own word, making it easier for the neural network to predict on the next word. Make sure you don't use a token that could be confused as a word. Instead of using the token "dash", try using something like "||dash||". ``` def token_lookup(): """ Generate a dict to turn punctuation into a token. :return: Tokenize dictionary where the key is the punctuation and the value is the token """ # TODO: Implement Function return {key: "||" + value + "||" for key, value in {".": "Period_Mark", \ ",": "Comma_Mark", \ '"': "Quotation_Mark", \ ";": "Semicolon_Mark", \ "!": "Exclamation_Mark", \ "?": "Question_Mark", \ "(": "Left_Bracket", \ ")": "Right_Bracket", \ "--":"Dash_Mark", \ "\n":"Return_Mark" \ }.items()} """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_tokenize(token_lookup) ``` ## Preprocess all the data and save it Running the code cell below will preprocess all the data and save it to file. ``` """ DON'T MODIFY ANYTHING IN THIS CELL """ # Preprocess Training, Validation, and Testing Data helper.preprocess_and_save_data(data_dir, token_lookup, create_lookup_tables) ``` # Check Point This is your first checkpoint. If you ever decide to come back to this notebook or have to restart the notebook, you can start from here. The preprocessed data has been saved to disk. ``` """ DON'T MODIFY ANYTHING IN THIS CELL """ import helper import numpy as np import problem_unittests as tests int_text, vocab_to_int, int_to_vocab, token_dict = helper.load_preprocess() ``` ## Build the Neural Network You'll build the components necessary to build a RNN by implementing the following functions below: - get_inputs - get_init_cell - get_embed - build_rnn - build_nn - get_batches ### Check the Version of TensorFlow and Access to GPU ``` """ DON'T MODIFY ANYTHING IN THIS CELL """ from distutils.version import LooseVersion import warnings import tensorflow as tf # Check TensorFlow Version assert LooseVersion(tf.__version__) >= LooseVersion('1.0'), 'Please use TensorFlow version 1.0 or newer' print('TensorFlow Version: {}'.format(tf.__version__)) # Check for a GPU if not tf.test.gpu_device_name(): warnings.warn('No GPU found. Please use a GPU to train your neural network.') else: print('Default GPU Device: {}'.format(tf.test.gpu_device_name())) ``` ### Input Implement the `get_inputs()` function to create TF Placeholders for the Neural Network. It should create the following placeholders: - Input text placeholder named "input" using the [TF Placeholder](https://www.tensorflow.org/api_docs/python/tf/placeholder) `name` parameter. - Targets placeholder - Learning Rate placeholder Return the placeholders in the following tuple `(Input, Targets, LearningRate)` ``` def get_inputs(): """ Create TF Placeholders for input, targets, and learning rate. :return: Tuple (input, targets, learning rate) """ # TODO: Implement Function inputs = tf.placeholder(tf.int32, [None, None], name = 'input') targets = tf.placeholder(tf.int32, [None, None], name= 'targets') learning_rate = tf.placeholder(tf.float32, name = 'learning_rate') return inputs, targets, learning_rate """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_get_inputs(get_inputs) ``` ### Build RNN Cell and Initialize Stack one or more [`BasicLSTMCells`](https://www.tensorflow.org/api_docs/python/tf/contrib/rnn/BasicLSTMCell) in a [`MultiRNNCell`](https://www.tensorflow.org/api_docs/python/tf/contrib/rnn/MultiRNNCell). - The Rnn size should be set using `rnn_size` - Initalize Cell State using the MultiRNNCell's [`zero_state()`](https://www.tensorflow.org/api_docs/python/tf/contrib/rnn/MultiRNNCell#zero_state) function - Apply the name "initial_state" to the initial state using [`tf.identity()`](https://www.tensorflow.org/api_docs/python/tf/identity) Return the cell and initial state in the following tuple `(Cell, InitialState)` ``` def get_init_cell(batch_size, rnn_size): """ Create an RNN Cell and initialize it. :param batch_size: Size of batches :param rnn_size: Size of RNNs :return: Tuple (cell, initialize state) """ # TODO: Implement Function lstmLayer = 3 cell = tf.contrib.rnn.BasicLSTMCell(rnn_size) cell = tf.contrib.rnn.MultiRNNCell([cell], rnn_size) initializedState = cell.zero_state(batch_size, tf.float32) initializedState = tf.identity(initializedState,name = "initial_state") return cell, initializedState """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_get_init_cell(get_init_cell) ``` ### Word Embedding Apply embedding to `input_data` using TensorFlow. Return the embedded sequence. ``` def get_embed(input_data, vocab_size, embed_dim): """ Create embedding for <input_data>. :param input_data: TF placeholder for text input. :param vocab_size: Number of words in vocabulary. :param embed_dim: Number of embedding dimensions :return: Embedded input. """ # TODO: Implement Function embedding = tf.Variable(tf.random_uniform((vocab_size,embed_dim),-1,1)) embedded = tf.nn.embedding_lookup(embedding,input_data) return embedded """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_get_embed(get_embed) ``` ### Build RNN You created a RNN Cell in the `get_init_cell()` function. Time to use the cell to create a RNN. - Build the RNN using the [`tf.nn.dynamic_rnn()`](https://www.tensorflow.org/api_docs/python/tf/nn/dynamic_rnn) - Apply the name "final_state" to the final state using [`tf.identity()`](https://www.tensorflow.org/api_docs/python/tf/identity) Return the outputs and final_state state in the following tuple `(Outputs, FinalState)` ``` def build_rnn(cell, inputs): """ Create a RNN using a RNN Cell :param cell: RNN Cell :param inputs: Input text data :return: Tuple (Outputs, Final State) """ # TODO: Implement Function outputs, finalState = tf.nn.dynamic_rnn(cell,inputs=inputs, dtype=tf.float32) finalState = tf.identity(finalState,name = "final_state") return outputs, finalState """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_build_rnn(build_rnn) ``` ### Build the Neural Network Apply the functions you implemented above to: - Apply embedding to `input_data` using your `get_embed(input_data, vocab_size, embed_dim)` function. - Build RNN using `cell` and your `build_rnn(cell, inputs)` function. - Apply a fully connected layer with a linear activation and `vocab_size` as the number of outputs. Return the logits and final state in the following tuple (Logits, FinalState) ``` def build_nn(cell, rnn_size, input_data, vocab_size, embed_dim): """ Build part of the neural network :param cell: RNN cell :param rnn_size: Size of rnns :param input_data: Input data :param vocab_size: Vocabulary size :param embed_dim: Number of embedding dimensions :return: Tuple (Logits, FinalState) """ # TODO: Implement Function inputs = get_embed(input_data, vocab_size, embed_dim) outputs,finalState = build_rnn(cell, inputs) logits = tf.contrib.layers.fully_connected(outputs, vocab_size,activation_fn=None, weights_initializer=tf.truncated_normal_initializer(mean = 0, stddev=.1), biases_initializer=tf.zeros_initializer()) return (logits, finalState) """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_build_nn(build_nn) ``` ### Batches Implement `get_batches` to create batches of input and targets using `int_text`. The batches should be a Numpy array with the shape `(number of batches, 2, batch size, sequence length)`. Each batch contains two elements: - The first element is a single batch of **input** with the shape `[batch size, sequence length]` - The second element is a single batch of **targets** with the shape `[batch size, sequence length]` If you can't fill the last batch with enough data, drop the last batch. For exmple, `get_batches([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], 3, 2)` would return a Numpy array of the following: ``` [ # First Batch [ # Batch of Input [[ 1 2], [ 7 8], [13 14]] # Batch of targets [[ 2 3], [ 8 9], [14 15]] ] # Second Batch [ # Batch of Input [[ 3 4], [ 9 10], [15 16]] # Batch of targets [[ 4 5], [10 11], [16 17]] ] # Third Batch [ # Batch of Input [[ 5 6], [11 12], [17 18]] # Batch of targets [[ 6 7], [12 13], [18 1]] ] ] ``` Notice that the last target value in the last batch is the first input value of the first batch. In this case, `1`. This is a common technique used when creating sequence batches, although it is rather unintuitive. ``` def get_batches(int_text, batch_size, seq_length): """ Return batches of input and target :param int_text: Text with the words replaced by their ids :param batch_size: The size of batch :param seq_length: The length of sequence :return: Batches as a Numpy array """ # TODO: Implement Function n_batches = len(int_text) // (batch_size * seq_length) inputs = np.array(int_text[: n_batches * batch_size * seq_length]) targets = np.array(int_text[1: n_batches * batch_size * seq_length + 1]) targets[-1] = inputs[0] inputs_batches = np.split(inputs.reshape(batch_size, -1), n_batches, 1) targets_batches = np.split(targets.reshape(batch_size, -1), n_batches, 1) return np.array(list(zip(inputs_batches, targets_batches))) """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_get_batches(get_batches) ``` ## Neural Network Training ### Hyperparameters Tune the following parameters: - Set `num_epochs` to the number of epochs. - Set `batch_size` to the batch size. - Set `rnn_size` to the size of the RNNs. - Set `embed_dim` to the size of the embedding. - Set `seq_length` to the length of sequence. - Set `learning_rate` to the learning rate. - Set `show_every_n_batches` to the number of batches the neural network should print progress. ``` # Number of Epochs num_epochs = 200 # Batch Size batch_size = 256 # RNN Size rnn_size = 512 # Embedding Dimension Size embed_dim = 512 # Sequence Length seq_length = 20 # Learning Rate learning_rate = .001 # Show stats for every n number of batches show_every_n_batches = 32 """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ save_dir = './save' ``` ### Build the Graph Build the graph using the neural network you implemented. ``` """ DON'T MODIFY ANYTHING IN THIS CELL """ from tensorflow.contrib import seq2seq train_graph = tf.Graph() with train_graph.as_default(): vocab_size = len(int_to_vocab) input_text, targets, lr = get_inputs() input_data_shape = tf.shape(input_text) cell, initial_state = get_init_cell(input_data_shape[0], rnn_size) logits, final_state = build_nn(cell, rnn_size, input_text, vocab_size, embed_dim) # Probabilities for generating words probs = tf.nn.softmax(logits, name='probs') # Loss function cost = seq2seq.sequence_loss( logits, targets, tf.ones([input_data_shape[0], input_data_shape[1]])) # Optimizer optimizer = tf.train.AdamOptimizer(lr) # Gradient Clipping gradients = optimizer.compute_gradients(cost) capped_gradients = [(tf.clip_by_value(grad, -1., 1.), var) for grad, var in gradients if grad is not None] train_op = optimizer.apply_gradients(capped_gradients) ``` ## Train Train the neural network on the preprocessed data. If you have a hard time getting a good loss, check the [forums](https://discussions.udacity.com/) to see if anyone is having the same problem. ``` """ DON'T MODIFY ANYTHING IN THIS CELL """ batches = get_batches(int_text, batch_size, seq_length) with tf.Session(graph=train_graph) as sess: sess.run(tf.global_variables_initializer()) for epoch_i in range(num_epochs): state = sess.run(initial_state, {input_text: batches[0][0]}) for batch_i, (x, y) in enumerate(batches): feed = { input_text: x, targets: y, initial_state: state, lr: learning_rate} train_loss, state, _ = sess.run([cost, final_state, train_op], feed) # Show every <show_every_n_batches> batches if (epoch_i * len(batches) + batch_i) % show_every_n_batches == 0: print('Epoch {:>3} Batch {:>4}/{} train_loss = {:.3f}'.format( epoch_i, batch_i, len(batches), train_loss)) # Save Model saver = tf.train.Saver() saver.save(sess, save_dir) print('Model Trained and Saved') ``` ## Save Parameters Save `seq_length` and `save_dir` for generating a new TV script. ``` """ DON'T MODIFY ANYTHING IN THIS CELL """ # Save parameters for checkpoint helper.save_params((seq_length, save_dir)) ``` # Checkpoint ``` """ DON'T MODIFY ANYTHING IN THIS CELL """ import tensorflow as tf import numpy as np import helper import problem_unittests as tests _, vocab_to_int, int_to_vocab, token_dict = helper.load_preprocess() seq_length, load_dir = helper.load_params() ``` ## Implement Generate Functions ### Get Tensors Get tensors from `loaded_graph` using the function [`get_tensor_by_name()`](https://www.tensorflow.org/api_docs/python/tf/Graph#get_tensor_by_name). Get the tensors using the following names: - "input:0" - "initial_state:0" - "final_state:0" - "probs:0" Return the tensors in the following tuple `(InputTensor, InitialStateTensor, FinalStateTensor, ProbsTensor)` ``` def get_tensors(loaded_graph): """ Get input, initial state, final state, and probabilities tensor from <loaded_graph> :param loaded_graph: TensorFlow graph loaded from file :return: Tuple (InputTensor, InitialStateTensor, FinalStateTensor, ProbsTensor) """ InputTensor = loaded_graph.get_tensor_by_name("input:0") InitialStateTensor = loaded_graph.get_tensor_by_name("initial_state:0") FinalStateTensor = loaded_graph.get_tensor_by_name("final_state:0") ProbsTensor = loaded_graph.get_tensor_by_name("probs:0") return InputTensor,InitialStateTensor, FinalStateTensor,ProbsTensor """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_get_tensors(get_tensors) ``` ### Choose Word Implement the `pick_word()` function to select the next word using `probabilities`. ``` def pick_word(probabilities, int_to_vocab): """ Pick the next word in the generated text :param probabilities: Probabilites of the next word :param int_to_vocab: Dictionary of word ids as the keys and words as the values :return: String of the predicted word """ return int_to_vocab[probabilities.argmax()] """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_pick_word(pick_word) ``` ## Generate TV Script This will generate the TV script for you. Set `gen_length` to the length of TV script you want to generate. ``` gen_length = 200 # homer_simpson, moe_szyslak, or Barney_Gumble prime_word = 'moe_szyslak' """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ loaded_graph = tf.Graph() with tf.Session(graph=loaded_graph) as sess: # Load saved model loader = tf.train.import_meta_graph(load_dir + '.meta') loader.restore(sess, load_dir) # Get Tensors from loaded model input_text, initial_state, final_state, probs = get_tensors(loaded_graph) # Sentences generation setup gen_sentences = [prime_word + ':'] prev_state = sess.run(initial_state, {input_text: np.array([[1]])}) # Generate sentences for n in range(gen_length): # Dynamic Input dyn_input = [[vocab_to_int[word] for word in gen_sentences[-seq_length:]]] dyn_seq_length = len(dyn_input[0]) # Get Prediction probabilities, prev_state = sess.run( [probs, final_state], {input_text: dyn_input, initial_state: prev_state}) probabilities = probabilities[0] pred_word = pick_word(probabilities[dyn_seq_length-1], int_to_vocab) gen_sentences.append(pred_word) # Remove tokens tv_script = ' '.join(gen_sentences) for key, token in token_dict.items(): ending = ' ' if key in ['\n', '(', '"'] else '' tv_script = tv_script.replace(' ' + token.lower(), key) tv_script = tv_script.replace('\n ', '\n') tv_script = tv_script.replace('( ', '(') print(tv_script) ``` # The TV Script is Nonsensical It's ok if the TV script doesn't make any sense. We trained on less than a megabyte of text. In order to get good results, you'll have to use a smaller vocabulary or get more data. Luckly there's more data! As we mentioned in the begging of this project, this is a subset of [another dataset](https://www.kaggle.com/wcukierski/the-simpsons-by-the-data). We didn't have you train on all the data, because that would take too long. However, you are free to train your neural network on all the data. After you complete the project, of course. # Submitting This Project When submitting this project, make sure to run all the cells before saving the notebook. Save the notebook file as "dlnd_tv_script_generation.ipynb" and save it as a HTML file under "File" -> "Download as". Include the "helper.py" and "problem_unittests.py" files in your submission.
github_jupyter
# ETL Pipeline Preparation Follow the instructions below to help you create your ETL pipeline. ### 1. Import libraries and load datasets. - Import Python libraries - Load `messages.csv` into a dataframe and inspect the first few lines. - Load `categories.csv` into a dataframe and inspect the first few lines. ``` # import libraries import pandas as pd from sqlalchemy import create_engine # load messages dataset messages = pd.read_csv('messages.csv') messages.head() # load categories dataset categories = pd.read_csv('categories.csv') categories.head() ``` ### 2. Merge datasets. - Merge the messages and categories datasets using the common id - Assign this combined dataset to `df`, which will be cleaned in the following steps ``` # merge datasets df = pd.merge(messages, categories, on='id', how='inner') df.head() df.iloc[0, 4] ``` ### 3. Split `categories` into separate category columns. - Split the values in the `categories` column on the `;` character so that each value becomes a separate column. You'll find [this method](https://pandas.pydata.org/pandas-docs/version/0.23/generated/pandas.Series.str.split.html) very helpful! Make sure to set `expand=True`. - Use the first row of categories dataframe to create column names for the categories data. - Rename columns of `categories` with new column names. ``` # create a dataframe of the 36 individual category columns categories = df.categories.str.split(';', expand=True) categories.head() # select the first row of the categories dataframe row = categories.iloc[0, :] # use this row to extract a list of new column names for categories. # one way is to apply a lambda function that takes everything # up to the second to last character of each string with slicing category_colnames = [i[:-2] for i in row] print(category_colnames) # rename the columns of `categories` categories.columns = category_colnames categories.head() ``` ### 4. Convert category values to just numbers 0 or 1. - Iterate through the category columns in df to keep only the last character of each string (the 1 or 0). For example, `related-0` becomes `0`, `related-1` becomes `1`. Convert the string to a numeric value. - You can perform [normal string actions on Pandas Series](https://pandas.pydata.org/pandas-docs/stable/text.html#indexing-with-str), like indexing, by including `.str` after the Series. You may need to first convert the Series to be of type string, which you can do with `astype(str)`. ``` for column in categories: # set each value to be the last character of the string categories[column] = categories[column].str[-1] # convert column from string to numeric categories[column] = pd.to_numeric(categories[column], errors='coerce') categories.head() ``` ### 5. Replace `categories` column in `df` with new category columns. - Drop the categories column from the df dataframe since it is no longer needed. - Concatenate df and categories data frames. ``` df.columns # drop the original categories column from `df` df.drop(['categories'], axis=1, inplace=True) df.head() # concatenate the original dataframe with the new `categories` dataframe df = pd.concat([df, categories], axis=1) df.head() ``` ### 6. Remove duplicates. - Check how many duplicates are in this dataset. - Drop the duplicates. - Confirm duplicates were removed. ``` # check number of duplicates df.duplicated().sum() # drop duplicates df = df.drop_duplicates() # check number of duplicates df.duplicated().sum() ``` ### 7. Save the clean dataset into an sqlite database. You can do this with pandas [`to_sql` method](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_sql.html) combined with the SQLAlchemy library. Remember to import SQLAlchemy's `create_engine` in the first cell of this notebook to use it below. ``` engine = create_engine('sqlite:///disaster.db') df.to_sql('disaster', engine, index=False) ``` ### 8. Use this notebook to complete `etl_pipeline.py` Use the template file attached in the Resources folder to write a script that runs the steps above to create a database based on new datasets specified by the user. Alternatively, you can complete `etl_pipeline.py` in the classroom on the `Project Workspace IDE` coming later.
github_jupyter
``` # Phong_Thesis ``` # <center>Hệ thống tự động nhận diện trạng thái bãi đỗ xe</center> ## Lý thuyết Hệ thống được hình thành để phân loại các lot đậu xe thành 2 loại là trống hoặc đã có xe đỗ vào. Hệ thống này đặc biệt tối ưu với các bãi đỗ xe có camera ở các cột đèn hay có tầm nhìn thoáng và rộng. Hệ thống sử dụng sự kết hợp của toán tử Laplace để xác định viền ảnh, Haar classifier để nhận dạng đối tượng và theo dõi chuyển động để phân biệt giữa chỗ chưa đã có và chưa có xe đậu. Theo dõi chuyển động được thiết kế bằng việc sử dụng kĩ thuật background substraction (tách cảnh nền), contours (được hiểu đơn giản là một đường cong liên kết toàn bộ các điểm liên tục (dọc theo đường biên) mà có cùng màu sắc hoặc giá trị cường độ.) và Morphological operations cũng được sử dụng. ## Hướng tiếp cận Haar classifier đã được cân nhắc so sánh với SVM và HOG. Mặc dù HOG kết hợp với SVM sẽ mang lại độ chính xác cao hơn nếu so sánh với Haar nhưng việc các yêu cầu về quá trình xử lý của Haar là ít hơn rất nhiều so với HOG. Cuối cùng, Haar được lựa chọn để áp dụng vào hệ thống lần này.Chức năng phát hiện người qua đường của HOG được cài đặt sẵn trong opencv2 cũng được sử dụng nhưng nó được tắt đi vì nó sẽ làm chậm tốc độ xử lý của hệ thống. Để tăng độ chính xác trong việc phân loại các lot đỗ xe, toán tử Laplace được sử dụng. Threshold sẽ được thiết lập nơi khả năng hiện diện của xe là tối đa. Về cơ bản, các khu vực đậu xe xác định bằng tay và threshold được xác định bằng cách tính toán độ lớn của các cạnh bên trong chúng. Với một chiếc xe thì nó sẽ có một số cạnh đáng kể, trong khi chỗ đậu xe trống gần như là mịn màng. Đây là thực tế đằng sau việc sử dụng toán tử Laplace. Nếu khả năng hiện diện của một chiếc xe vượt quá threshold thì thuật toán phân loại ngay lập tức được áp dụng để phát hiện liệu nó có phải là một chiếc xe hay không. Bất cứ khi nào một sự thay đổi threshold được tìm thấy, thuật toán phân loại sẽ được gọi là để kiểm tra liệu đó là một chiếc xe hay không. Nếu được xác định là một chiếc xe thì nó sẽ được đánh dấu và quan sát chuyển động. Bất cứ khi nào có một chuyển động tại một điểm, thuật toán phân loại sẽ lại được gọi là để xác định sự hiện diện của xe. Vì vậy hệ thống đề xuất một sự kết hợp của phát hiện, theo dõi và phân loại để đạt được bãi đậu xe hiệu quả. ## Kết quả Một chương trình đã được em sử dụng để tính toán độ chính xác của thuật toán phân loại trong việc phát hiện xe. Chương trình áp dụng thuật toán phân loại vào một số khung hình được em cắt ra từ video và từ đó tính toán được tỉ lệ phát hiện chính xác số xe trong từng khung hình. Tiếp đó, nó sẽ hiển thị giá trị trung bình tỉ lệ của tất cả các khung hình. Kết quả thu được như sau: * Classifier được train với: **1562 Positives and 1772 Negatives** (có thể kiểm tra bằng việc click vào file 'haarTraining.bat'. Có thể kiểm tra ở mục screenshots để xem quá trình training) * Số khung hình được sử dụng: **5** * Trung bình tỉ lệ chính xác: **62.25%** (Xem phần tính toán bằng đoạn code được viết ở cuối cùng) Threshold được thay đổi và em nhận thấy rằng nó sẽ cho ra tỉ lệ chính xác nhật với giá trị là 2.7 (Vui lòng kiểm tra chương trình tính toán giá trị Threshold) Kết quả của thí nghiệm kiểm tra Threshold với tổng số xe là 120 * Threshold = 1.5 Số xe không được phân loại = 54 * Threshold = 2.0 Số xe không được phân loại = 39 * Threshold = 2.8 Số xe không được phân loại = 19 * Threshold = 3.0 Số xe không được phân loại = 24 * Threshold = 3.5 Số xe không được phân loại = 38 ## Code 1. Chương trình chính của hệ thống. 2. Chương trình cho phép ta thấy độ nhạy của thuật toán áp dụng đối với đường cao tốc M6, một trong những đường cao tốc có lưu lượng xe lớn nhất thế giới. 3. Chương trình cho phép ta xác định độ chính xác của thuật toán phân loại 4. Chương trình cho phép ta xác định các lot đỗ xe trên video bằng tay và lưu chúng vào yaml file để phục vụ cho hệ thống. 5. Chương trình giúp tính toán giá trị ước lượng của Threshold cho một video xác định. ``` """ Hướng dẫn: Escape key Nhấn Esc để thoát chương trình, lưu ý có thể ấn nhiều lần nếu lệnh không được thực hiện. Nhấn U để nhảy 500 frames và nhận J để nhảy 1000 frames. Các giá trị có thể chỉnh sửa được trong dictionary: 1. show_ids: Bật hoặc tắt id cuẩ từng lot 2. save_video: Lưu video được tạo ra từ chương trình 3. text_overlay: Hiển thị đếm frame ở góc trên màn hình. 4. motion_detection: Bật hoặc tắt motion detection 5. pedestrian detection: Khiến cho chương trình chậm vì function HOG trong opencv 6. min_area_motion_contour: Area cần nhỏ nhất cho motion 7. start_frame: Bắt đầu từ frame nào 8. park_laplacian_th: Thiết lập giá trị Threshold """ import yaml import numpy as np import cv2 fn = "phong_testvideo_03.mp4" #3 fn_yaml = "phong_yml_02.yml" fn_out = "phong_outputvideo_02.avi" cascade_src = 'phong_classifier.xml' car_cascade = cv2.CascadeClassifier(cascade_src) global_str = "Last change at: " change_pos = 0.00 dict = { 'text_overlay': True, 'parking_overlay': True, 'parking_id_overlay': True, 'parking_detection': True, 'motion_detection': False, 'pedestrian_detection': False, # mất nhiều power 'min_area_motion_contour': 500, 'park_laplacian_th': 2.7, 'park_sec_to_wait': 1, #thời gian đợi để thay đổi trạng thái của region 'start_frame': 0, # Bắt đầu từ frame nào 'show_ids': True, # Hiển thị id cho từng lot 'classifier_used': True, 'save_video': False } # Set từ video cap = cv2.VideoCapture(fn) video_info = { 'fps': cap.get(cv2.CAP_PROP_FPS), 'width': int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)*0.6), 'height': int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)*0.6), 'fourcc': cap.get(cv2.CAP_PROP_FOURCC), 'num_of_frames': int(cap.get(cv2.CAP_PROP_FRAME_COUNT))} cap.set(cv2.CAP_PROP_POS_FRAMES, dict['start_frame']) # Nhảy đến frame được xác định trước def run_classifier(img, id): cars = car_cascade.detectMultiScale(img, 1.1, 1) if cars == (): return False else: return True # Định nghĩa codec và tạo VideoWriter object if dict['save_video']: fourcc = cv2.VideoWriter_fourcc('X','V','I','D') # các lựa chọn: ('P','I','M','1'), ('D','I','V','X'), ('M','J','P','G'), ('X','V','I','D') out = cv2.VideoWriter(fn_out, -1, 25.0,(video_info['width'], video_info['height'])) # Khởi tạo HOG descriptor/person detector. Mất rất nhiều power cho quá trình này. if dict['pedestrian_detection']: hog = cv2.HOGDescriptor() hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector()) # Sử dụng Background subtraction tách cảnh nền. if dict['motion_detection']: fgbg = cv2.createBackgroundSubtractorMOG2(history=300, varThreshold=16, detectShadows=True) # Đọc file yaml (parking space polygons) with open(fn_yaml, 'r') as stream: parking_data = yaml.load(stream) parking_contours = [] parking_bounding_rects = [] parking_mask = [] parking_data_motion = [] if parking_data != None: for park in parking_data: points = np.array(park['points']) rect = cv2.boundingRect(points) points_shifted = points.copy() points_shifted[:,0] = points[:,0] - rect[0] # shift contour to region of interest points_shifted[:,1] = points[:,1] - rect[1] parking_contours.append(points) parking_bounding_rects.append(rect) mask = cv2.drawContours(np.zeros((rect[3], rect[2]), dtype=np.uint8), [points_shifted], contourIdx=-1, color=255, thickness=-1, lineType=cv2.LINE_8) mask = mask==255 parking_mask.append(mask) kernel_erode = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3)) # morphological kernel kernel_dilate = cv2.getStructuringElement(cv2.MORPH_RECT,(5,19)) if parking_data != None: parking_status = [False]*len(parking_data) parking_buffer = [None]*len(parking_data) def print_parkIDs(park, coor_points, frame_rev): moments = cv2.moments(coor_points) centroid = (int(moments['m10']/moments['m00'])-3, int(moments['m01']/moments['m00'])+3) # Gắn số vào các region được marked bằng tay cv2.putText(frame_rev, str(park['id']), (centroid[0]+1, centroid[1]+1), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,255,255), 1, cv2.LINE_AA) cv2.putText(frame_rev, str(park['id']), (centroid[0]-1, centroid[1]-1), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,255,255), 1, cv2.LINE_AA) cv2.putText(frame_rev, str(park['id']), (centroid[0]+1, centroid[1]-1), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,255,255), 1, cv2.LINE_AA) cv2.putText(frame_rev, str(park['id']), (centroid[0]-1, centroid[1]+1), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,255,255), 1, cv2.LINE_AA) cv2.putText(frame_rev, str(park['id']), centroid, cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,0,0), 1, cv2.LINE_AA) while(cap.isOpened()): current_count = 0 video_cur_pos = cap.get(cv2.CAP_PROP_POS_MSEC) / 1000.0 # Vị trí hiện tại của video file tính theo giây video_cur_frame = cap.get(cv2.CAP_PROP_POS_FRAMES) # Vị trí tính theo frame ret, frame_initial = cap.read() if ret == True: frame = cv2.resize(frame_initial, None, fx=0.6, fy=0.6) if ret == False: print("Video ended") break # Background Subtraction frame_blur = cv2.GaussianBlur(frame.copy(), (5,5), 3) frame_gray = cv2.cvtColor(frame_blur, cv2.COLOR_BGR2GRAY) frame_out = frame.copy() # Hiển thị số frame trên góc trái video if dict['text_overlay']: str_on_frame = "%d/%d" % (video_cur_frame, video_info['num_of_frames']) cv2.putText(frame_out, str_on_frame, (5,30), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0,255,255), 2, cv2.LINE_AA) cv2.putText(frame_out,global_str + str(round(change_pos,2)) + 'sec', (5, 60), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 0, 0), 2, cv2.LINE_AA) # motion detection cho mọi objects if dict['motion_detection']: fgmask = fgbg.apply(frame_blur) bw = np.uint8(fgmask==255)*255 bw = cv2.erode(bw, kernel_erode, iterations=1) bw = cv2.dilate(bw, kernel_dilate, iterations=1) (_, cnts, _) = cv2.findContours(bw.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # Áp loop cho contours for c in cnts: # Nếu contours quá nhỏ thì bỏ qua if cv2.contourArea(c) < dict['min_area_motion_contour']: continue (x, y, w, h) = cv2.boundingRect(c) cv2.rectangle(frame_out, (x, y), (x + w, y + h), (255, 0, 0), 1) # Detect xe và chỗ trống if dict['parking_detection']: for ind, park in enumerate(parking_data): points = np.array(park['points']) rect = parking_bounding_rects[ind] roi_gray = frame_gray[rect[1]:(rect[1]+rect[3]), rect[0]:(rect[0]+rect[2])] # crop ROI để tính toán nhanh hơn laplacian = cv2.Laplacian(roi_gray, cv2.CV_64F) points[:,0] = points[:,0] - rect[0] # Chuyển contour sang ROI points[:,1] = points[:,1] - rect[1] delta = np.mean(np.abs(laplacian * parking_mask[ind])) status = delta < dict['park_laplacian_th'] # Nếu phát hiện có sự thay đổi thì lưu thời gian lại if status != parking_status[ind] and parking_buffer[ind]==None: parking_buffer[ind] = video_cur_pos change_pos = video_cur_pos # Nếu trạng thái vẫn khác với cái đã được lưu và counter đang open elif status != parking_status[ind] and parking_buffer[ind]!=None: if video_cur_pos - parking_buffer[ind] > dict['park_sec_to_wait']: parking_status[ind] = status parking_buffer[ind] = None # Nếu trạng thái vẫn như vậy và counter đang open elif status == parking_status[ind] and parking_buffer[ind]!=None: parking_buffer[ind] = None # Thay đổi màu và trạng thái hiển thị trên section phía trên if dict['parking_overlay']: for ind, park in enumerate(parking_data): points = np.array(park['points']) if parking_status[ind]: color = (0,255,0) rect = parking_bounding_rects[ind] roi_gray_ov = frame_gray[rect[1]:(rect[1] + rect[3]), rect[0]:(rect[0] + rect[2])] # crop ROI để tính toán nhanh hơn res = run_classifier(roi_gray_ov, ind) current_count += 1 if res: parking_data_motion.append(parking_data[ind]) color = (0,0,255) else: color = (0,0,255) cv2.drawContours(frame_out, [points], contourIdx=-1, color=color, thickness=2, lineType=cv2.LINE_8) if dict['show_ids']: print_parkIDs(park, points, frame_out) #Hiển thị số lot trống trong frame cv2.putText(frame_out,'Vacant spots in frame: ' + str(current_count),(7,85),cv2.FONT_HERSHEY_SIMPLEX,0.728,(98,189,184),2,cv2.LINE_AA) if parking_data_motion != []: for index, park_coord in enumerate(parking_data_motion): points = np.array(park_coord['points']) color = (0, 0, 255) recta = parking_bounding_rects[ind] roi_gray1 = frame_gray[recta[1]:(recta[1] + recta[3]), recta[0]:(recta[0] + recta[2])] # crop ROI để tính toán nhanh hơn fgbg1 = cv2.createBackgroundSubtractorMOG2(history=300, varThreshold=16, detectShadows=True) roi_gray1_blur = cv2.GaussianBlur(roi_gray1.copy(), (5, 5), 3) fgmask1 = fgbg1.apply(roi_gray1_blur) bw1 = np.uint8(fgmask1 == 255) * 255 bw1 = cv2.erode(bw1, kernel_erode, iterations=1) bw1 = cv2.dilate(bw1, kernel_dilate, iterations=1) (_, cnts1, _) = cv2.findContours(bw1.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # Áp loop cho contours for c in cnts1: print(cv2.contourArea(c)) # Nếu contours quá nhỏ thì bỏ qua if cv2.contourArea(c) < 4: continue (x, y, w, h) = cv2.boundingRect(c) classifier_result1 = run_classifier(roi_gray1, index) if classifier_result1: color = (0, 0, 255) # Đỏ nếu có xe else: color = (0,255, 0) classifier_result1 = run_classifier(roi_gray1, index) if classifier_result1: color = (0, 0, 255) # Đỏ nếu có xe else: color = (0, 255, 0) cv2.drawContours(frame_out, [points], contourIdx=-1, color=color, thickness=2, lineType=cv2.LINE_8) if dict['pedestrian_detection']: # Detecr người trong video, sẽ làm giản tốc độ chương trình vì cần một GPU có tốc độ xử lý cao (rects, weights) = hog.detectMultiScale(frame, winStride=(4, 4), padding=(8, 8), scale=1.05) # Vẽ bounding box for (x, y, w, h) in rects: cv2.rectangle(frame_out, (x, y), (x + w, y + h), (255, 0, 0), 2) # write output frames if dict['save_video']: out.write(frame_out) # Hiển thị video cv2.imshow('frame', frame_out) k = cv2.waitKey(1) if k == ord('q'): break elif k == ord('c'): cv2.imwrite('frame%d.jpg' % video_cur_frame, frame_out) elif k == ord('j'): cap.set(cv2.CAP_PROP_POS_FRAMES, video_cur_frame+1000) # Nhảy 1000 frames elif k == ord('u'): cap.set(cv2.CAP_PROP_POS_FRAMES, video_cur_frame + 500) # Nhảy 500 frames if cv2.waitKey(33) == 27: break cv2.waitKey(0) cap.release() if dict['save_video']: out.release() cv2.destroyAllWindows() # Classifier demonstration on M6 highway Britain: import cv2 from imutils.object_detection import non_max_suppression def perform_classification(video_src, cascade_src): cap = cv2.VideoCapture(video_src) car_cascade = cv2.CascadeClassifier(cascade_src) while True: ret, img = cap.read() if (type(img) == type(None)): print('Video not found') break image_scaled = cv2.resize(img, None, fx=0.6, fy=0.6) gray = cv2.cvtColor(image_scaled, cv2.COLOR_BGR2GRAY) cars = car_cascade.detectMultiScale(gray, 1.1, 1) #1.1, 1 cars = np.array([[x, y, x + w, y + h] for (x, y, w, h) in cars]) pick = non_max_suppression(cars, probs=None, overlapThresh=0.65) for (x, y, w, h) in pick: cv2.rectangle(image_scaled, (x, y), (w, h), (0, 255, 255), 2) cv2.imshow('Press ESC key to finish', image_scaled) # Nhấn Esc để thoát if cv2.waitKey(33) == 27: break print('Execution finished') cv2.destroyAllWindows() perform_classification('phong_testvideo_02.avi', 'phong_classifier.xml') # M6 highway Britain # Tính toán độ chính xác của classifier. Frames được lấy từ các buổi trong ngày với điều kiện ánh sáng khác sau (sáng chiều tối) import phong_utility_01 as util util.get_acc('phong_classifier.xml') # Nhấn Esc để hoàn thành việc xác định real time boxing # Chương trình sẽ vẽ những hình tứ giác khi có đủ 4 lần nháy đúp chuột trái import cv2 import yaml import numpy as np refPt = [] cropping = False data = [] file_path = 'phong_yml_02.yml' img = cv2.imread('phong_frame_02.png') def yaml_loader(file_path): with open(file_path, "r") as file_descr: data = yaml.load(file_descr) return data def yaml_dump(file_path, data): with open(file_path, "a") as file_descr: yaml.dump(data, file_descr) def yaml_dump_write(file_path, data): with open(file_path, "w") as file_descr: yaml.dump(data, file_descr) def click_and_crop(event, x, y, flags, param): current_pt = {'id': 0, 'points': []} # grab references cho biến global global refPt, cropping if event == cv2.EVENT_LBUTTONDBLCLK: refPt.append((x, y)) cropping = False if len(refPt) == 4: if data == []: if yaml_loader(file_path) != None: data_already = len(yaml_loader(file_path)) else: data_already = 0 else: if yaml_loader(file_path) != None: data_already = len(data) + len(yaml_loader(file_path)) else: data_already = len(data) cv2.line(image, refPt[0], refPt[1], (0, 255, 0), 1) cv2.line(image, refPt[1], refPt[2], (0, 255, 0), 1) cv2.line(image, refPt[2], refPt[3], (0, 255, 0), 1) cv2.line(image, refPt[3], refPt[0], (0, 255, 0), 1) temp_lst1 = list(refPt[2]) temp_lst2 = list(refPt[3]) temp_lst3 = list(refPt[0]) temp_lst4 = list(refPt[1]) current_pt['points'] = [temp_lst1, temp_lst2, temp_lst3, temp_lst4] current_pt['id'] = data_already data.append(current_pt) refPt = [] image = cv2.resize(img, None, fx=0.6, fy=0.6) clone = image.copy() cv2.namedWindow("Double click to mark points") cv2.imshow("Double click to mark points", image) cv2.setMouseCallback("Double click to mark points", click_and_crop) # Tiếp tục looping cho đến khi 'q' được nhấn while True: # Hiển thị hình ảnh cho đến khi được được nhấn cv2.imshow("Double click to mark points", image) key = cv2.waitKey(1) & 0xFF if cv2.waitKey(33) == 27: break # data list vào yaml file if data != []: yaml_dump(file_path, data) cv2.destroyAllWindows() # Chương trình tính toán giá trị Threshold cho một parking area có sẵn import statistics import cv2 import yaml import numpy as np sum_up = 0.0 delta_list = [] frame = cv2.imread('phong_frame_02.png') # parking_bounding_rects = [] parking_mask = [] frame_blur = cv2.GaussianBlur(frame.copy(), (5,5), 3) frame_gray = cv2.cvtColor(frame_blur, cv2.COLOR_BGR2GRAY) with open('phong_yml_02.yml', 'r') as stream: parking_data = yaml.load(stream) if parking_data != None: for park in parking_data: points = np.array(park['points']) rect = cv2.boundingRect(points) points_shifted = points.copy() points_shifted[:,0] = points[:,0] - rect[0] # shift contour to region of interest points_shifted[:,1] = points[:,1] - rect[1] parking_bounding_rects.append(rect) mask = cv2.drawContours(np.zeros((rect[3], rect[2]), dtype=np.uint8), [points_shifted], contourIdx=-1, color=255, thickness=-1, lineType=cv2.LINE_8) mask = mask==255 parking_mask.append(mask) for ind, park in enumerate(parking_data): points = np.array(park['points']) rect = parking_bounding_rects[ind] roi_gray = frame_gray[rect[1]:(rect[1]+rect[3]), rect[0]:(rect[0]+rect[2])] # crop ROI để tính toán nhanh hơn laplacian = cv2.Laplacian(roi_gray, cv2.CV_64F) points[:,0] = points[:,0] - rect[0] # shift contour to roi points[:,1] = points[:,1] - rect[1] delta = np.mean(np.abs(laplacian * parking_mask[ind])) if(delta > 1.8): # Bỏ qua space trống delta_list.append(delta) sum_up = sum_up + delta avg = sum_up/len(parking_data) med = statistics.median(delta_list) print("mean: ", avg) print("median: ", med) ``` ## Kết luận Hệ thống đề xuất một phương pháp hiệu quả để quản lý hệ thống bãi đậu xe bằng cách sử dụng máy ảnh được đặt ở các cột đèn. Độ chính xác của hệ thống phụ thuộc vào giá trị Threshold, thuật toán theo dõi chuyển động dựa trên background subtraction và quan trọng nhất là sức mạnh của classifier. Thách thức phải đối mặt là để xác định chuyển động trong một ROI nhỏ khi có tồn tại khả năng có nhiễu. Ví dụ, máy ảnh được đặt gần cầu thang và reflection của những người đi bộ xuống cầu thang đã được reflect trong video đầu vào được cung cấp bởi máy ảnh. Nó trở nên khó khăn để giảm tác động của nhiễu và phát hiện được các chuyển động nhỏ. Bên cạnh đó, Haar classifier đã thực hiện tốt mục tiêu đặt ra của đề tài nhưng thực hiện classifier dựa trên Convolution Neural Networks sẽ làm tăng độ chính xác tổng thể của hệ thống một cách đáng kể. Đây là phạm vi công việc trong tương lai của dự án này. Tuy nhiên với hiện tại thì mức độ chính xác của hệ thống là rất tốt với độ chính xác hơn 85% với mô hình bãi đỗ xe vừa-nhỏ và hơn 62.5% với mô hình bãi độ xe lớn. ## Tham khảo ### 1. Video -https://www.youtube.com/watch?v=bPeGC8-PQJg -https://www.youtube.com/watch?v=Dg-4MoABv4I ### 2. Codes -https://github.com/eladj/detectParking -http://www.pyimagesearch.com/2015/11/09/pedestrian-detection-opencv/ ### 3. Papers [1] M. I. et al, “Car park system: A review of smart parking system and its technology,” Information Technology Journal, 2009. In this study, various types of smart parking systems with their pros and cons are presented. [2] N. True, “Vacant parking space detection in static images,” 2007. http://cseweb.ucsd.edu/classes/wi07/cse190-a/reports/ntrue.pdf
github_jupyter
# EDA Case Study: House Price ### Task Description House Prices is a classical Kaggle competition. The task is to predicts final price of each house. For more detail, refer to https://www.kaggle.com/c/house-prices-advanced-regression-techniques/. ### Goal of this notebook As it is a famous competition, there exists lots of excelent analysis on how to do eda and how to build model for this task. See https://www.kaggle.com/khandelwallaksya/house-prices-eda for a reference. In this notebook, we will show how dataprep.eda can simply the eda process using a few lines of code. In conclusion: * **Understand the problem**. We'll look at each variable and do a philosophical analysis about their meaning and importance for this problem. * **Univariable study**. We'll just focus on the dependent variable ('SalePrice') and try to know a little bit more about it. * **Multivariate study**. We'll try to understand how the dependent variable and independent variables relate. * **Basic cleaning**. We'll clean the dataset and handle the missing data, outliers and categorical variables. ### Import libraries ``` from dataprep.eda import plot from dataprep.eda import plot_correlation from dataprep.eda import plot_missing from dataprep.datasets import load_dataset import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns sns.set(style="whitegrid", color_codes=True) sns.set(font_scale=1) ``` ### Load data ``` houses = load_dataset("house_prices_train") houses.head() houses_test = load_dataset("house_prices_test") houses_test.head() houses.shape ``` There are total 1460 tuples, each tuple contains 80 features and 1 target value. ``` houses_test.shape ``` ### Variable identification ``` plot(houses) ``` ### Overview of the data We could get the following information: * **Variable**-Variable name * **Type**-There are 43 categorical columns and 38 numerical columns. * **Missing value**-How many missing values each column contains. For instance, Fence contains 80.8% * 1460 = 1180 missing tuples. Usually, some model does not allow the input data contains missing value such as SVM, we have to clean the data before we utilize it. * **Target Value**-The distribution of target value (SalePrice). According to the distribution of the target value, we could get the information that the target value is numerical and the distribution of the target value conforms to the norm distribution. Thus, we are not confronted with imbalanced classes problem. It is really great. * **Guess**-According to the columns' name, we reckon GrLivArea, YearBuilt and OverallQual are likely to be correlated to the target value (SalePrice). ### Correlation in data ``` plot_correlation(houses, "SalePrice") plot_correlation(houses, "SalePrice", value_range=[0.5, 1]) ``` OverallQual, GrLivArea, GarageCars, GarageArea, TotalBsmtSF, 1stFlrSF, FullBath, TotRmsAbvGrd, YearBuilt, YearRemodAdd have more than 0.5 Pearson correlation with SalePrice. OverallQual, GrLivArea, GarageCars, YearBuilt, GarageArea, FullBath, TotalBsmtSF, GarageYrBlt, 1stFlrSF, YearRemodAdd, TotRmsAbvGrd and Fireplaces have more than 0.5 Spearman correlation with SalePrice. OverallQual, GarageCars, GrLivArea and FullBath have more than 0.5 KendallTau correlation with SalePrice. EnclosedPorch and KitchenAbvGr have little negative correlation with target variable. These can prove to be important features to predict SalePrice. ### Heatmap ``` plot_correlation(houses) ``` ### In summary In my opinion, this heatmap is the best way to get a quick overview of features' relationships. At first sight, there are two red colored squares that get my attention. The first one refers to the 'TotalBsmtSF' and '1stFlrSF' variables, and the second one refers to the 'GarageX' variables. Both cases show how significant the correlation is between these variables. Actually, this correlation is so strong that it can indicate a situation of multicollinearity. If we think about these variables, we can conclude that they give almost the same information so multicollinearity really occurs. Heatmaps are great to detect this kind of situations and in problems dominated by feature selection, like ours, they are an essential tool. Another thing that got my attention was the 'SalePrice' correlations. We can see our well-known 'GrLivArea', 'TotalBsmtSF', and 'OverallQual', but we can also see many other variables that should be taken into account. That's what we will do next. ``` plot_correlation(houses[["SalePrice","OverallQual","GrLivArea","GarageCars", "GarageArea","GarageYrBlt","TotalBsmtSF","1stFlrSF","FullBath", "TotRmsAbvGrd","YearBuilt","YearRemodAdd"]]) ``` As we saw above there are few feature which shows high multicollinearity from heatmap. Lets focus on red squares on diagonal line and few on the sides. SalePrice and OverallQual GarageArea and GarageCars TotalBsmtSF and 1stFlrSF GrLiveArea and TotRmsAbvGrd YearBulit and GarageYrBlt We have to create a single feature from them before we use them as predictors. ``` plot_correlation(houses, value_range=[0.5, 1]) plot_correlation(houses, k=30) ``` **Attribute Pair Correlation** 7 (GarageArea, GarageCars) 0.882475 11 (GarageYrBlt, YearBuilt) 0.825667 15 (GrLivArea, TotRmsAbvGrd) 0.825489 18 (1stFlrSF, TotalBsmtSF) 0.819530 19 (2ndFlrSF, GrLivArea) 0.687501 9 (BedroomAbvGr, TotRmsAbvGrd) 0.676620 0 (BsmtFinSF1, BsmtFullBath) 0.649212 2 (GarageYrBlt, YearRemodAdd) 0.642277 24 (FullBath, GrLivArea) 0.630012 8 (2ndFlrSF, TotRmsAbvGrd) 0.616423 1 (2ndFlrSF, HalfBath) 0.609707 4 (GarageCars, OverallQual) 0.600671 16 (GrLivArea, OverallQual) 0.593007 23 (YearBuilt, YearRemodAdd) 0.592855 22 (GarageCars, GarageYrBlt) 0.588920 12 (OverallQual, YearBuilt) 0.572323 5 (1stFlrSF, GrLivArea) 0.566024 25 (GarageArea, GarageYrBlt) 0.564567 6 (GarageArea, OverallQual) 0.562022 17 (FullBath, TotRmsAbvGrd) 0.554784 13 (OverallQual, YearRemodAdd) 0.550684 14 (FullBath, OverallQual) 0.550600 3 (GarageYrBlt, OverallQual) 0.547766 10 (GarageCars, YearBuilt) 0.537850 27 (OverallQual, TotalBsmtSF) 0.537808 20 (BsmtFinSF1, TotalBsmtSF) 0.522396 21 (BedroomAbvGr, GrLivArea) 0.521270 26 (2ndFlrSF, BedroomAbvGr) 0.502901 This shows multicollinearity. In regression, "multicollinearity" refers to features that are correlated with other features. Multicollinearity occurs when your model includes multiple factors that are correlated not just to your target variable, but also to each other. Problem: Multicollinearity increases the standard errors of the coefficients. That means, multicollinearity makes some variables statistically insignificant when they should be significant. To avoid this we can do 3 things: Completely remove those variables Make new feature by adding them or by some other operation. Use PCA, which will reduce feature set to small number of non-collinear features. Reference:http://blog.minitab.com/blog/understanding-statistics/handling-multicollinearity-in-regression-analysis ### Univariate Analysis How 1 single variable is distributed in numeric range. What is statistical summary of it. Is it positively skewed or negatively. ``` plot(houses, "SalePrice") ``` ### Pivotal Features ``` plot_correlation(houses, "OverallQual", "SalePrice") plot(houses, "OverallQual", "SalePrice") # why not combine them together? plot(houses, "GarageCars", "SalePrice") plot(houses, "Fireplaces", "SalePrice") plot(houses, "GrLivArea", "SalePrice") plot(houses, "TotalBsmtSF", "SalePrice") plot(houses, "YearBuilt", "SalePrice") ``` ### In summary Based on the above analysis, we can conclude that: 'GrLivArea' and 'TotalBsmtSF' seem to be linearly related with 'SalePrice'. Both relationships are positive, which means that as one variable increases, the other also increases. In the case of 'TotalBsmtSF', we can see that the slope of the linear relationship is particularly high. 'OverallQual' and 'YearBuilt' also seem to be related with 'SalePrice'. The relationship seems to be stronger in the case of 'OverallQual', where the box plot shows how sales prices increase with the overall quality. We just analysed four variables, but there are many other that we should analyse. The trick here seems to be the choice of the right features (feature selection) and not the definition of complex relationships between them (feature engineering). That said, let's separate the wheat from the chaff. ### Missing Value Imputation Missing values in the training data set can affect prediction or classification of a model negatively. Also some machine learning algorithms can't accept missing data eg. SVM, Neural Network. But filling missing values with mean/median/mode or using another predictive model to predict missing values is also a prediction which may not be 100% accurate, instead you can use models like Decision Trees and Random Forest which handle missing values very well. Some of this part is based on this kernel: https://www.kaggle.com/bisaria/house-prices-advanced-regression-techniques/handling-missing-data ``` plot_missing(houses) # plot_missing(houses, "BsmtQual") basement_cols=['BsmtQual','BsmtCond','BsmtExposure','BsmtFinType1','BsmtFinType2','BsmtFinSF1','BsmtFinSF2'] houses[basement_cols][houses['BsmtQual'].isnull()==True] ``` All categorical variables contains NAN whereas continuous ones have 0. So that means there is no basement for those houses. we can replace it with 'None'. ``` for col in basement_cols: if 'FinSF'not in col: houses[col] = houses[col].fillna('None') # plot_missing(houses, "FireplaceQu") houses["FireplaceQu"] = houses["FireplaceQu"].fillna('None') pd.crosstab(houses.Fireplaces, houses.FireplaceQu) garage_cols=['GarageType','GarageQual','GarageCond','GarageYrBlt','GarageFinish','GarageCars','GarageArea'] houses[garage_cols][houses['GarageType'].isnull()==True] ``` All garage related features are missing values in same rows. that means we can replace categorical variables with None and continuous ones with 0. ``` for col in garage_cols: if houses[col].dtype==np.object: houses[col] = houses[col].fillna('None') else: houses[col] = houses[col].fillna(0) ```
github_jupyter
# Keyword Spotting Dataset Curation [![Open In Colab <](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/ShawnHymel/ei-keyword-spotting/blob/master/ei-audio-dataset-curation.ipynb) Use this tool to download the Google Speech Commands Dataset, combine it with your own keywords, mix in some background noise, and upload the curated dataset to Edge Impulse. From there, you can train a neural network to classify spoken words and upload it to a microcontroller to perform real-time keyword spotting. 1. Upload samples of your own keyword (optional) 2. Adjust parameters in the Settings cell (you will need an [Edge Impulse](https://www.edgeimpulse.com/) account) 3. Run the rest of the cells! ('shift' + 'enter' on each cell) ### Upload your own keyword samples You are welcome to use my [custom keyword dataset](https://github.com/ShawnHymel/custom-speech-commands-dataset), but note that it's limited and that I can't promise it will work well. If you want to use it, uncomment the `###Download custom dataset` cell below. You may also add your own recorded keywords to the extracted folder (`/content/custom_keywords`) to augment what's already there. If you'd rather upload your own custom keyword dataset, follow these instructions: On the left pane, in the file browser, create a directory structure containing space for your keyword audio samples. All samples for each keyword should be in a directory with that keyword's name. The audio samples should be `.wav` format, mono, and 1 second long. Bitrate and bitdepth should not matter. Samples shorter than 1 second will be padded with 0s, and samples longer than 1 second will be truncated to 1 second. The exact name of each `.wav` file does not matter, as they will be read, mixed with background noise, and saved to a separate file with an auto-generated name. Directory name does matter (it is used to determine the name of the class during neural network training). Right-click on each keyword directory and upload all of your samples. Your directory structor should look like the following: ``` / |- content |--- custom_keywords |----- keyword_1 |------- 000.wav |------- 001.wav |------- ... |----- keyword_2 |------- 000.wav |------- 001.wav |------- ... |----- ... ``` ``` ### Update Node.js to the latest stable version !npm cache clean -f !npm install -g n !n stable ### Install required packages and tools !python -m pip install soundfile !npm install -g --unsafe-perm edge-impulse-cli ### Settings (You probably do not need to change these) BASE_DIR = "/content" OUT_DIR = "keywords_curated" GOOGLE_DATASET_FILENAME = "speech_commands_v0.02.tar.gz" GOOGLE_DATASET_URL = "http://download.tensorflow.org/data/" + GOOGLE_DATASET_FILENAME GOOGLE_DATASET_DIR = "google_speech_commands" CUSTOM_KEYWORDS_FILENAME = "main.zip" CUSTOM_KEYWORDS_URL = "https://github.com/ShawnHymel/custom-speech-commands-dataset/archive/" + CUSTOM_KEYWORDS_FILENAME CUSTOM_KEYWORDS_DIR = "custom_keywords" CUSTOM_KEYWORDS_REPO_NAME = "custom-speech-commands-dataset-main" CURATION_SCRIPT = "dataset-curation.py" CURATION_SCRIPT_URL = "https://raw.githubusercontent.com/ShawnHymel/ei-keyword-spotting/master/" + CURATION_SCRIPT UTILS_SCRIPT_URL = "https://raw.githubusercontent.com/ShawnHymel/ei-keyword-spotting/master/utils.py" NUM_SAMPLES = 1500 # Target number of samples to mix and send to Edge Impulse WORD_VOL = 1.0 # Relative volume of word in output sample BG_VOL = 0.1 # Relative volume of noise in output sample SAMPLE_TIME = 1.0 # Time (seconds) of output sample SAMPLE_RATE = 16000 # Sample rate (Hz) of output sample BIT_DEPTH = "PCM_16" # Options: [PCM_16, PCM_24, PCM_32, PCM_U8, FLOAT, DOUBLE] BG_DIR = "_background_noise_" TEST_RATIO = 0.2 # 20% reserved for test set, rest is for training EI_INGEST_TEST_URL = "https://ingestion.edgeimpulse.com/api/test/data" EI_INGEST_TRAIN_URL = "https://ingestion.edgeimpulse.com/api/training/data" ### Download Google Speech Commands Dataset !cd {BASE_DIR} !wget {GOOGLE_DATASET_URL} !mkdir {GOOGLE_DATASET_DIR} !echo "Extracting..." !tar xfz {GOOGLE_DATASET_FILENAME} -C {GOOGLE_DATASET_DIR} ### Pull out background noise directory !cd {BASE_DIR} !mv "{GOOGLE_DATASET_DIR}/{BG_DIR}" "{BG_DIR}" ### (Optional) Download custom dataset--uncomment the code in this cell if you want to use my custom datase ## Download, extract, and move dataset to separate directory # !cd {BASE_DIR} # !wget {CUSTOM_KEYWORDS_URL} # !echo "Extracting..." # !unzip -q {CUSTOM_KEYWORDS_FILENAME} # !mv "{CUSTOM_KEYWORDS_REPO_NAME}/{CUSTOM_KEYWORDS_DIR}" "{CUSTOM_KEYWORDS_DIR}" ### User Settings (do change these) # Location of your custom keyword samples (e.g. "/content/custom_keywords") # Leave blank ("") for no custom keywords. set to the CUSTOM_KEYWORDS_DIR # variable to use samples from my custom-speech-commands-dataset repo. CUSTOM_DATASET_PATH = "" # Edge Impulse > your_project > Dashboard > Keys EI_API_KEY = "ei_e544..." # Comma separated words. Must match directory names (that contain samples). # Recommended: use 2 keywords for microcontroller demo TARGETS = "go, stop" ### Download curation and utils scripts !wget {CURATION_SCRIPT_URL} !wget {UTILS_SCRIPT_URL} ### Perform curation and mixing of samples with background noise !cd {BASE_DIR} !python {CURATION_SCRIPT} \ -t "{TARGETS}" \ -n {NUM_SAMPLES} \ -w {WORD_VOL} \ -g {BG_VOL} \ -s {SAMPLE_TIME} \ -r {SAMPLE_RATE} \ -e {BIT_DEPTH} \ -b "{BG_DIR}" \ -o "{OUT_DIR}" \ "{GOOGLE_DATASET_DIR}" \ "{CUSTOM_DATASET_PATH}" ### Use CLI tool to send curated dataset to Edge Impulse !cd {BASE_DIR} # Imports import os import random # Seed with system time random.seed() # Go through each category in our curated dataset for dir in os.listdir(OUT_DIR): # Create list of files for one category paths = [] for filename in os.listdir(os.path.join(OUT_DIR, dir)): paths.append(os.path.join(OUT_DIR, dir, filename)) # Shuffle and divide into test and training sets random.shuffle(paths) num_test_samples = int(TEST_RATIO * len(paths)) test_paths = paths[:num_test_samples] train_paths = paths[num_test_samples:] # Create arugments list (as a string) for CLI call test_paths = ['"' + s + '"' for s in test_paths] test_paths = ' '.join(test_paths) train_paths = ['"' + s + '"' for s in train_paths] train_paths = ' '.join(train_paths) # Send test files to Edge Impulse !edge-impulse-uploader \ --category testing \ --label {dir} \ --api-key {EI_API_KEY} \ --silent \ {test_paths} # # Send training files to Edge Impulse !edge-impulse-uploader \ --category training \ --label {dir} \ --api-key {EI_API_KEY} \ --silent \ {train_paths} ```
github_jupyter
<a href="https://colab.research.google.com/github/felipe-parodi/QuantTools4Neuro/blob/master/PCA_PyDSHandbook.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> <!--BOOK_INFORMATION--> <img align="left" style="padding-right:10px;" src="https://github.com/jakevdp/PythonDataScienceHandbook/blob/master/notebooks/figures/PDSH-cover-small.png?raw=1"> *This notebook contains an excerpt from the [Python Data Science Handbook](http://shop.oreilly.com/product/0636920034919.do) by Jake VanderPlas; the content is available [on GitHub](https://github.com/jakevdp/PythonDataScienceHandbook).* *The text is released under the [CC-BY-NC-ND license](https://creativecommons.org/licenses/by-nc-nd/3.0/us/legalcode), and code is released under the [MIT license](https://opensource.org/licenses/MIT). If you find this content useful, please consider supporting the work by [buying the book](http://shop.oreilly.com/product/0636920034919.do)!* <!--NAVIGATION--> < [In-Depth: Decision Trees and Random Forests](05.08-Random-Forests.ipynb) | [Contents](Index.ipynb) | [In-Depth: Manifold Learning](05.10-Manifold-Learning.ipynb) > <a href="https://colab.research.google.com/github/jakevdp/PythonDataScienceHandbook/blob/master/notebooks/05.09-Principal-Component-Analysis.ipynb"><img align="left" src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open in Colab" title="Open and Execute in Google Colaboratory"></a> # In Depth: Principal Component Analysis Up until now, we have been looking in depth at supervised learning estimators: those estimators that predict labels based on labeled training data. Here we begin looking at several unsupervised estimators, which can highlight interesting aspects of the data without reference to any known labels. In this section, we explore what is perhaps one of the most broadly used of unsupervised algorithms, principal component analysis (PCA). PCA is fundamentally a dimensionality reduction algorithm, but it can also be useful as a tool for visualization, for noise filtering, for feature extraction and engineering, and much more. After a brief conceptual discussion of the PCA algorithm, we will see a couple examples of these further applications. We begin with the standard imports: ``` %matplotlib inline import numpy as np import matplotlib.pyplot as plt import seaborn as sns; sns.set() ``` ## Introducing Principal Component Analysis Principal component analysis is a fast and flexible unsupervised method for dimensionality reduction in data, which we saw briefly in [Introducing Scikit-Learn](05.02-Introducing-Scikit-Learn.ipynb). Its behavior is easiest to visualize by looking at a two-dimensional dataset. Consider the following 200 points: ``` rng = np.random.RandomState(1) X = np.dot(rng.rand(2,2), rng.randn(2,200)).T plt.scatter(X[:,0], X[:, 1]) plt.axis('equal') ``` By eye, it is clear that there is a nearly linear relationship between the x and y variables. This is reminiscent of the linear regression data we explored in [In Depth: Linear Regression](05.06-Linear-Regression.ipynb), but the problem setting here is slightly different: rather than attempting to *predict* the y values from the x values, the unsupervised learning problem attempts to learn about the *relationship* between the x and y values. In principal component analysis, this relationship is quantified by finding a list of the *principal axes* in the data, and using those axes to describe the dataset. Using Scikit-Learn's ``PCA`` estimator, we can compute this as follows: ``` from sklearn.decomposition import PCA # Run PCA pca = PCA(n_components=2) pca.fit(X) ``` The fit learns some quantities from the data, most importantly the "components" and "explained variance": ``` print(pca.components_) print(pca.explained_variance_) ``` To see what these numbers mean, let's visualize them as vectors over the input data, using the "components" to define the direction of the vector, and the "explained variance" to define the squared-length of the vector: ``` def draw_vector(v0, v1, ax=None): ax = ax or plt.gca() arrowprops=dict(arrowstyle='->', linewidth=2, shrinkA=0, shrinkB=0) ax.annotate('', v1,v0, arrowprops=arrowprops) # plot data plt.scatter(X[:,0], X[:, 1], alpha=0.2) for length, vector in zip(pca.explained_variance_, pca.components_): v = vector * 3* np.sqrt(length) draw_vector(pca.mean_, pca.mean_ + v) plt.axis('equal') ``` These vectors represent the *principal axes* of the data, and the length of the vector is an indication of how "important" that axis is in describing the distribution of the data—more precisely, it is a measure of the variance of the data when projected onto that axis. The projection of each data point onto the principal axes are the "principal components" of the data. If we plot these principal components beside the original data, we see the plots shown here: ![](https://github.com/jakevdp/PythonDataScienceHandbook/blob/master/notebooks/figures/05.09-PCA-rotation.png?raw=1) [figure source in Appendix](06.00-Figure-Code.ipynb#Principal-Components-Rotation) This transformation from data axes to principal axes is an *affine transformation*, which basically means it is composed of a translation, rotation, and uniform scaling. While this algorithm to find principal components may seem like just a mathematical curiosity, it turns out to have very far-reaching applications in the world of machine learning and data exploration. ### PCA as dimensionality reduction Using PCA for dimensionality reduction involves zeroing out one or more of the smallest principal components, resulting in a lower-dimensional projection of the data that preserves the maximal data variance. Here is an example of using PCA as a dimensionality reduction transform: ``` pca = PCA(n_components=1) pca.fit(X) X_pca = pca.transform(X) print("original shape: ", X.shape) print("transformed shape:", X_pca.shape) ``` The transformed data has been reduced to a single dimension. To understand the effect of this dimensionality reduction, we can perform the inverse transform of this reduced data and plot it along with the original data: ``` X_new = pca.inverse_transform(X_pca) plt.scatter(X[:,0], X[:,1], alpha=0.2) plt.scatter(X_new[:,0], X_new[:, 1], alpha=0.8) plt.axis('equal') ``` The light points are the original data, while the dark points are the projected version. This makes clear what a PCA dimensionality reduction means: the information along the least important principal axis or axes is removed, leaving only the component(s) of the data with the highest variance. The fraction of variance that is cut out (proportional to the spread of points about the line formed in this figure) is roughly a measure of how much "information" is discarded in this reduction of dimensionality. This reduced-dimension dataset is in some senses "good enough" to encode the most important relationships between the points: despite reducing the dimension of the data by 50%, the overall relationship between the data points are mostly preserved. ### PCA for visualization: Hand-written digits The usefulness of the dimensionality reduction may not be entirely apparent in only two dimensions, but becomes much more clear when looking at high-dimensional data. To see this, let's take a quick look at the application of PCA to the digits data we saw in [In-Depth: Decision Trees and Random Forests](05.08-Random-Forests.ipynb). We start by loading the data: ``` from sklearn.datasets import load_digits digits = load_digits() digits.data.shape ``` Recall that the data consists of 8×8 pixel images, meaning that they are 64-dimensional. To gain some intuition into the relationships between these points, we can use PCA to project them to a more manageable number of dimensions, say two: ``` pca = PCA(20) projected = pca.fit_transform(digits.data) print(digits.data.shape) print(projected.shape) ``` plt.scaWe can now plot the first two principal components of each point to learn about the data: ``` plt.scatter(projected[:,0], projected[:,1], c=digits.target, edgecolor='none', alpha=0.5, cmap = plt.cm.get_cmap('Greens', 10)) plt.xlabel('component 1') plt.ylabel('component 2') plt.colorbar() ``` Recall what these components mean: the full data is a 64-dimensional point cloud, and these points are the projection of each data point along the directions with the largest variance. Essentially, we have found the optimal stretch and rotation in 64-dimensional space that allows us to see the layout of the digits in two dimensions, and have done this in an unsupervised manner—that is, without reference to the labels. ### What do the components mean? We can go a bit further here, and begin to ask what the reduced dimensions *mean*. This meaning can be understood in terms of combinations of basis vectors. For example, each image in the training set is defined by a collection of 64 pixel values, which we will call the vector $x$: $$ x = [x_1, x_2, x_3 \cdots x_{64}] $$ One way we can think about this is in terms of a pixel basis. That is, to construct the image, we multiply each element of the vector by the pixel it describes, and then add the results together to build the image: $$ {\rm image}(x) = x_1 \cdot{\rm (pixel~1)} + x_2 \cdot{\rm (pixel~2)} + x_3 \cdot{\rm (pixel~3)} \cdots x_{64} \cdot{\rm (pixel~64)} $$ One way we might imagine reducing the dimension of this data is to zero out all but a few of these basis vectors. For example, if we use only the first eight pixels, we get an eight-dimensional projection of the data, but it is not very reflective of the whole image: we've thrown out nearly 90% of the pixels! ![](https://github.com/jakevdp/PythonDataScienceHandbook/blob/master/notebooks/figures/05.09-digits-pixel-components.png?raw=1) [figure source in Appendix](06.00-Figure-Code.ipynb#Digits-Pixel-Components) The upper row of panels shows the individual pixels, and the lower row shows the cumulative contribution of these pixels to the construction of the image. Using only eight of the pixel-basis components, we can only construct a small portion of the 64-pixel image. Were we to continue this sequence and use all 64 pixels, we would recover the original image. But the pixel-wise representation is not the only choice of basis. We can also use other basis functions, which each contain some pre-defined contribution from each pixel, and write something like $$ image(x) = {\rm mean} + x_1 \cdot{\rm (basis~1)} + x_2 \cdot{\rm (basis~2)} + x_3 \cdot{\rm (basis~3)} \cdots $$ PCA can be thought of as a process of choosing optimal basis functions, such that adding together just the first few of them is enough to suitably reconstruct the bulk of the elements in the dataset. The principal components, which act as the low-dimensional representation of our data, are simply the coefficients that multiply each of the elements in this series. This figure shows a similar depiction of reconstructing this digit using the mean plus the first eight PCA basis functions: ![](https://github.com/jakevdp/PythonDataScienceHandbook/blob/master/notebooks/figures/05.09-digits-pca-components.png?raw=1) [figure source in Appendix](06.00-Figure-Code.ipynb#Digits-PCA-Components) Unlike the pixel basis, the PCA basis allows us to recover the salient features of the input image with just a mean plus eight components! The amount of each pixel in each component is the corollary of the orientation of the vector in our two-dimensional example. This is the sense in which PCA provides a low-dimensional representation of the data: it discovers a set of basis functions that are more efficient than the native pixel-basis of the input data. pca =### Choosing the number of components A vital part of using PCA in practice is the ability to estimate how many components are needed to describe the data. This can be determined by looking at the cumulative *explained variance ratio* as a function of the number of components: ``` pca = PCA().fit(digits.data) plt.plot(np.cumsum(pca.explained_variance_ratio_)) plt.xlabel('number of components') plt.ylabel('cumulative explained variance'); ``` This curve quantifies how much of the total, 64-dimensional variance is contained within the first $N$ components. For example, we see that with the digits the first 10 components contain approximately 75% of the variance, while you need around 50 components to describe close to 100% of the variance. Here we see that our two-dimensional projection loses a lot of information (as measured by the explained variance) and that we'd need about 20 components to retain 90% of the variance. Looking at this plot for a high-dimensional dataset can help you understand the level of redundancy present in multiple observations. def plot## PCA as Noise Filtering PCA can also be used as a filtering approach for noisy data. The idea is this: any components with variance much larger than the effect of the noise should be relatively unaffected by the noise. So if you reconstruct the data using just the largest subset of principal components, you should be preferentially keeping the signal and throwing out the noise. Let's see how this looks with the digits data. First we will plot several of the input noise-free data: ``` def plot_digits(data): fig, axes = plt.subplots(4,10, figsize=(10,4), subplot_kw={'xticks':[],'yticks':[]}, gridspec_kw=dict(hspace=0.1, wspace=0.1)) for i, ax in enumerate(axes.flat): ax.imshow(data[i].reshape(8,8), cmap='binary', interpolation='nearest', clim=(0,16)) plot_digits(digits.data) # def plot_digits(data): # fig, axes = plt.subplots(4, 10, figsize=(10, 4), # subplot_kw={'xticks':[], 'yticks':[]}, # gridspec_kw=dict(hspace=0.1, wspace=0.1)) # for i, ax in enumerate(axes.flat): # ax.imshow(data[i].reshape(8, 8), # cmap='binary', interpolation='nearest', # clim=(0, 16)) # plot_digits(digits.data) ``` Now lets add some random noise to create a noisy dataset, and re-plot it: ``` np.random.seed(42) noisy = np.random.normal(digits.data,4) plot_digits(noisy) ``` It's clear by eye that the images are noisy, and contain spurious pixels. Let's train a PCA on the noisy data, requesting that the projection preserve 50% of the variance: ``` pca = PCA(0.7 0).fit(noisy) pca.n_components_ ``` Here 50% of the variance amounts to 12 principal components. Now we compute these components, and then use the inverse of the transform to reconstruct the filtered digits: ``` components = pca.transform(noisy) filtered = pca.inverse_transform(components) plot_digits(filtered) ``` This signal preserving/noise filtering property makes PCA a very useful feature selection routine—for example, rather than training a classifier on very high-dimensional data, you might instead train the classifier on the lower-dimensional representation, which will automatically serve to filter out random noise in the inputs. ## Example: Eigenfaces Earlier we explored an example of using a PCA projection as a feature selector for facial recognition with a support vector machine (see [In-Depth: Support Vector Machines](05.07-Support-Vector-Machines.ipynb)). Here we will take a look back and explore a bit more of what went into that. Recall that we were using the Labeled Faces in the Wild dataset made available through Scikit-Learn: ``` from sklearn.datasets import fetch_lfw_people faces = fetch_lfw_people(min_faces_per_person=60) print(faces.target_names) print(faces.images.shape) ``` from sklearn.Let's take a look at the principal axes that span this dataset. Because this is a large dataset, we will use ``RandomizedPCA``—it contains a randomized method to approximate the first $N$ principal components much more quickly than the standard ``PCA`` estimator, and thus is very useful for high-dimensional data (here, a dimensionality of nearly 3,000). We will take a look at the first 150 components: ``` from sklearn.decomposition import PCA as RandomizedPCA pca = RandomizedPCA(150, svd_solver='randomized', whiten=True).fit(faces.data) ``` In this case, it can be interesting to visualize the images associated with the first several principal components (these components are technically known as "eigenvectors," so these types of images are often called "eigenfaces"). As you can see in this figure, they are as creepy as they sound: ``` fig, axes = plt.subplots(3, 8, figsize=(9, 4), subplot_kw={'xticks':[], 'yticks':[]}, gridspec_kw=dict(hspace=0.1, wspace=0.1)) for i, ax in enumerate(axes.flat): ax.imshow(pca.components_[i].reshape(62, 47), cmap='bone') ``` The results are very interesting, and give us insight into how the images vary: for example, the first few eigenfaces (from the top left) seem to be associated with the angle of lighting on the face, and later principal vectors seem to be picking out certain features, such as eyes, noses, and lips. Let's take a look at the cumulative variance of these components to see how much of the data information the projection is preserving: ``` plt.plot(np.cumsum(pca.explained_variance_ratio_)) plt.xlabel('number of components') plt.ylabel('cumulative explained variance'); ``` We see that these 150 components account for just over 90% of the variance. That would lead us to believe that using these 150 components, we would recover most of the essential characteristics of the data. To make this more concrete, we can compare the input images with the images reconstructed from these 150 components: ``` # Compute the components and projected faces pca = RandomizedPCA(150).fit(faces.data) components = pca.transform(faces.data) projected = pca.inverse_transform(components) # Plot the results fig, ax = plt.subplots(2, 10, figsize=(10, 2.5), subplot_kw={'xticks':[], 'yticks':[]}, gridspec_kw=dict(hspace=0.1, wspace=0.1)) for i in range(10): ax[0, i].imshow(faces.data[i].reshape(62, 47), cmap='binary_r') ax[1, i].imshow(projected[i].reshape(62, 47), cmap='binary_r') ax[0, 0].set_ylabel('full-dim\ninput') ax[1, 0].set_ylabel('150-dim\nreconstruction'); ``` The top row here shows the input images, while the bottom row shows the reconstruction of the images from just 150 of the ~3,000 initial features. This visualization makes clear why the PCA feature selection used in [In-Depth: Support Vector Machines](05.07-Support-Vector-Machines.ipynb) was so successful: although it reduces the dimensionality of the data by nearly a factor of 20, the projected images contain enough information that we might, by eye, recognize the individuals in the image. What this means is that our classification algorithm needs to be trained on 150-dimensional data rather than 3,000-dimensional data, which depending on the particular algorithm we choose, can lead to a much more efficient classification. ## Principal Component Analysis Summary In this section we have discussed the use of principal component analysis for dimensionality reduction, for visualization of high-dimensional data, for noise filtering, and for feature selection within high-dimensional data. Because of the versatility and interpretability of PCA, it has been shown to be effective in a wide variety of contexts and disciplines. Given any high-dimensional dataset, I tend to start with PCA in order to visualize the relationship between points (as we did with the digits), to understand the main variance in the data (as we did with the eigenfaces), and to understand the intrinsic dimensionality (by plotting the explained variance ratio). Certainly PCA is not useful for every high-dimensional dataset, but it offers a straightforward and efficient path to gaining insight into high-dimensional data. PCA's main weakness is that it tends to be highly affected by outliers in the data. For this reason, many robust variants of PCA have been developed, many of which act to iteratively discard data points that are poorly described by the initial components. Scikit-Learn contains a couple interesting variants on PCA, including ``RandomizedPCA`` and ``SparsePCA``, both also in the ``sklearn.decomposition`` submodule. ``RandomizedPCA``, which we saw earlier, uses a non-deterministic method to quickly approximate the first few principal components in very high-dimensional data, while ``SparsePCA`` introduces a regularization term (see [In Depth: Linear Regression](05.06-Linear-Regression.ipynb)) that serves to enforce sparsity of the components. In the following sections, we will look at other unsupervised learning methods that build on some of the ideas of PCA. <!--NAVIGATION--> < [In-Depth: Decision Trees and Random Forests](05.08-Random-Forests.ipynb) | [Contents](Index.ipynb) | [In-Depth: Manifold Learning](05.10-Manifold-Learning.ipynb) > <a href="https://colab.research.google.com/github/jakevdp/PythonDataScienceHandbook/blob/master/notebooks/05.09-Principal-Component-Analysis.ipynb"><img align="left" src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open in Colab" title="Open and Execute in Google Colaboratory"></a>
github_jupyter
# StateFarm Distracted Driver Detection Full Dataset ``` %cd /home/ubuntu/kaggle/state-farm-distracted-driver-detection # Make sure you are in the main directory (state-farm-distracted-driver-detection) %pwd # Create references to key directories import os, sys from glob import glob from matplotlib import pyplot as plt import numpy as np import keras np.set_printoptions(precision=4, linewidth=100) current_dir = os.getcwd() CHALLENGE_HOME_DIR = current_dir DATA_HOME_DIR = current_dir+'/data' #Allow relative imports to directories sys.path.insert(1, os.path.join(sys.path[0], '..')) #import modules from utils import * from utils.vgg16 import Vgg16 import utils; reload(utils) from utils import * from utils.utils import * #Instantiate plotting tool %matplotlib inline #Need to correctly import utils.py import bcolz from numpy.random import random, permutation %cd $DATA_HOME_DIR path = DATA_HOME_DIR + '/' test_path = path + 'test/' results_path= path + 'results/' train_path=path + 'train/' valid_path=path + 'valid/' #Set constants. You can experiment with no_of_epochs to improve the model batch_size=64 no_of_epochs=3 ``` ## Create Batches ``` batches = get_batches(train_path, batch_size=batch_size) val_batches = get_batches(valid_path, batch_size=batch_size*2, shuffle=False) (val_classes, trn_classes, val_labels, trn_labels, val_filenames, filenames, test_filename) = get_classes(path) ``` ## Use Previous Conv sample model on full dataset The previous model used in the sample data should work better with more data. Lets try it out ``` def simple_conv(batches): model = Sequential([ BatchNormalization(axis=1, input_shape=(3,224,224)), Convolution2D(32,3,3, activation='relu'), BatchNormalization(axis=1), MaxPooling2D((3,3)), Convolution2D(64,3,3, activation='relu'), BatchNormalization(axis=1), MaxPooling2D((3,3)), Flatten(), Dense(200, activation='relu'), BatchNormalization(), Dense(10, activation='softmax') ]) model.compile(Adam(lr=1e-4), loss='categorical_crossentropy', metrics=['accuracy']) model.fit_generator(batches, batches.nb_sample, nb_epoch=2, validation_data=val_batches, nb_val_samples=val_batches.nb_sample) model.optimizer.lr = 0.001 model.fit_generator(batches, batches.nb_sample, nb_epoch=4, validation_data=val_batches, nb_val_samples=val_batches.nb_sample) return model model = simple_conv(batches) model.save_weights(path+'models/simple_conv.h5') ``` ## Improve with Data Augmentation ``` gen_t = image.ImageDataGenerator(rotation_range=15, height_shift_range=0.1, shear_range=0.1, channel_shift_range=25, width_shift_range=0.1) da_batches = get_batches(train_path, gen_t, batch_size=batch_size) model = simple_conv(da_batches) model.save_weights(path+'models/simple_conv_da_1.h5') model.optimizer.lr = 0.0001 model.fit_generator(da_batches, da_batches.nb_sample, nb_epoch=4, validation_data=val_batches, nb_val_samples=val_batches.nb_sample) model.save_weights(path+'models/simple_conv_da_2.h5') ``` ## Deeper Conv/Pooling pair model + Dropout If the results are still unstable - the validation accuracy jumps from epoch to epoch, creating a deeper model with dropout will help. Create a Deeper model with dropout ``` gen_t = image.ImageDataGenerator(rotation_range=15, height_shift_range=0.1, shear_range=0.1, channel_shift_range=25, width_shift_range=0.1) batches = get_batches(train_path, gen_t, batch_size=batch_size) model = Sequential([ BatchNormalization(axis=1, input_shape=(3,224,224)), Convolution2D(32,3,3, activation='relu'), BatchNormalization(axis=1), MaxPooling2D(), Convolution2D(64,3,3, activation='relu'), BatchNormalization(axis=1), MaxPooling2D(), Convolution2D(128,3,3, activation='relu'), BatchNormalization(axis=1), MaxPooling2D(), Flatten(), Dense(200, activation='relu'), BatchNormalization(), Dropout(0.5), Dense(200, activation='relu'), BatchNormalization(), Dropout(0.5), Dense(10, activation='softmax') ]) model.compile(Adam(lr=10e-5), loss='categorical_crossentropy', metrics=['accuracy']) model.fit_generator(batches, batches.nb_sample, nb_epoch=2, validation_data=val_batches, nb_val_samples=val_batches.nb_sample) model.save_weights(path+'models/deep_conv_da_1.h5') model.load_weights(path+'models/deep_conv_da_1.h5') ``` The model is underfitting, lets increase the learning rate ``` model.optimizer.lr=0.001 model.fit_generator(batches, batches.nb_sample, nb_epoch=10, validation_data=val_batches, nb_val_samples=val_batches.nb_sample) model.save_weights(path+'models/deep_conv_da_2.h5') ``` If the model was overfitting, you would need to decrease the learning rate. Let me decrease the learning rate and see if we get better results ``` model.optimizer.lr=0.00001 model.fit_generator(batches, batches.nb_sample, nb_epoch=5, validation_data=val_batches, nb_val_samples=val_batches.nb_sample) model.save_weights(path+'models/deep_conv_da_3.h5') ``` The accuracy is similar and there is more stability. However, its try with VGG16 model ## Use ImageNet Conv Features Since we have so little data, and it is similar to imagenet images (full color photos), using pre-trained VGG weights is likely to be helpful - in fact it seems likely that we won't need to fine-tune the convolutional layer weights much, if at all. So we can pre-compute the output of the last convolutional layer, as we did in lesson 3 when we experimented with dropout. (However this means that we can't use full data augmentation, since we can't pre-compute something that changes every image.) ``` vgg = Vgg16() model=vgg.model last_conv_idx = [i for i,l in enumerate(model.layers) if type(l) is Convolution2D][-1] conv_layers = model.layers[:last_conv_idx+1] conv_model = Sequential(conv_layers) # Lets pre-compute the features. Thus, shuffle should be set to False batches = get_batches(train_path, batch_size=batch_size, shuffle=False) (val_classes, trn_classes, val_labels, trn_labels, val_filenames, filenames, test_filenames) = get_classes(path) # Compute features for the conv layers for the training, validation, and test data conv_feat = conv_model.predict_generator(batches, batches.nb_sample) conv_val_feat = conv_model.predict_generator(val_batches, val_batches.nb_sample) conv_test_feat = conv_model.predict_generator(test_batches, test_batches.nb_sample) # save the features for future use save_array(path+'results/conv_val_feat.dat', conv_val_feat) save_array(path+'results/conv_test_feat.dat', conv_test_feat) save_array(path+'results/conv_feat.dat', conv_feat) conv_val_feat.shape ``` ### Create Batchnorm dense layers under the Conv layers Create a network that would sit under the prior conv layers to predict the 10 classes. This is a simplified version on the VGG's dense layers ``` def get_bn_layers(p): return [ MaxPooling2D(input_shape=conv_layers[-1].output_shape[1:]), Flatten(), Dropout(p/2), Dense(128, activation='relu'), BatchNormalization(), Dropout(p/2), Dense(128, activation='relu'), BatchNormalization(), Dropout(p), Dense(10, activation='softmax') ] p=0.8 bn_model = Sequential(get_bn_layers(p)) bn_model.compile(Adam(lr=0.001), loss='categorical_crossentropy', metrics=['accuracy']) bn_model.fit(conv_feat, trn_labels, batch_size=batch_size, nb_epoch=1, validation_data=(conv_val_feat, val_labels) bn_model.optimizer.lr = 0.01 bn_model.fit(conv_feat, trn_labels, batch_size=batch_size, nb_epoch=2, validation_data=(conv_val_feat, val_labels)) bn_model.save_weights(path+'models/bn_dense.h5') ``` ### Pre-computed data augmentation + more dropout Lets add the augmented data and adding larger dense layers, and therefore more dropout to the pre-trained model ``` gen_t = image.ImageDataGenerator(rotation_range=15, height_shift_range=0.1, shear_range=0.1, channel_shift_range=25, width_shift_range=0.1) batches = get_batches(train_path, gen_t, batch_size=batch_size, shuffle=False) ``` Create a dataset of convolutional features that is 5x bigger than the original training set (5 variations of data augmentation from the ImageDataGenerator) ``` da_conv_feat = conv_model.predict_generator(da_batches, da_batches.nb_sample*5) save_array(path+'results/da_conv_feat.dat', da_conv_feat) ``` Add the real training data in its non-augmented form ``` da_conv_feat = np.concatenate([da_conv_feat, conv_feat]) # Since we've now gotten a dataset 6x bigger than before, we'll need to copy our labels 6x too da_trn_labels = np.concatenate([trn_labels]*6) def get_bn_da_layers(p): return [ MaxPooling2D(input_shape=conv_layers[-1].output_shape[1:]), Flatten(), Dropout(p), Dense(256, activation='relu'), BatchNormalization(), Dropout(p), Dense(256, activation='relu'), BatchNormalization(), Dropout(p), Dense(10, activation='softmax') ] p=0.8 bn_model = Sequential(get_bn_da_layers(p)) bn_model.compile(Adam(lr=0.001), loss='categorical_crossentropy', metrics=['accuracy']) # Lets train the model with the larger set of pre-computed augemented data bn_model.fit(da_conv_feat, da_trn_labels, batch_size=batch_size, nb_epoch=1, validation_data=(conv_val_feat, val_labels)) bn_model.optimizer.lr=0.01 bn_model.fit(da_conv_feat, da_trn_labels, batch_size=batch_size, nb_epoch=4, validation_data=(conv_val_feat, val_labels)) bn_model.optimizer.lr=0.0001 bn_model.fit(da_conv_feat, da_trn_labels, batch_size=batch_size, nb_epoch=4, validation_data=(conv_val_feat, val_labels)) bn_model.save_weights(path+'models/bn_da_dense.h5') ``` ## Pseudo Labeling Try using a combination of pseudo labeling and knowledge distillation to allow us to use unlabeled data (i.e. do semi-supervised learning). For our initial experiment we'll use the validation set as the unlabeled data, so that we can see that it is working without using the test set ``` val_pseudo = bn_model.predict(conv_val_feat, batch_size=batch_size) # Concatenate them with the original training set comb_pseudo = np.concatenate([da_trn_labels, val_pseudo]) comb_feat = np.concatenate([da_conv_feat, conv_val_feat]) # fine-tune the model using this combined training set bn_model.load_weights(path+'models/bn_da_dense.h5') bn_model.fit(comb_feat, comb_pseudo, batch_size=batch_size, nb_epoch=1, validation_data=(conv_val_feat, val_labels)) bn_model.fit(comb_feat, comb_pseudo, batch_size=batch_size, nb_epoch=4, validation_data=(conv_val_feat, val_labels)) bn_model.optimizer.lr=0.00001 bn_model.fit(comb_feat, comb_pseudo, batch_size=batch_size, nb_epoch=4, validation_data=(conv_val_feat, val_labels)) # There is a distinct improvement - altough the validation set isn't large. # A sigfniicant improvement can be found when using the test data bn_model.save_weights(path+'models/bn-ps8.h5') ``` ## Generate Predictions from Test data ``` test_batches = get_batches(test_path, shuffle=False, batch_size=batch_size) preds = model.predict_generator(test_batches, test_batches.nb_sample) preds[:2] ``` ### Submit to competition ``` def do_clip(arr, mx): return np.clip(arr, (1-mx)/9, mx) keras.metrics.categorical_crossentropy(val_labels, do_clip(val_preds, 0.93)).eval() subm = do_clip(preds,0.93) subm_name = path+'results/subm.csv' classes = sorted(batches.class_indices, key=batches.class_indices.get) submission = pd.DataFrame(subm, columns=classes) submission.insert(0, 'img', [a[8:] for a in test_filename]) submission.head() submission.tail() submission.to_csv(subm_name, index=False, encoding='utf-8') FileLink(subm_name) ```
github_jupyter
<img src="../img/logo_white_bkg_small.png" align="right" /> # Worksheet 3: Detecting Domain Generation Algorithm (DGA) Domains against DNS This worksheet covers concepts covered in the second half of Module 6 - Hunting with Data Science. It should take no more than 20-30 minutes to complete. Please raise your hand if you get stuck. Your objective is to reduce a dataset that has thousands of domain names and identify those created by DGA. ## Import the Libraries For this exercise, we will be using: * Pandas (http://pandas.pydata.org/pandas-docs/stable/) * Flare (https://github.com/austin-taylor/flare) * Json (https://docs.python.org/3/library/json.html) * WHOIS (https://pypi.python.org/pypi/whois) Beacon writeup: <a href="http://www.austintaylor.io/detect/beaconing/intrusion/detection/system/command/control/flare/elastic/stack/2017/06/10/detect-beaconing-with-flare-elasticsearch-and-intrusion-detection-systems/"> Detect Beaconing <a href="../answers/Worksheet 10 - Hunting with Data Science - Answers.ipynb"> Answers for this section </a> ``` from flare.data_science.features import entropy from flare.data_science.features import dga_classifier from flare.data_science.features import domain_tld_extract from flare.tools.alexa import Alexa from pandas.io.json import json_normalize from whois import whois import pandas as pd import json import warnings warnings.filterwarnings('ignore') ``` ## This is an example of how to generate domain generated algorithms. ``` def generate_domain(year, month, day): """Generates a domain name for the given date.""" domain = "" for i in range(16): year = ((year ^ 8 * year) >> 11) ^ ((year & 0xFFFFFFF0) << 17) month = ((month ^ 4 * month) >> 25) ^ 16 * (month & 0xFFFFFFF8) day = ((day ^ (day << 13)) >> 19) ^ ((day & 0xFFFFFFFE) << 12) domain += chr(((year ^ month ^ day) % 25) + 97) return domain + '.com' generate_domain(2017, 6, 23) ``` ### A large portion of data science is data preparation. In this exercise, we'll take output from Suricata's eve.json file and extract the DNS records so we can find anything using DGA. First you'll need to **unzip the large_eve_json.zip file** in the data directory and specify the path. ``` eve_json = '../data/large_eve.json' ``` ### Next read the data in and build a list ``` all_suricata_data = [json.loads(record) for record in open(eve_json).readlines()] len(all_suricata_data) ``` ### Our output from Suricata has 746909 records, and for we are only interested in DNS records. Let's narrow our data down to records that only contain dns ### Read in suricata data and load each record as json if DNS is in the key. This will help pandas json_normalize feature ``` # YOUR CODE (hint check if dns is in key) len(dns_records) ``` ### Down to 21484 -- much better. ### Somewhere in our _21484_ records is communication from infected computers. It's up to you to narrow the results down and find the malicious DNS request. ``` dns_records[2] ``` ### The data is nested json and has varying lengths, so you will need to use the json_normalize feature ``` suricata_df = json_normalize(dns_records) suricata_df.shape suricata_df.head(2) ``` ### Next we need to filter out all A records ``` # YOUR CODE to filter out all A records a_records.shape ``` ### By filtering out the A records, our dataset is down to 2849. ``` a_records['dns.rrname'].value_counts().head() ``` ### Next we can figure out how many unique DNS names there are. ``` a_records_unique = pd.DataFrame(a_records['dns.rrname'].unique(), columns=['dns_rrname']) ``` ### Should have a much smaller set of domains to process now ``` a_records_unique.head() ``` ### Next we need to train extract the top level domains (remove subdomains) using flare so we can feed it to our classifier ``` #Apply extract to the dns_rrname and create a column named domain_tld a_records_unique.head() ``` ### Train DGA Classifier with dictionary words, n-grams and DGA Domains ``` dga_predictor = dga_classifier() ``` You can apply dga prediction to a column by using dga_predictor.predict('baddomain.com') ``` # YOUR CODE ``` ### A quick sampling of the data shows our prediction has labelled our data. ``` a_records_unique.sample(10) ``` Create a new dataframe called dga_df and filter it out to only show names predicted as DGA ``` # YOUR CODE dga_df ``` ### Our dataset is down to 5 results! Let's run the domains through alexa to see if ny are in the top 1 million ``` alexa = Alexa() # Example: dga_df['in_alexa'] = dga_df.dns_rrname.apply(alexa.domain_in_alexa) def get_creation_date(domain): try: lookup = whois(domain) output = lookup.get('creation_date','No results') except: output = 'No Creation Date!' if output is None: output = 'No Creation Date!' return output get_creation_date('google.com') ``` ### It appears none of our domains are in Alexa, but let's check creation dates. ``` # YOUR CODE ``` ### Congrats! If you did this exercise right, you should have 2 domains with no creation date which were generated by DGA! Bonus points if you can figure out the dates for each domain.
github_jupyter
``` import pandas as pds import numpy as np import matplotlib.pyplot as plt method_dict = {"vi": "D-CODE", "diff": "SR-T", "spline": "SR-S", "gp": "SR-G"} val_dict = { "noise": "sigma", "freq": "del_t", "n": "n", } ode_list = ["GompertzODE", "LogisticODE"] def plot_df(df, x_val="sigma"): for method in method_dict.keys(): df_sub = df[df.method == method] df_sub = df_sub.dropna() plt.fill_between( df_sub[x_val], df_sub.rate - df_sub.rate_sd, df_sub.rate + df_sub.rate_sd, alpha=0.3, ) plt.plot(df_sub[x_val], df_sub.rate, "o-", label=method_dict[method]) plt.ylim(-0.05, 1.05) plt.figure(figsize=(12, 4)) plt.style.use("tableau-colorblind10") colors = plt.rcParams["axes.prop_cycle"].by_key()["color"] plt.rcParams["font.size"] = "13" counter = 1 for i in range(len(ode_list)): ode = ode_list[i] for val_key, x_val in val_dict.items(): print(ode, val_key, x_val) df = pds.read_csv("results/{}-{}.txt".format(ode, val_key), header=None) df.columns = [ "ode", "freq", "n", "sigma", "method", "rate", "rate_sd", "ks", "ks_sd", ] df["del_t"] = 1.0 / df["freq"] df = df.sort_values(["method", x_val]) plot_conf = 230 + counter plt.subplot(plot_conf) plot_df(df, x_val=x_val) if counter == 1 or counter == 4: plt.ylabel("Success Prob.", size=16) if counter == 1: plt.title("Varying noise level $\sigma_R$") plt.xscale("log") elif counter == 2: plt.title("Gompertz Model \n Varying step size $\Delta t$") plt.xscale("log") elif counter == 3: plt.title("Varying sample size $N$") elif counter == 5: plt.title("Generalized Logistic Model") if counter == 4: plt.xlabel(r"$\sigma_R$", size=16) plt.xscale("log") elif counter == 5: plt.xlabel(r"$\Delta t$", size=16) plt.xscale("log") elif counter == 6: plt.xlabel(r"$N$", size=16) counter += 1 plt.legend(title="Methods", bbox_to_anchor=(1.05, 1), loc="upper left") plt.tight_layout(pad=0.2) plt.savefig("growth_results.png", dpi=200) ``` ## Selkov Table ``` ode = "SelkovODE" val_key = list(val_dict.keys())[0] x_val = val_dict[val_key] df = pds.read_csv("results/{}-{}.txt".format(ode, val_key), header=None) df.columns = ["ode", "freq", "n", "sigma", "method", "rate", "rate_sd", "ks", "ks_sd"] df["del_t"] = 1.0 / df["freq"] df = df.sort_values(["method", x_val]) df["x_id"] = 0 df0 = df df = pds.read_csv("results/{}-{}-1.txt".format(ode, val_key), header=None) df.columns = ["ode", "freq", "n", "sigma", "method", "rate", "rate_sd", "ks", "ks_sd"] df["del_t"] = 1.0 / df["freq"] df = df.sort_values(["method", x_val]) df["x_id"] = 1 df1 = df df = pds.read_csv("results/{}-{}-param.txt".format(ode, val_key), header=None) df.columns = [ "ode", "freq", "n", "sigma", "method", "sigma_rmse", "sigma_sd", "rho_rmse", "rho_sd", ] df["del_t"] = 1.0 / df["freq"] df = df.sort_values(["method", x_val]) df["x_id"] = 0 df0_param = df df = pds.read_csv("results/{}-{}-param-1.txt".format(ode, val_key), header=None) df.columns = [ "ode", "freq", "n", "sigma", "method", "sigma_rmse", "sigma_sd", "rho_rmse", "rho_sd", ] df["del_t"] = 1.0 / df["freq"] df = df.sort_values(["method", x_val]) df["x_id"] = 1 df1_param = df df = pds.concat([df0, df1]) df_param = pds.concat([df0_param, df1_param]) df = pds.merge(df, df_param) tbl_rate = pds.pivot_table(df, values="rate", index=["x_id", "method"], columns="sigma") tbl_rate["val"] = "rate" tbl_rate_sd = pds.pivot_table( df, values="rate_sd", index=["x_id", "method"], columns="sigma" ) tbl_rate_sd["val"] = "rate_sd" tbl_sigma_rmse = pds.pivot_table( df, values="sigma_rmse", index=["x_id", "method"], columns="sigma" ) tbl_sigma_rmse["val"] = "sigma_rmse" tbl_sigma_sd = pds.pivot_table( df, values="sigma_sd", index=["x_id", "method"], columns="sigma" ) tbl_sigma_sd["val"] = "sigma_sd" tbl_sigma_ks = pds.pivot_table( df, values="ks", index=["x_id", "method"], columns="sigma" ) tbl_sigma_ks["val"] = "ks" tbl_sigma_ks tbl_sigma_ks_sd = pds.pivot_table( df, values="ks_sd", index=["x_id", "method"], columns="sigma" ) tbl_sigma_ks_sd["val"] = "ks_sd" tbl_sigma_ks_sd selkov_table = pds.concat([tbl_rate, tbl_rate_sd, tbl_sigma_rmse, tbl_sigma_sd]) selkov_table tt = selkov_table.reset_index() tt[tt["method"] == "gp"] tt[tt["method"] == "diff"] selkov_table.to_csv("Selkov_results.csv") ``` ## Lorenz results ``` def plot_df_ax(df, ax, x_val="sigma"): for method in method_dict.keys(): df_sub = df[df.method == method] df_sub = df_sub.dropna() ax.fill_between( df_sub[x_val], df_sub.rate - df_sub.rate_sd, df_sub.rate + df_sub.rate_sd, alpha=0.3, ) ax.plot(df_sub[x_val], df_sub.rate, "o-", label=method_dict[method]) ax.set_ylim(-0.05, 1.05) ## this part is the placeholder def lorenz(x, y, z, s=10, r=28, b=2.667): """ Given: x, y, z: a point of interest in three dimensional space s, r, b: parameters defining the lorenz attractor Returns: x_dot, y_dot, z_dot: values of the lorenz attractor's partial derivatives at the point x, y, z """ x_dot = s * (y - x) y_dot = r * x - y - x * z z_dot = x * y - b * z return x_dot, y_dot, z_dot dt = 0.01 num_steps = 10000 # Need one more for the initial values xs = np.empty(num_steps + 1) ys = np.empty(num_steps + 1) zs = np.empty(num_steps + 1) # Set initial values xs[0], ys[0], zs[0] = (0.0, 1.0, 1.05) # Step through "time", calculating the partial derivatives at the current point # and using them to estimate the next point for i in range(num_steps): x_dot, y_dot, z_dot = lorenz(xs[i], ys[i], zs[i]) xs[i + 1] = xs[i] + (x_dot * dt) ys[i + 1] = ys[i] + (y_dot * dt) zs[i + 1] = zs[i] + (z_dot * dt) import pickle with open("results/Lorenz_traj.pkl", "rb") as f: diff_dict = pickle.load(f) with open("results/Lorenz_vi_traj.pkl", "rb") as f: vi_dict = pickle.load(f) with open("results/Lorenz_true_traj.pkl", "rb") as f: true_dict = pickle.load(f) with open("results/Lorenz_node_traj2.pkl", "rb") as f: node_dict = pickle.load(f) def plot_trac(ax, xs, ys, zs, title, lw=0.5): elev = 5.0 azim = 120.0 ax.view_init(elev, azim) 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.plot(xs, ys, zs, lw=lw) ax.set_title(title) # ax.set_xticks([]) # ax.set_yticks([]) # ax.set_zticks([]) import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec plt.figure(figsize=(12, 6)) plt.style.use("tableau-colorblind10") colors = plt.rcParams["axes.prop_cycle"].by_key()["color"] plt.rcParams["font.size"] = "13" gs = gridspec.GridSpec(3, 12) ax1a = plt.subplot(gs[0, :4]) ax1b = plt.subplot(gs[0, 4:8]) ax1c = plt.subplot(gs[0, 8:]) # ax1a = plt.subplot(gs[0, :3]) # ax1b = plt.subplot(gs[0, 3:6]) # ax1c = plt.subplot(gs[0, 6:9]) ax2a = plt.subplot(gs[1:, :3], projection="3d") ax2b = plt.subplot(gs[1:, 3:6], projection="3d") ax2c = plt.subplot(gs[1:, 6:9], projection="3d") ax2d = plt.subplot(gs[1:, 9:], projection="3d") for i, ax in enumerate(plt.gcf().axes): if i < 3: x_id = i if x_id == 0: df = pds.read_csv("results/Lorenz-noise.txt", header=None) else: df = pds.read_csv("results/Lorenz-noise-{}.txt".format(x_id), header=None) df.columns = [ "ode", "freq", "n", "sigma", "method", "rate", "rate_sd", "ks", "ks_sd", ] df["del_t"] = 1.0 / df["freq"] df = df.sort_values(["method", "sigma"]) plot_df_ax(df, ax) ax.set_xlabel("Noise $\sigma_R$") if i == 0: ax.set_title("Success Prob. $\dot{x}_1(t)$") elif i == 1: ax.set_title("Success Prob. $\dot{x}_2(t)$") else: ax.set_title("Success Prob. $\dot{x}_3(t)$") ax.legend(bbox_to_anchor=(1.005, 1), loc="upper left", fontsize=10) # ax.legend(loc='center left', fontsize=10) else: if i == 3: plot_trac(ax, true_dict["x"], true_dict["y"], true_dict["z"], str(i)) ax.set_title("Ground truth") elif i == 4: plot_trac(ax, vi_dict["x"], vi_dict["y"], vi_dict["z"], str(i), lw=0.3) ax.set_title("D-CODE") elif i == 5: plot_trac( ax, diff_dict["x"], diff_dict["y"], diff_dict["z"], str(i), lw=0.8 ) ax.set_title("SR-T") else: plot_trac( ax, node_dict["x"], node_dict["y"], node_dict["z"], str(i), lw=2.0 ) ax.set_title("Neural ODE") ax.set_zlim(0, 50) ax.set_xlim(-25, 25) ax.set_ylim(-25, 25) plt.tight_layout() plt.savefig("lorenz.png", dpi=200) plt.show() ``` ## sensitivity plot ``` def plot_df2(df_sub, x_val="n_basis"): plt.fill_between( df_sub[x_val], df_sub.rate - df_sub.rate_sd, df_sub.rate + df_sub.rate_sd, alpha=0.3, ) plt.plot(df_sub[x_val], df_sub.rate, "o-") plt.ylim(-0.05, 1.05) ode_list = ["GompertzODE", "Lorenz"] bas_list = ["sine", "cubic"] plt.figure(figsize=(12, 4)) plt.style.use("tableau-colorblind10") colors = plt.rcParams["axes.prop_cycle"].by_key()["color"] plt.rcParams["font.size"] = "13" counter = 1 for i in range(len(ode_list)): ode = ode_list[i] for bas in bas_list: df = pds.read_csv("results/sensitivity_{}.txt".format(ode), header=None) df.columns = ["ode", "basis", "n_basis", "N", "rate", "rate_sd", "ks", "ks_sd"] df = df.sort_values(["basis", "n_basis"]) df_sub = df[df["basis"] == bas] df_sub = df_sub.dropna() plot_conf = 220 + counter plt.subplot(plot_conf) plot_df2(df_sub) if counter > 2: plt.xlabel("Number of basis", size=16) # if counter == 1 or counter == 4: # plt.ylabel('Recovery Rate', size=16) plt.title("{} - {}".format(ode, bas)) # if counter == 1: # plt.title('Varying noise level $\sigma_R$') # plt.xscale('log') # elif counter == 2: # plt.title('Gompertz Model \n Varying step size $\Delta t$') # elif counter == 3: # plt.title('Varying sample size $N$') # elif counter == 4: # plt.title('Generalized Logistic Model') # if counter == 4: # plt.xlabel(r'$\sigma_R$', size=16) # plt.xscale('log') # elif counter == 5: # plt.xlabel(r'$\Delta t$', size=16) # elif counter == 6: # plt.xlabel(r'$N$', size=16) counter += 1 plt.tight_layout(pad=0.2) plt.savefig("sensitivity_results.png", dpi=200) ``` ## objective ``` method_dict = {"vi": "D-CODE", "diff": "SR-T", "spline": "SR-S", "gp": "SR-G"} val_dict = { "noise": "sigma", "freq": "del_t", "n": "n", } ode_list = ["GompertzODE", "LogisticODE"] def plot_df(df, x_val="sigma"): for method in method_dict.keys(): df_sub = df[df.method == method] df_sub = df_sub.dropna() # if x_val == 'sigma': # df_sub = df_sub[df_sub[x_val] < 0.6] plt.fill_between( df_sub[x_val], df_sub.ks - df_sub.ks_sd, df_sub.ks + df_sub.ks_sd, alpha=0.3 ) plt.plot(df_sub[x_val], df_sub.ks, "o-", label=method_dict[method]) # plt.ylim([-0.05, None]) plt.figure(figsize=(12, 4)) plt.style.use("tableau-colorblind10") colors = plt.rcParams["axes.prop_cycle"].by_key()["color"] plt.rcParams["font.size"] = "13" counter = 1 for i in range(len(ode_list)): ode = ode_list[i] for val_key, x_val in val_dict.items(): df = pds.read_csv("results/{}-{}.txt".format(ode, val_key), header=None) df.columns = [ "ode", "freq", "n", "sigma", "method", "rate", "rate_sd", "ks", "ks_sd", ] df["del_t"] = 1.0 / df["freq"] df = df.sort_values(["method", x_val]) plot_conf = 230 + counter plt.subplot(plot_conf) plot_df(df, x_val=x_val) if counter == 1 or counter == 4: plt.ylabel("Objective $d_x$", size=16) if counter == 1: plt.title("Varying noise level $\sigma_R$") plt.xscale("log") elif counter == 2: plt.title("Gompertz Model \n Varying step size $\Delta t$") plt.xscale("log") elif counter == 3: plt.title("Varying sample size $N$") elif counter == 5: plt.title("Generalized Logistic Model") if counter == 4: plt.xlabel(r"$\sigma_R$", size=16) plt.xscale("log") elif counter == 5: plt.xlabel(r"$\Delta t$", size=16) elif counter == 6: plt.xlabel(r"$N$", size=16) counter += 1 plt.legend(title="Methods", bbox_to_anchor=(1.05, 1), loc="upper left") plt.tight_layout(pad=0.2) plt.savefig("growth_results_obj.png", dpi=200) ``` ## Lorenz objective ``` def plot_df_ax2(df, ax, x_val="sigma"): for method in method_dict.keys(): df_sub = df[df.method == method] df_sub = df_sub.dropna() ax.fill_between( df_sub[x_val], df_sub.ks - df_sub.ks_sd, df_sub.ks + df_sub.ks_sd, alpha=0.3 ) ax.plot(df_sub[x_val], df_sub.ks, "o-", label=method_dict[method]) # ax.set_ylim(-0.05, 1.05) import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec plt.figure(figsize=(12, 2.5)) plt.style.use("tableau-colorblind10") colors = plt.rcParams["axes.prop_cycle"].by_key()["color"] plt.rcParams["font.size"] = "13" # gs = gridspec.GridSpec(3, 9) ax1a = plt.subplot(1, 3, 1) ax1b = plt.subplot(1, 3, 2) ax1c = plt.subplot(1, 3, 3) # ax1a = plt.subplot(gs[0, :3]) # ax1b = plt.subplot(gs[0, 3:6]) # ax1c = plt.subplot(gs[0, 6:9]) # ax2a = plt.subplot(gs[1:, :3], projection='3d') # ax2b = plt.subplot(gs[1:, 3:6], projection='3d') # ax2c = plt.subplot(gs[1:, 6:9], projection='3d') # ax2d = plt.subplot(gs[1:, 9:], projection='3d') for i, ax in enumerate(plt.gcf().axes): if i < 3: x_id = i if x_id == 0: df = pds.read_csv("results/Lorenz-noise.txt", header=None) else: df = pds.read_csv("results/Lorenz-noise-{}.txt".format(x_id), header=None) df.columns = [ "ode", "freq", "n", "sigma", "method", "rate", "rate_sd", "ks", "ks_sd", ] df["del_t"] = 1.0 / df["freq"] df = df.sort_values(["method", "sigma"]) plot_df_ax2(df, ax) ax.set_xlabel("Noise $\sigma_R$") if i == 0: ax.set_title("Objective $d_x$ for $\dot{x}_1(t)$") elif i == 1: ax.set_title("Objective $d_x$ for $\dot{x}_2(t)$") else: ax.set_title("Objective $d_x$ for $\dot{x}_3(t)$") ax.legend(bbox_to_anchor=(1.005, 1), loc="upper left", fontsize=10) # ax.legend(loc='center left', fontsize=10) plt.tight_layout() plt.savefig("lorenz_objective.png", dpi=200) plt.show() ``` ## Fraction ODE ``` import matplotlib.pyplot as plt plt.figure(figsize=(12, 2.5)) plt.subplot(1, 2, 1) plt.style.use("tableau-colorblind10") colors = plt.rcParams["axes.prop_cycle"].by_key()["color"] plt.rcParams["font.size"] = "13" df = pds.read_csv("results/FracODE-noise.txt", header=None) df.columns = ["ode", "freq", "n", "sigma", "method", "rate", "rate_sd", "ks", "ks_sd"] df["del_t"] = 1.0 / df["freq"] df = df.sort_values(["method", "sigma"]) x_val = "sigma" for method in method_dict.keys(): df_sub = df[df.method == method] df_sub = df_sub.dropna() plt.fill_between( df_sub[x_val], df_sub.rate - df_sub.rate_sd, df_sub.rate + df_sub.rate_sd, alpha=0.3, ) plt.plot(df_sub[x_val], df_sub.rate, "o-", label=method_dict[method]) plt.ylim(-0.05, 1.05) plt.title("Discover Prob.") plt.xlabel("Noise level $\sigma$") ax = plt.subplot(1, 2, 2) plot_df_ax2(df, ax) ax.set_title("Objective $d_x$") ax.legend(bbox_to_anchor=(1.005, 1), loc="upper left", fontsize=10) plt.xlabel("Noise level $\sigma$") plt.savefig("frac.png", dpi=200) plt.show() ```
github_jupyter
# Standard Network Models ## 1. Multilayer Perceptron(MLP) * Model for binary classification * The model has 10 inputs,3 hidden layers with 10,20 and 10 neurons and an output layer with 1 output. * Rectified linear activation functions are used in each hidden layer and s sigmoid activation function is used in the output layer. ``` # Multilayer Perceptron from keras.utils import plot_model from keras.models import Model from keras.layers import Dense from keras.layers import Input visible = Input(shape=(10,)) hidden1 = Dense(10,activation='relu')(visible) hidden2 = Dense(20,activation='relu')(hidden1) hidden3 = Dense(10,activation='relu')(hidden2) output = Dense(1,activation='sigmoid')(hidden3) model = Model(inputs=visible,outputs=output) # summarize layers model.summary() # plot graph plot_model(model, to_file='multilayer_perceptron_graph.png') ``` ## 2. Convolutional Neural Network * The model receives black and white 64*64 images as input. * Then has a sequence of two convolutional and pooling layers as feature extractors. * Followed by a fully connected layer to interpret the features and an output layer with a sigmoid activation for two-class predictions. ``` # Convolutional Neural Network from keras.utils import plot_model from keras.models import Model from keras.layers import Input from keras.layers import Dense from keras.layers.convolutional import Conv2D from keras.layers.pooling import MaxPooling2D visible = Input(shape=(64,64,1)) conv1 = Conv2D(32,kernel_size=4,activation='relu')(visible) pool1 = MaxPooling2D(pool_size=(2,2))(conv1) conv2 = Conv2D(16,kernel_size=4,activation='relu')(pool1) pool2 = MaxPooling2D(pool_size=(2,2))(conv2) hidden1 = Dense(10,activation='relu')(pool2) output = Dense(1,activation='sigmoid')(hidden1) model = Model(inputs=visible,outputs=output) # summarize layers model.summary() # plot graph plot_model(model,to_file='convolutional_neural_network.png') ``` ## 3. Recurrent Neural Network * LSTM RNN for sequence classification. * The model expects 100 time steps of one feature as input. * The model has a single LSTM hidden layer to extract features from the sequence. * Followed by a fully connected layer to interpret the LSTM output. * And an output layer for making binary predictions. ``` # Recurrent Neural Network from keras.utils import plot_model from keras.models import Model from keras.layers import Input from keras.layers import Dense from keras.layers.recurrent import LSTM visible = Input(shape=(100,1)) hidden1 = LSTM(10)(visible) hidden2 = Dense(10,activation='relu')(hidden1) output = Dense(1,activation='sigmoid')(hidden2) model = Model(inputs=visible,outputs=output) # summarize layers model.summary() # plot_graph plot_model(model,to_file='recurrent_neural_network.png') ```
github_jupyter
## Importing libraries ``` import pandas as pd import numpy as np import pickle import matplotlib.pyplot as plt from scipy import stats import tensorflow as tf import seaborn as sns from pylab import rcParams from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler from sklearn.linear_model import LogisticRegression from sklearn.manifold import TSNE from sklearn.metrics import classification_report, accuracy_score from keras.models import Model, load_model from keras.layers import Input, Dense from keras.callbacks import ModelCheckpoint, TensorBoard from keras import regularizers, Sequential %matplotlib inline sns.set(style='whitegrid', palette='muted', font_scale=1.5) rcParams['figure.figsize'] = 14, 8 RANDOM_SEED = 42 LABELS = ["Normal", "Fraud"] ``` The data set I am going to use contains data about credit card transactions that occurred during a period of two days, with 492 frauds out of 284,807 transactions. All variables in the data set are numerical. The data has been transformed using PCA transformation(s) due to privacy reasons. The two features that haven’t been changed are Time and Amount. Time contains the seconds elapsed between each transaction and the first transaction in the data set. ## Data analysis ``` df = pd.read_csv("creditcard.csv") df.head() df.shape df.isnull().values.any() # checking if there is any null values count_classes = df.groupby(['Class']).size() count_classes.plot(kind= 'bar') plt.title("Transaction class distribution") plt.xticks(range(2), LABELS) plt.xlabel("Class") plt.ylabel("Frequency") frauds = df[df['Class'] == 1] normal = df[df['Class'] == 0] frauds.head(3) frauds.shape normal.head(3) normal.shape ``` #### Since only 3 of the features (time, amount and Class) are non-anomyzed, let’s explore them. ``` frauds['Amount'].describe() normal['Amount'].describe() f, axes = plt.subplots(1, 2) f.suptitle('Amount per transaction by class') sns.histplot(x= normal['Amount'], data=normal, ax=axes[0], bins=50) sns.histplot( x= frauds['Amount'], data=frauds, ax=axes[1], bins=50) axes[0].set_title('Normal') axes[1].set_title('Fraud') f, axes = plt.subplots(1, 2) f.suptitle('Time of transaction vs Amount by class') sns.scatterplot(x= normal['Time'],y= normal['Amount'], data=normal, ax=axes[0]) sns.scatterplot( x= frauds['Time'],y= frauds['Amount'], data=frauds, ax=axes[1]) axes[0].set_title('Normal') axes[1].set_title('Fraud') ``` The time does not seem to be a crucial feature in distinguishing normal vs fraud cases. Hence, I will drop it. ``` data = df.drop(['Time'], axis=1) from sklearn.preprocessing import StandardScaler data['Amount'] = StandardScaler().fit_transform(data['Amount'].values.reshape(-1, 1)) ``` The numerical amount in fraud and normal cases differ highly, hence we scale them. ## Scaling the 'Amount' using StandardScaler ``` from sklearn.preprocessing import StandardScaler data['Amount'] = StandardScaler().fit_transform(data['Amount'].values.reshape(-1, 1)) ``` ## Building the model We will be using autoencoders for the fraud detection model. Using autoencoders, we train the database only to learn the representation of the non-fraudulent transactions. The reason behind applying this method is to let the model learn the best representation of non-fraudulent cases so that it automatically distinguishes the other case from it. ``` # non_fraud = data[data['Class'] == 0] #.sample(1000) # fraud = data[data['Class'] == 1] # df = non_fraud.append(fraud) # X = df.drop(['Class'], axis = 1).values # Y = df["Class"].values ``` ## Spiting the data into 80% training and 20% testing ``` X_train, X_test = train_test_split(data, test_size=0.2, random_state=RANDOM_SEED) # X_train_fraud = X_train[X_train['Class'] == 1] # X_train = X_train[X_train['Class'] == 0] X_train = X_train.drop(['Class'], axis=1) y_test= X_test['Class'] X_test = X_test.drop(['Class'], axis=1) X_train = X_train.values X_test = X_test.values X_train.shape ``` ## Autoencoder model ``` input_layer = Input(shape=(X.shape[1],)) ## encoding part encoded = Dense(100, activation='tanh', activity_regularizer=regularizers.l1(10e-5))(input_layer) encoded = Dense(50, activation='relu')(encoded) ## decoding part decoded = Dense(50, activation='tanh')(encoded) decoded = Dense(100, activation='tanh')(decoded) ## output layer output_layer = Dense(X.shape[1], activation='relu')(decoded) ``` ## Training the credit card fraud detection model ``` autoencoder = Model(input_layer, output_layer) autoencoder.compile(optimizer="adadelta", loss="mse") ``` ## Scaling the values ``` x = data.drop(["Class"], axis=1) y = data["Class"].values x_scale = MinMaxScaler().fit_transform(x.values) x_norm, x_fraud = x_scale[y == 0], x_scale[y == 1] autoencoder.fit(x_norm[0:2000], x_norm[0:2000], batch_size = 256, epochs = 10, shuffle = True, validation_split = 0.20); ``` ## Obtain the Hidden Representation ``` hidden_representation = Sequential() hidden_representation.add(autoencoder.layers[0]) hidden_representation.add(autoencoder.layers[1]) hidden_representation.add(autoencoder.layers[2]) ``` ## Model Prediction ``` norm_hid_rep = hidden_representation.predict(x_norm[:3000]) fraud_hid_rep = hidden_representation.predict(x_fraud) ``` ## Getting the representation data ``` rep_x = np.append(norm_hid_rep, fraud_hid_rep, axis = 0) y_n = np.zeros(norm_hid_rep.shape[0]) y_f = np.ones(fraud_hid_rep.shape[0]) rep_y = np.append(y_n, y_f) ``` ## Train, test, split ``` train_x, val_x, train_y, val_y = train_test_split(rep_x, rep_y, test_size=0.25) ``` # Credit Card Fraud Detection Prediction model ``` clf = LogisticRegression(solver="lbfgs").fit(train_x, train_y) pred_y = clf.predict(val_x) print ("") print ("Classification Report: ") print (classification_report(val_y, pred_y)) print ("") print ("Accuracy Score: ", accuracy_score(val_y, pred_y)) ```
github_jupyter
Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. # Tutorial: Train a classification model with automated machine learning In this tutorial, you'll learn how to generate a machine learning model using automated machine learning (automated ML). Azure Machine Learning can perform algorithm selection and hyperparameter selection in an automated way for you. The final model can then be deployed following the workflow in the [Deploy a model](02.deploy-models.ipynb) tutorial. [flow diagram](./imgs/flow2.png) Similar to the [train models tutorial](01.train-models.ipynb), this tutorial classifies handwritten images of digits (0-9) from the [MNIST](http://yann.lecun.com/exdb/mnist/) dataset. But this time you don't to specify an algorithm or tune hyperparameters. The automated ML technique iterates over many combinations of algorithms and hyperparameters until it finds the best model based on your criterion. You'll learn how to: > * Set up your development environment > * Access and examine the data > * Train using an automated classifier locally with custom parameters > * Explore the results > * Review training results > * Register the best model ## Prerequisites Use [these instructions](https://aka.ms/aml-how-to-configure-environment) to: * Create a workspace and its configuration file (**config.json**) * Upload your **config.json** to the same folder as this notebook ### Start a notebook To follow along, start a new notebook from the same directory as **config.json** and copy the code from the sections below. ## Set up your development environment All the setup for your development work can be accomplished in the Python notebook. Setup includes: * Import Python packages * Configure a workspace to enable communication between your local computer and remote resources * Create a directory to store training scripts ### Import packages Import Python packages you need in this tutorial. ``` import azureml.core import pandas as pd from azureml.core.workspace import Workspace from azureml.train.automl.run import AutoMLRun import time import logging from sklearn import datasets from matplotlib import pyplot as plt from matplotlib.pyplot import imshow import random import numpy as np ``` ### Configure workspace Create a workspace object from the existing workspace. `Workspace.from_config()` reads the file **aml_config/config.json** and loads the details into an object named `ws`. `ws` is used throughout the rest of the code in this tutorial. Once you have a workspace object, specify a name for the experiment and create and register a local directory with the workspace. The history of all runs is recorded under the specified experiment. ``` ws = Workspace.from_config() # choose a name for the run history container in the workspace experiment_name = 'automl-classifier' # project folder project_folder = './automl-classifier' import os output = {} output['SDK version'] = azureml.core.VERSION output['Subscription ID'] = ws.subscription_id output['Workspace'] = ws.name output['Resource Group'] = ws.resource_group output['Location'] = ws.location output['Project Directory'] = project_folder pd.set_option('display.max_colwidth', -1) pd.DataFrame(data=output, index=['']).T ``` ## Explore data The initial training tutorial used a high-resolution version of the MNIST dataset (28x28 pixels). Since auto training requires many iterations, this tutorial uses a smaller resolution version of the images (8x8 pixels) to demonstrate the concepts while speeding up the time needed for each iteration. ``` from sklearn import datasets digits = datasets.load_digits() # Exclude the first 100 rows from training so that they can be used for test. X_train = digits.data[100:,:] y_train = digits.target[100:] ``` ### Display some sample images Load the data into `numpy` arrays. Then use `matplotlib` to plot 30 random images from the dataset with their labels above them. ``` count = 0 sample_size = 30 plt.figure(figsize = (16, 6)) for i in np.random.permutation(X_train.shape[0])[:sample_size]: count = count + 1 plt.subplot(1, sample_size, count) plt.axhline('') plt.axvline('') plt.text(x = 2, y = -2, s = y_train[i], fontsize = 18) plt.imshow(X_train[i].reshape(8, 8), cmap = plt.cm.Greys) plt.show() ``` You now have the necessary packages and data ready for auto training for your model. ## Auto train a model To auto train a model, first define settings for autogeneration and tuning and then run the automatic classifier. ### Define settings for autogeneration and tuning Define the experiment parameters and models settings for autogeneration and tuning. |Property| Value in this tutorial |Description| |----|----|---| |**primary_metric**|AUC Weighted | Metric that you want to optimize.| |**max_time_sec**|12,000|Time limit in seconds for each iteration| |**iterations**|20|Number of iterations. In each iteration, the model trains with the data with a specific pipeline| |**n_cross_validations**|3|Number of cross validation splits| |**exit_score**|0.9985|*double* value indicating the target for *primary_metric*. Once the target is surpassed the run terminates| |**blacklist_algos**|['kNN','LinearSVM']|*Array* of *strings* indicating algorithms to ignore. ``` from azureml.train.automl import AutoMLConfig ##Local compute Automl_config = AutoMLConfig(task = 'classification', primary_metric = 'AUC_weighted', max_time_sec = 12000, iterations = 20, n_cross_validations = 3, exit_score = 0.9985, blacklist_algos = ['kNN','LinearSVM'], X = X_train, y = y_train, path=project_folder) ``` ### Run the automatic classifier Start the experiment to run locally. Define the compute target as local and set the output to true to view progress on the experiment. ``` from azureml.core.experiment import Experiment experiment=Experiment(ws, experiment_name) local_run = experiment.submit(Automl_config, show_output=True) ``` ## Explore the results Explore the results of automatic training with a Jupyter widget or by examining the experiment history. ### Jupyter widget Use the Jupyter notebook widget to see a graph and a table of all results. ``` from azureml.train.widgets import RunDetails RunDetails(local_run).show() ``` ### Retrieve all iterations View the experiment history and see individual metrics for each iteration run. ``` children = list(local_run.get_children()) metricslist = {} for run in children: properties = run.get_properties() metrics = {k: v for k, v in run.get_metrics().items() if isinstance(v, float)} metricslist[int(properties['iteration'])] = metrics import pandas as pd rundata = pd.DataFrame(metricslist).sort_index(1) rundata ``` ## Register the best model Use the `local_run` object to get the best model and register it into the workspace. ``` # find the run with the highest accuracy value. best_run, fitted_model = local_run.get_output() # register model in workspace description = 'Automated Machine Learning Model' tags = None local_run.register_model(description=description, tags=tags) local_run.model_id # Use this id to deploy the model as a web service in Azure ``` ## Test the best model Use the model to predict a few random digits. Display the predicted and the image. Red font and inverse image (white on black) is used to highlight the misclassified samples. Since the model accuracy is high, you might have to run the following code a few times before you can see a misclassified sample. ``` # find 30 random samples from test set n = 30 X_test = digits.data[:100, :] y_test = digits.target[:100] sample_indices = np.random.permutation(X_test.shape[0])[0:n] test_samples = X_test[sample_indices] # predict using the model result = fitted_model.predict(test_samples) # compare actual value vs. the predicted values: i = 0 plt.figure(figsize = (20, 1)) for s in sample_indices: plt.subplot(1, n, i + 1) plt.axhline('') plt.axvline('') # use different color for misclassified sample font_color = 'red' if y_test[s] != result[i] else 'black' clr_map = plt.cm.gray if y_test[s] != result[i] else plt.cm.Greys plt.text(x = 2, y = -2, s = result[i], fontsize = 18, color = font_color) plt.imshow(X_test[s].reshape(8, 8), cmap = clr_map) i = i + 1 plt.show() ``` ## Next steps In this Azure Machine Learning tutorial, you used Python to: > * Set up your development environment > * Access and examine the data > * Train using an automated classifier locally with custom parameters > * Explore the results > * Review training results > * Register the best model Learn more about [how to configure settings for automatic training](https://aka.ms/aml-how-to-configure-auto) or [how to use automatic training on a remote resource](https://aka.ms/aml-how-to-auto-remote).
github_jupyter
``` import glob, os import pandas as pd import shutil import matplotlib.pyplot as plt from matplotlib.collections import PolyCollection from matplotlib import colors as mcolors import numpy as np import math from sklearn.preprocessing import MinMaxScaler, StandardScaler from sklearn.neural_network import MLPClassifier from sklearn.model_selection import train_test_split from sklearn.metrics import plot_confusion_matrix root_path = f"G:/Research/AI_STM/gpspec/dpath/" WS2_folder_path = "WS2_defects/" Au_folder_path = "Au/" path = root_path + WS2_folder_path ``` # Create annotation file ``` all_subdir = [name for name in os.listdir(root_path) if os.path.isdir(root_path + name)] s = 0 frames = [] for i, subdir in enumerate(all_subdir): path = root_path + subdir +"/" print(path) # get list of files with .dat extension files = glob.glob(f"{path}*.dat") # print(files) n = len(files) print(f"{n} STS files found.") labels = np.full((n,), i) sts_ann_df = pd.DataFrame(list(zip(files,labels)), columns=['files','category']) frames.append(sts_ann_df) s+=1 sts_ann_df.head() out = pd.concat(frames) out out.to_csv(root_path + "annotations.dat",index=False) ``` # Explore the STS Dataset ``` # Grab bias sweep column from first data file, since every sample was taken with the same sweep. # This will be the independent variable for the water fall plot. bias_df = pd.read_csv(sts_ann_df['files'][0], sep="\s+", skiprows=10, usecols=[0], names=['Bias (V)']) bias_sweep = bias_df.to_numpy().flatten() # Read each file with extension .dat and normalize the LIY channel (dI/dV) frames = [] for file in files: sts_df = pd.read_csv(file, sep="\s+", skiprows=10, usecols=[0,1,3], names=['Bias (V)', 'Current (A)', 'dI/dV (A/V)']) frames.append(sts_df) sts_dfs = pd.concat([df['dI/dV (A/V)'] for df in frames], axis=1) sts_dfs.head() out = pd.concat([bias_df,sts_dfs],axis=1) out.to_csv(folder_path + "/WS2_defects_all_dIdV.dat",index=False) plt.imshow(sts_dfs.T, interpolation='nearest') plt.xticks(np.arange(0,len(bias_sweep), 250),bias_sweep[::250]) plt.show() ``` # Standardize the STS Data ``` scaler_std = StandardScaler() sts_std = scaler_std.fit_transform(sts_dfs) sts_std_df = pd.DataFrame(sts_std) sts_std_df.columns = ['dI/dV' for n in range(len(sts_std_df.columns))] plt.imshow(sts_std_df.T) plt.show() for sts in sts_std: plt.plot(sts) plt.show() scaler_MinMax = MinMaxScaler() sts_MinMax = scaler_MinMax.fit_transform(sts_dfs) sts_MinMax_df = pd.DataFrame(sts_MinMax) sts_MinMax_df.columns = ['dI/dV' for n in range(len(sts_MinMax_df.columns))] plt.imshow(sts_MinMax_df.T) plt.show() for sts in sts_MinMax: plt.plot(sts) plt.show() out = pd.concat([bias_df, sts_std_df],axis=1) out.to_csv(folder_path + "/WS2_defects_all_dIdV_standardized.dat",index=False) ``` # Plot the FFT of the STS spectra ``` R = STS_std_df.apply(lambda col: np.fft.fft(col).real, result_type='expand') J = STS_std_df.apply(lambda col: np.fft.fft(col).imag, result_type='expand') freq = np.fft.fftfreq(sts_dfs.iloc[:,0].shape[-1]) freq_df = pd.DataFrame(freq) plt.plot(freq, R) plt.show() plt.plot(freq, J) plt.show() outR = pd.concat([freq_df, R],axis=1) outR.to_csv(folder_path + "/WS2_defects_all_dIdV_std_fft-R.dat",index=False) outJ = pd.concat([freq_df, J],axis=1) outJ.to_csv(folder_path + "/WS2_defects_all_dIdV_std_fft-J.dat",index=False) # fig = plt.figure() # ax = fig.gca(projection='3d') # def cc(arg): # return mcolors.to_rgba(arg, alpha=0.6) # verts = [] # xs = bias_sweep # ys = list(range(n)) # for z in sts_dfs: # verts.append(list(zip(xs, ys)) # poly = PolyCollection(verts, facecolors=[cc('r'), cc('g'), cc('b'), cc('y')]) # poly.set_alpha(0.7) # ax.add_collection3d(poly, zs=sts_dfs.T, zdir='y') # ax.set_xlabel('X') # ax.set_xlim3d(0, 10) # ax.set_ylabel('Y') # ax.set_ylim3d(-1, 4) # ax.set_zlabel('Z') # ax.set_zlim3d(0, 1) # plt.show() def normalize_dIdV(row): I = row['Current (A)'] V = row['Bias (V)'] dIdV = row['dI/dV (A/V)'] return (dIdV)/(I/V) frames_normalized = [df.apply(normalize_dIdV, axis=1, result_type='expand') for df in frames] sts_norm_dfs = pd.concat(frames_normalized,1) sts_norm_dfs.columns = ['dI/dV (a.u.)' for n in range(len(sts_norm_dfs.columns))] sts_norm_dfs.head() # plt.xticks(bias_df.values) plt.imshow(sts_norm_dfs.T, interpolation='none') scaler = MinMaxScaler() Z = scaler.fit_transform(sts_norm_dfs) plt.imshow(Z.T, interpolation='nearest') out = pd.concat([bias_df, pd.DataFrame(Z)],axis=1) out.to_csv(folder_path + "/WS2_defects_all_dIdV_normalized_standardized.dat",index=False) sts_df0 = pd.read_csv(files[177], sep="\s+", skiprows=10, usecols=[0,1,3], names=['Bias (V)', 'Current (A)', 'dI/dV (A/V)']) dIdV_norm = sts_df0.apply(normalize_dIdV, axis=1, result_type='expand') plt.plot(sts_df0['Bias (V)'], sts_df0['dI/dV (A/V)']) plt.plot(sts_df0['Bias (V)'], dIdV_norm) # plt.xticks(np.arange(0,len(bias_sweep), 250),bias_sweep[::250]) plt.show() dIdV_fft = np.fft.fft(sts_df0['dI/dV (A/V)']) dIdV_fft_freq = np.fft.fftfreq(sts_df0['dI/dV (A/V)'].shape[-1]) plt.plot(dIdV_fft_freq, dIdV_fft.real, dIdV_fft_freq, dIdV_fft.imag) ``` # Scikit Learn MPL Classifer ``` clf = MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(5, 2), random_state=1) clf.fit(X, y) label = 1 num_classes = 2 label_onehot = np.zeros( num_classes) label_onehot[label] = 1 label_onehot x = np.random.rand(10) z = np.zeros(3, dtype=float) np.concatenate((x,z)) ``` # Explore synthetic S vacancy in WS2 STS map with drift compensation ``` STS = np.load('G:\Research\AI_STM\gpspec\dpath\train\au_fcc\dI_dV00008_Au_3.npy') STS.shape STS[:,:,0].shape plt.imshow(STS[:,:,600]) plt.show() plt.plot(STS[40,40,:]) plt.show() plt.plot(STS[60,40,:]) plt.show() # X = STS.flatten() X = STS.reshape(-1, 1200) X.shape plt.figure(figsize=(8, 20)) plt.imshow(X) plt.show() from scipy.signal import find_peaks, peak_prominences, savgol_filter def locate_peaks(signal,filter_window_length=0,filter_polyorder=1,finder_prominence=0, width=1): """ Search through the data and find peaks. """ # Smooth data before peak finding (to reduce the influence of noise) if filter_window_length: signal = savgol_filter(signal, filter_window_length, filter_polyorder) # Find the peaks in the denoised intensity data. peak_indices, peak_properties = find_peaks(signal, prominence=finder_prominence, wlen=30, width=width) return peak_indices , peak_properties summed_STS = np.sum(STS, axis=2) plt.imshow(summed_STS) plt.show() print(summed_STS[0,0]) summed_STS = summed_STS - summed_STS[0,0] plt.imshow(summed_STS) plt.show() print(summed_STS[0,0]) summed_STS[summed_STS != 0.0] = 1.0 plt.imshow(summed_STS) plt.show() summed_STS.shape root_path = f"G:/Research/AI_STM/sts-storage/dpath/" np.savetxt(root_path + "STS-cube_annotations.csv", summed_STS, delimiter=",") y = STS[39:40,39:40] print(y.shape) t_peak_indices, _ = locate_peaks(y.flatten(), filter_window_length=0, finder_prominence=3e-14, width=3) t_peak_indices n_max = 3 for x in STS: for y in x: peak_indices, _ = locate_peaks(y.flatten(), filter_window_length=0, finder_prominence=3e-14, width=3) n = len(peak_indices) if n > n_max: b_peak_indices = np.apply_along_axis(lambda yi: locate_peaks(yi.flatten(), filter_window_length=0, finder_prominence=3e-14, width=3)[0], 2, STS) b_peak_indices = b_peak_indices.flatten() b_peak_indices.shape test_spectrum = STS[40,40,:] peak_info = locate_peaks(test_spectrum, filter_window_length=0, finder_prominence=3e-14, width=3) peak_indices = peak_info[0] peak_properties = peak_info[1] print(peak_indices) plt.plot(test_spectrum) plt.plot(peak_indices, test_spectrum[peak_indices], 'o') plt.plot(t_peak_indices, test_spectrum[t_peak_indices], 'x') plt.show() from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from matplotlib import cm import numpy as np from sys import argv # x,y,z = np.loadtxt('your_file', unpack=True) x,y,z = STS fig = plt.figure() ax = Axes3D(fig) surf = ax.plot_trisurf(x, y, z, cmap=cm.jet, linewidth=0.1) fig.colorbar(surf, shrink=0.5, aspect=5) plt.savefig('teste.pdf') plt.show() ```
github_jupyter
Sveučilište u Zagrebu Fakultet elektrotehnike i računarstva ## Strojno učenje 2018/2019 http://www.fer.unizg.hr/predmet/su ------------------------------ ### Laboratorijska vježba 5: Probabilistički grafički modeli, naivni Bayes, grupiranje i vrednovanje klasifikatora *Verzija: 1.4 Zadnji put ažurirano: 11. siječnja 2019.* (c) 2015-2019 Jan Šnajder, Domagoj Alagić Objavljeno: **11. siječnja 2019.** Rok za predaju: **21. siječnja 2019. u 07:00h** ------------------------------ ### Upute Peta laboratorijska vježba sastoji se od tri zadatka. U nastavku slijedite upute navedene u ćelijama s tekstom. Rješavanje vježbe svodi se na **dopunjavanje ove bilježnice**: umetanja ćelije ili više njih **ispod** teksta zadatka, pisanja odgovarajućeg kôda te evaluiranja ćelija. Osigurajte da u potpunosti **razumijete** kôd koji ste napisali. Kod predaje vježbe, morate biti u stanju na zahtjev asistenta (ili demonstratora) preinačiti i ponovno evaluirati Vaš kôd. Nadalje, morate razumjeti teorijske osnove onoga što radite, u okvirima onoga što smo obradili na predavanju. Ispod nekih zadataka možete naći i pitanja koja služe kao smjernice za bolje razumijevanje gradiva (**nemojte pisati** odgovore na pitanja u bilježnicu). Stoga se nemojte ograničiti samo na to da riješite zadatak, nego slobodno eksperimentirajte. To upravo i jest svrha ovih vježbi. Vježbe trebate raditi **samostalno**. Možete se konzultirati s drugima o načelnom načinu rješavanja, ali u konačnici morate sami odraditi vježbu. U protivnome vježba nema smisla. ``` # Učitaj osnovne biblioteke... import sklearn import codecs import mlutils import matplotlib.pyplot as plt import pgmpy as pgm %pylab inline ``` ### 1. Probabilistički grafički modeli -- Bayesove mreže Ovaj zadatak bavit će se Bayesovim mrežama, jednim od poznatijih probabilističkih grafičkih modela (*probabilistic graphical models*; PGM). Za lakše eksperimentiranje koristit ćemo programski paket [`pgmpy`](https://github.com/pgmpy/pgmpy). Molimo Vas da provjerite imate li ovaj paket te da ga instalirate ako ga nemate. #### (a) Prvo ćemo pogledati udžbenički primjer s prskalicom. U ovom primjeru razmatramo Bayesovu mrežu koja modelira zavisnosti između oblačnosti (slučajna varijabla $C$), kiše ($R$), prskalice ($S$) i mokre trave ($W$). U ovom primjeru također pretpostavljamo da već imamo parametre vjerojatnosnih distribucija svih čvorova. Ova mreža prikazana je na sljedećoj slici: ![This](http://www.fer.unizg.hr/_download/repository/bayes-net-sprinkler.jpg) Koristeći paket `pgmpy`, konstruirajte Bayesovu mrežu iz gornjeg primjera. Zatim, koristeći **egzaktno** zaključivanje, postavite sljedeće posteriorne upite: $P(w=1)$, $P(s=1|w=1)$, $P(r=1|w=1)$, $P(c=1|s=1, r=1)$ i $P(c=1)$. Provedite zaključivanje na papiru i uvjerite se da ste ispravno konstruirali mrežu. Pomoći će vam službena dokumentacija te primjeri korištenja (npr. [ovaj](https://github.com/pgmpy/pgmpy_notebook/blob/master/notebooks/2.%20Bayesian%20Networks.ipynb)). ``` from pgmpy.models import BayesianModel from pgmpy.factors.discrete.CPD import TabularCPD from pgmpy.inference import VariableElimination model = BayesianModel([('C', 'S'), ('C', 'R'), ('S', 'WG'), ('R', 'WG')]) c_cpd = TabularCPD(variable='C', variable_card=2, values=[[0.5, 0.5]]) s_cpd = TabularCPD(variable='S', variable_card=2, values=[[0.5, 0.9], [0.5, 0.1]], evidence=['C'], evidence_card=[2]) r_cpd = TabularCPD(variable='R', variable_card=2, values=[[0.8, 0.2], [0.2, 0.8]], evidence=['C'], evidence_card=[2]) wg_cpd = TabularCPD(variable='WG', variable_card=2, values=[[1, 0.1, 0.1, 0.01], [0, 0.9, 0.9, 0.99]], evidence=['S', 'R'], evidence_card=[2, 2]) model.add_cpds(c_cpd, s_cpd, r_cpd, wg_cpd) print(f"Model correct: {model.check_model()}") infer = VariableElimination(model) print('P(WG=1)') print(infer.query(['WG'])['WG']) print('P(S=1|WG=1)') print(infer.query(['S'], evidence={'WG': 1})['S']) print('P(R=1|WG=1)') print(infer.query(['R'], evidence={'WG': 1})['R']) print('P(C=1|S=1, R=1)') print(infer.query(['C'], evidence={'S': 1, 'R': 1})['C']) print('P(C=1)') print(infer.query(['C'])['C']) ``` **Q:** Koju zajedničku vjerojatnosnu razdiobu ova mreža modelira? Kako tu informaciju očitati iz mreže? **Q:** U zadatku koristimo egzaktno zaključivanje. Kako ono radi? **Q:** Koja je razlika između posteriornog upita i MAP-upita? **Q:** Zašto je vjerojatnost $P(c=1)$ drugačija od $P(c=1|s=1,r=1)$ ako znamo da čvorovi $S$ i $R$ nisu roditelji čvora $C$? #### (b) **Efekt objašnjavanja** (engl. *explaining away*) zanimljiv je fenomen u kojem se događa da se dvije varijable "natječu" za objašnjavanje treće. Ovaj fenomen može se primijetiti na gornjoj mreži. U tom se slučaju varijable prskalice ($S$) i kiše ($R$) "natječu" za objašnjavanje mokre trave ($W$). Vaš zadatak je pokazati da se fenomen zaista događa. ``` print('P(S=1|WG=1)') print(infer.query(['S'], evidence={'WG': 1})['S']) print('P(S=1|WG=1, R=1)') print(infer.query(['S'], evidence={'WG': 1, 'R': 1})['S']) print('P(R=1|WG=1)') print(infer.query(['R'], evidence={'WG': 1})['R']) print('P(R=1|WG=1, S=1)') print(infer.query(['R'], evidence={'WG': 1, 'S': 1})['R']) ``` **Q:** Kako biste svojim riječima opisali ovaj fenomen, koristeći se ovim primjerom? #### (c) Koristeći [`BayesianModel.is_active_trail`](http://pgmpy.org/models.html#pgmpy.models.BayesianModel.BayesianModel.is_active_trail) provjerite jesu li varijable oblačnosti ($C$) i mokre trave ($W$) uvjetno nezavisne. Što mora vrijediti kako bi te dvije varijable bile uvjetno nezavisne? Provjerite korištenjem iste funkcije. ``` print(model.is_active_trail('WG', 'C')) print(model.is_active_trail(start='WG', end='C', observed=['R', 'S'])) ``` **Q:** Kako možemo na temelju grafa saznati koje dvije varijable su, uz neka opažanja, uvjetno nezavisne? **Q:** Zašto bismo uopće htjeli znati koje su varijable u mreži uvjetno nezavisne? ### 2. Vrednovanje modela (klasifikatora) Kako bismo se uvjerili koliko naš naučeni model zapravo dobro radi, nužno je provesti evaluaciju modela. Ovaj korak od presudne je važnosti u svim primjenama strojnog učenja, pa je stoga bitno znati provesti evaluaciju na ispravan način. Vrednovat ćemo modele na stvarnom skupu podataka [*SMS Spam Collection*](https://archive.ics.uci.edu/ml/datasets/SMS+Spam+Collection) [1], koji se sastoji od 5,574 SMS-poruka klasificiranih u dvije klase: spam (oznaka: *spam*) i ne-spam (oznaka: *ham*). Ako već niste, preuzmite skup podataka s poveznice ili sa stranice kolegija i stavite ga u radni direktorij (otpakirajte arhivu i preimenujte datoteku u `spam.csv` po potrebi). Sljedeći komad kôda učitava skup podataka i dijeli ga na podskupove za učenje i testiranje. [1] *Almeida, T.A., GÃmez Hidalgo, J.M., Yamakami, A. Contributions to the Study of SMS Spam Filtering: New Collection and Results. Proceedings of the 2011 ACM Symposium on Document Engineering (DOCENG'11), Mountain View, CA, USA, 2011.* ``` from sklearn.model_selection import train_test_split spam_X, spam_y = mlutils.load_SMS_dataset('./spam.csv') spam_X_train, spam_X_test, spam_y_train, spam_y_test = \ train_test_split(spam_X, spam_y, train_size=0.7, test_size=0.3, random_state=69) ``` #### (a) Prije nego što krenemo u vrednovanje modela za klasifikaciju spama, upoznat ćete se s jednostavnijom apstrakcijom cjelokupnog procesa učenja modela u biblioteci `scikit-learn`. Ovo je korisno zato što se učenje modela često sastoji od mnoštva koraka prije sâmog pozivanja magične funkcije `fit`: ekstrakcije podataka, ekstrakcije značajki, standardizacije, skaliranja, nadopunjavanjem nedostajućih vrijednosti i slično. U "standardnom pristupu", ovo se svodi na pozamašan broj linija kôda u kojoj konstantno proslijeđujemo podatke iz jednog koraka u sljedeći, tvoreći pritom cjevovod izvođenja. Osim nepreglednosti, ovakav pristup je često i sklon pogreškama, s obzirom na to da je dosta jednostavno proslijediti pogrešan skup podataka i ne dobiti pogrešku pri izvođenju kôda. Stoga je u biblioteci `scikit-learn` uveden razred [`pipeline.Pipeline`](http://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html). Kroz ovaj razred, svi potrebni koraci učenja mogu se apstrahirati iza jednog cjevovoda, koji je opet zapravo model s `fit` i `predict` funkcijama. U ovom zadatku ćete napraviti samo jednostavni cjevovod modela za klasifikaciju teksta, koji se sastoji od pretvorbe teksta u vektorsku reprezentaciju vreće riječi s TF-IDF-težinama, redukcije dimenzionalnosti pomoću krnje dekompozicije singularnih vrijednosti, normalizacije, te konačno logističke regresije. **NB:** Nije sasvim nužno znati kako rade ovi razredi pomoću kojih dolazimo do konačnih značajki, ali preporučamo da ih proučite ako vas zanima (posebice ako vas zanima obrada prirodnog jezika). ``` from sklearn.pipeline import Pipeline from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.decomposition import TruncatedSVD from sklearn.preprocessing import Normalizer from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score ``` Prvo, prilažemo kôd koji to radi "standardnim pristupom": ``` # TF-IDF vectorizer = TfidfVectorizer(stop_words="english", ngram_range=(1, 2), max_features=500) spam_X_feat_train = vectorizer.fit_transform(spam_X_train) # Smanjenje dimenzionalnosti reducer = TruncatedSVD(n_components=300, random_state=69) spam_X_feat_train = reducer.fit_transform(spam_X_feat_train) # Normaliziranje normalizer = Normalizer() spam_X_feat_train = normalizer.fit_transform(spam_X_feat_train) # NB clf = LogisticRegression() clf.fit(spam_X_feat_train, spam_y_train) # I sada ponovno sve ovo za testne podatke. spam_X_feat_test = vectorizer.transform(spam_X_test) spam_X_feat_test = reducer.transform(spam_X_feat_test) spam_X_feat_test = normalizer.transform(spam_X_feat_test) print(accuracy_score(spam_y_test, clf.predict(spam_X_feat_test))) x_test = ["You were selected for a green card, apply here for only 50 USD!!!", "Hey, what are you doing later? Want to grab a cup of coffee?"] x_test = vectorizer.transform(x_test) x_test = reducer.transform(x_test) x_test = normalizer.transform(x_test) print(clf.predict(x_test)) ``` Vaš zadatak izvesti je dani kôd korištenjem cjevovoda. Proučite razred [`pipeline.Pipeline`](http://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html). **NB** Ne treba vam više od svega nekoliko naredbi. ``` vectorizer = TfidfVectorizer(stop_words="english", ngram_range=(1, 2), max_features=500) reducer = TruncatedSVD(n_components=300, random_state=69) normalizer = Normalizer() clf = LogisticRegression() pipe_clf = Pipeline(steps=[ ('vectorizer', vectorizer), ('reducer', reducer), ('normalizer', normalizer), ('log_reg', clf)]) pipe_clf.fit(spam_X_train, spam_y_train) print(f"Pipeline classifier accuracy: {accuracy_score(spam_y_test, pipe_clf.predict(spam_X_test))}") x_test = ["You were selected for a green card, apply here for only 50 USD!!!", "Hey, what are you doing later? Want to grab a cup of coffee?"] print(pipe_clf.predict(x_test)) ``` #### (b) U prošlom smo podzadatku ispisali točnost našeg modela. Ako želimo vidjeti koliko je naš model dobar po ostalim metrikama, možemo iskoristiti bilo koju funkciju iz paketa [`metrics`](http://scikit-learn.org/stable/modules/classes.html#module-sklearn.metrics). Poslužite se funkcijom [`metrics.classification_report`](http://scikit-learn.org/stable/modules/generated/sklearn.metrics.classification_report.html#sklearn.metrics.classification_report), koja ispisuje vrijednosti najčešćih metrika. (Obavezno koristite naredbu `print` kako ne biste izgubili format izlaza funkcije.) Ispišite ponovno točnost za usporedbu. ``` from sklearn.metrics import classification_report, accuracy_score, confusion_matrix tn, fp, fn, tp = confusion_matrix(spam_y_test, pipe_clf.predict(spam_X_test)).ravel() print('TP', tp) print('TN', tn) print('FP', fp) print('FN', fn) print(classification_report(spam_y_test, pipe_clf.predict(spam_X_test), target_names=['spam', 'ham'])) ``` Potreba za drugim metrikama osim točnosti može se vidjeti pri korištenju nekih osnovnih modela (engl. *baselines*). Možda najjednostavniji model takvog tipa je model koji svrstava sve primjere u većinsku klasu (engl. *most frequent class*; MFC) ili označuje testne primjere nasumično (engl. *random*). Proučite razred [`dummy.DummyClassifier`](http://scikit-learn.org/stable/modules/generated/sklearn.dummy.DummyClassifier.html) i pomoću njega stvorite spomenute osnovne klasifikatore. Opet ćete trebati iskoristiti cjevovod kako biste došli do vektorskog oblika ulaznih primjera, makar ovi osnovni klasifikatori koriste samo oznake pri predikciji. ``` from sklearn.dummy import DummyClassifier vectorizer = TfidfVectorizer(stop_words="english", ngram_range=(1, 2), max_features=500) reducer = TruncatedSVD(n_components=300, random_state=69) normalizer = Normalizer() clf = DummyClassifier(strategy='most_frequent') pipe_clf = Pipeline(steps=[ ('vectorizer', vectorizer), ('reducer', reducer), ('normalizer', normalizer), ('dummy_clf', clf)]) pipe_clf.fit(spam_X_train, spam_y_train) print(f"Most frequent dummy classifier accuracy: {accuracy_score(spam_y_test, pipe_clf.predict(spam_X_test))}") x_test = ["You were selected for a green card, apply here for only 50 USD!!!", "Hey, what are you doing later? Want to grab a cup of coffee?"] print(pipe_clf.predict(x_test)) tn, fp, fn, tp = confusion_matrix(spam_y_test, pipe_clf.predict(spam_X_test)).ravel() print('TP', tp) print('TN', tn) print('FP', fp) print('FN', fn) print(classification_report(spam_y_test, pipe_clf.predict(spam_X_test), target_names=['spam', 'ham'])) vectorizer = TfidfVectorizer(stop_words="english", ngram_range=(1, 2), max_features=500) reducer = TruncatedSVD(n_components=300, random_state=69) normalizer = Normalizer() clf = DummyClassifier(strategy='uniform') pipe_clf = Pipeline(steps=[ ('vectorizer', vectorizer), ('reducer', reducer), ('normalizer', normalizer), ('dummy_clf', clf)]) pipe_clf.fit(spam_X_train, spam_y_train) print(f"Random dummy classifier accuracy: {accuracy_score(spam_y_test, pipe_clf.predict(spam_X_test))}") x_test = ["You were selected for a green card, apply here for only 50 USD!!!", "Hey, what are you doing later? Want to grab a cup of coffee?"] print(pipe_clf.predict(x_test)) tn, fp, fn, tp = confusion_matrix(spam_y_test, pipe_clf.predict(spam_X_test)).ravel() print('TP', tp) print('TN', tn) print('FP', fp) print('FN', fn) print(classification_report(spam_y_test, pipe_clf.predict(spam_X_test), target_names=['spam', 'ham'])) ``` **Q:** Na temelju ovog primjera objasnite zašto točnost nije uvijek prikladna metrika. **Q:** Zašto koristimo F1-mjeru? #### (c) Međutim, provjera za kakvom smo posegli u prošlom podzadatku nije robusna. Stoga se u strojnom učenju obično koristi k-struka unakrsna provjera. Proučite razred [`model_selection.KFold`](http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.KFold.html#sklearn.model_selection.KFold) i funkciju [`model_selection.cross_val_score`](http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.cross_val_score.html#sklearn.model_selection.cross_val_score) te izračunajte procjenu pogreške na cijelom skupu podataka koristeći peterostruku unakrsnu provjeru. **NB:** Vaš model je sada cjevovod koji sadrži čitavo pretprocesiranje. Također, u nastavku ćemo se ograničiti na točnost, ali ovi postupci vrijede za sve metrike. ``` from sklearn.model_selection import cross_val_score, KFold vectorizer = TfidfVectorizer(stop_words="english", ngram_range=(1, 2), max_features=500) reducer = TruncatedSVD(n_components=300, random_state=69) normalizer = Normalizer() clf = LogisticRegression() pipe_clf = Pipeline(steps=[ ('vectorizer', vectorizer), ('reducer', reducer), ('normalizer', normalizer), ('log_reg', clf)]) score = cross_val_score(X=spam_X, y=spam_y, estimator=pipe_clf, cv=5) print(f"Score: {score}") print(f"Average score: {np.average(score)}") ``` **Q:** Zašto "obična" unakrsna provjera nije dovoljno robusna? **Q:** Što je to stratificirana k-struka unakrsna provjera? Zašto ju često koristimo? #### (d) Gornja procjena pogreške je u redu ako imamo već imamo model (bez ili s fiksiranim hiperparametrima). Međutim, mi želimo koristiti model koji ima optimalne vrijednosti hiperparametara te ih je stoga potrebno optimirati korištenjem pretraživanja po rešetci (engl. *grid search*). Očekivano, biblioteka `scikit-learn` već ima ovu funkcionalnost u razredu [`model_selection.GridSearchCV`](http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html). Jedina razlika vaše implementacije iz prošlih vježbi (npr. kod SVM-a) i ove jest ta da ova koristi k-struku unakrsnu provjeru. Prije optimizacije vrijednosti hiperparametara, očigledno moramo definirati i samu rešetku vrijednosti hiperparametara. Proučite kako se definira ista kroz rječnik u [primjeru](http://scikit-learn.org/stable/auto_examples/model_selection/grid_search_text_feature_extraction.html#sphx-glr-auto-examples-model-selection-grid-search-text-feature-extraction-py). Proučite spomenuti razred te pomoću njega pronađite i ispišite najbolje vrijednosti hiperparametara cjevovoda iz podzadatka (a): `max_features` $\in \{500, 1000\}$ i `n_components` $\in \{ 100, 200, 300 \}$ korištenjem pretraživanja po rešetci na skupu za učenje ($k=3$, kako bi išlo malo brže). ``` from sklearn.model_selection import GridSearchCV pipe_clf = Pipeline(steps=[ ('vectorizer', TfidfVectorizer(stop_words="english", ngram_range=(1, 2))), ('reducer', TruncatedSVD(random_state=69)), ('normalizer', Normalizer()), ('log_reg', LogisticRegression(solver='liblinear'))]) parameters = { 'vectorizer__max_features': (500, 1000), 'reducer__n_components': (100, 200, 300, 400), } grid_search = GridSearchCV(estimator=pipe_clf, param_grid=parameters, cv=3, verbose=1, n_jobs=3) grid_search.fit(X=spam_X, y=spam_y) print(f"Best score: {grid_search.best_score_}") print(f"Best params: {grid_search.best_params_}") ``` **Q:** Koja se metrika optimira pri ovoj optimizaciji? **Q:** Kako biste odredili broj preklopa $k$? #### (e) Ako želimo procijeniti pogrešku, ali pritom i napraviti odabir modela, tada se okrećemo ugniježđenoj k-strukoj unakrsnoj provjeri (engl. *nested k-fold cross validation*). U ovom zadatku ćete ju sami implementirati. Implementirajte funkciju `nested_kfold_cv(clf, param_grid, X, y, k1, k2)` koja provodi ugniježđenu k-struku unakrsnu provjeru. Argument `clf` predstavlja vaš klasifikator, `param_grid` rječnik vrijednosti hiperparametara (isto kao i u podzadatku (d)), `X` i `y` označeni skup podataka, a `k1` i `k2` broj preklopa u vanjskoj, odnosno unutarnjoj petlji. Poslužite se razredima [`model_selection.GridSearchCV`](http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html) i [`model_selection.KFold`](http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.KFold.html). Funkcija vraća listu pogrešaka kroz preklope vanjske petlje. ``` from sklearn.model_selection import GridSearchCV, KFold from sklearn.metrics import accuracy_score def nested_kfold_cv(clf, param_grid, X, y, metric=accuracy_score , k1=10, k2=3, verbose = 1, n_jobs=3): fold_size = int(X.shape[0] / k1) len_X = X.shape[0] scores = [] kf = KFold(n_splits=k1, shuffle=True) for train_index, test_index in kf.split(X): X_train = X[train_index] X_test = X[test_index] y_train = y[train_index] y_test = y[test_index] grid_search = GridSearchCV(estimator=clf, param_grid=param_grid, cv=k2, verbose=verbose, n_jobs=n_jobs) grid_search.fit(X=X_train, y=y_train) estimator = grid_search.best_estimator_ estimator.fit(X_train, y_train) scores.append(metric(estimator.predict(X_test), y_test)) return scores pipe_clf = Pipeline(steps=[ ('vectorizer', TfidfVectorizer(stop_words="english", ngram_range=(1, 2))), ('reducer', TruncatedSVD(random_state=69)), ('normalizer', Normalizer()), ('log_reg', LogisticRegression(solver='liblinear'))]) parameters = { 'vectorizer__max_features': (500, 1000), 'reducer__n_components': (100, 200, 300, 400), } scores = nested_kfold_cv(pipe_clf, parameters, spam_X, spam_y, k1=3) print(f"scores: {scores}") print(f"average score: {np.average(scores)}") ``` **Q:** Kako biste odabrali koji su hiperparametri generalno najbolji, a ne samo u svakoj pojedinačnoj unutarnjoj petlji? **Q:** Čemu u konačnici odgovara procjena generalizacijske pogreške? #### (f) Scenarij koji nas najviše zanima jest usporedba dvaju klasifikatora, odnosno, je li jedan od njih zaista bolji od drugog. Jedini način kako to možemo zaista potvrditi jest statističkom testom, u našem slučaju **uparenim t-testom**. Njime ćemo se baviti u ovom zadatku. Radi bržeg izvođenja, umjetno ćemo generirati podatke koji odgovaraju pogreškama kroz vanjske preklope dvaju klasifikatora (ono što bi vratila funkcija `nested_kfold_cv`): ``` np.random.seed(1337) C1_scores_5folds = np.random.normal(78, 4, 5) C2_scores_5folds = np.random.normal(81, 2, 5) C1_scores_10folds = np.random.normal(78, 4, 10) C2_scores_10folds = np.random.normal(81, 2, 10) C1_scores_50folds = np.random.normal(78, 4, 50) C2_scores_50folds = np.random.normal(81, 2, 50) ``` Iskoristite ugrađenu funkciju [`scipy.stats.ttest_rel`](https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.stats.ttest_rel.html) za provedbu uparenog t-testa i provjerite koji od ova modela je bolji kada se koristi 5, 10 i 50 preklopa. ``` from scipy.stats import ttest_rel print(ttest_rel(C1_scores_5folds, C2_scores_5folds)) print(ttest_rel(C1_scores_10folds, C2_scores_10folds)) print(ttest_rel(C1_scores_50folds, C2_scores_50folds)) ``` **Q:** Koju hipotezu $H_0$ i alternativnu hipotezu $H_1$ testiramo ovim testom? **Q:** Koja pretpostavka na vjerojatnosnu razdiobu primjera je napravljena u gornjem testu? Je li ona opravdana? **Q:** Koji je model u konačnici bolji i je li ta prednost značajna uz $\alpha = 0.05$? ### 3. Grupiranje U ovom zadatku ćete se upoznati s algoritmom k-sredina (engl. *k-means*), njegovim glavnim nedostatcima te pretpostavkama. Također ćete isprobati i drugi algoritam grupiranja: model Gaussovih mješavina (engl. *Gaussian mixture model*). #### (a) Jedan od nedostataka algoritma k-sredina jest taj što unaprijed zahtjeva broj grupa ($K$) u koje će grupirati podatke. Ta informacija nam često nije dostupna (kao što nam nisu dostupne ni oznake primjera) te je stoga potrebno nekako izabrati najbolju vrijednost hiperparametra $K$. Jedan od naivnijih pristupa jest **metoda lakta/koljena** (engl. *elbow method*) koju ćete isprobati u ovom zadatku. U svojim rješenjima koristite ugrađenu implementaciju algoritma k-sredina, dostupnoj u razredu [`cluster.KMeans`](http://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html). **NB**: Kriterijska funkcija algoritma k-sredina još se i naziva **inercijom** (engl. *inertia*). Za naučeni model, vrijednost kriterijske funkcije $J$ dostupna je kroz razredni atribut `inertia_`. ``` from sklearn.datasets import make_blobs Xp, yp = make_blobs(n_samples=300, n_features=2, centers=[[0, 0], [3, 2.5], [0, 4]], cluster_std=[0.45, 0.3, 0.45], random_state=96) plt.scatter(Xp[:,0], Xp[:,1], c=yp, cmap=plt.get_cmap("cool"), s=20) plt.show() ``` Iskoristite skup podataka `Xp` dan gore. Isprobajte vrijednosti hiperparametra $K$ iz $[0,1,\ldots,15]$. Ne trebate dirati nikakve hiperparametre modela osim $K$. Iscrtajte krivulju od $J$ u ovisnosti o broju grupa $K$. Metodom lakta/koljena odredite vrijednost hiperparametra $K$. ``` from sklearn.cluster import KMeans J_vals = [] for K in range(1, 16): km = KMeans(n_clusters=K) km.fit(Xp) J_vals.append(km.inertia_) plt.figure(figsize=(8, 5)) plt.xlabel('K - cluster number') plt.ylabel('J') plt.plot(range(1, 16), J_vals) plt.show() ``` **Q:** Koju biste vrijednost hiperparametra $K$ izabrali na temelju ovog grafa? Zašto? Je li taj odabir optimalan? Kako to znate? **Q:** Je li ova metoda robusna? **Q:** Možemo li izabrati onaj $K$ koji minimizira pogrešku $J$? Objasnite. #### (b) Odabir vrijednosti hiperparametra $K$ može se obaviti na mnoštvo načina. Pored metode lakta/koljena, moguće je isto ostvariti i analizom siluete (engl. *silhouette analysis*). Za to smo pripremili funkciju `mlutils.plot_silhouette` koja za dani broj grupa i podatke iscrtava prosječnu vrijednost koeficijenta siluete i vrijednost koeficijenta svakog primjera (kroz grupe). Vaš je zadatak isprobati različite vrijednosti hiperparametra $K$, $K \in \{2, 3, 5\}$ i na temelju dobivenih grafova odlučiti se za optimalan $K$. ``` for K in [2, 3, 5]: mlutils.plot_silhouette(K, Xp) ``` **Q:** Kako biste se gledajući ove slike odlučili za $K$? **Q:** Koji su problemi ovog pristupa? #### (c) U ovom i sljedećim podzadatcima fokusirat ćemo se na temeljne pretpostavke algoritma k-sredina te što se događa ako te pretpostavke nisu zadovoljene. Dodatno, isprobat ćemo i grupiranje modelom Gaussovih mješavina (engl. *Gaussian Mixture Models*; GMM) koji ne nema neke od tih pretpostavki. Prvo, krenite od podataka `X1`, koji su generirani korištenjem funkcije [`datasets.make_blobs`](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_blobs.html), koja stvara grupe podataka pomoću izotropskih Gaussovih distribucija. ``` from sklearn.datasets import make_blobs X1, y1 = make_blobs(n_samples=1000, n_features=2, centers=[[0, 0], [1.3, 1.3]], cluster_std=[0.15, 0.5], random_state=96) plt.scatter(X1[:,0], X1[:,1], c=y1, cmap=plt.get_cmap("cool"), s=20) plt.show() ``` Naučite model k-sredina (idealno pretpostavljajući $K=2$) na gornjim podatcima i prikažite dobiveno grupiranje (proučite funkciju [`scatter`](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.scatter), posebice argument `c`). ``` km = KMeans(n_clusters=2) km.fit(X1) plt.scatter(X1[:,0], X1[:,1], c=km.predict(X1), cmap=plt.get_cmap("cool"), s=20, marker='D') plt.show() ``` **Q:** Što se dogodilo? Koja je pretpostavka algoritma k-sredina ovdje narušena? **Q:** Što biste morali osigurati kako bi algoritam pronašao ispravne grupe? #### (d) Isprobajte algoritam k-sredina na podatcima generiranim korištenjem funkcije [`datasets.make_circles`](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_circles.html), koja stvara dvije grupe podataka tako da je jedna unutar druge. ``` from sklearn.datasets import make_circles X2, y2 = make_circles(n_samples=1000, noise=0.15, factor=0.05, random_state=96) plt.scatter(X2[:,0], X2[:,1], c=y2, cmap=plt.get_cmap("cool"), s=20) plt.show() ``` Ponovno, naučite model k-sredina (idealno pretpostavljajući $K=2$) na gornjim podatcima i prikažite dobiveno grupiranje (proučite funkciju [`scatter`](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.scatter), posebice argument `c`). ``` km = KMeans(n_clusters=2) km.fit(X2) plt.scatter(X2[:,0], X2[:,1], c=km.predict(X2), cmap=plt.get_cmap("cool"), s=20, marker='D') plt.show() ``` **Q:** Što se dogodilo? Koja je pretpostavka algoritma k-sredina ovdje narušena? **Q:** Što biste morali osigurati kako bi algoritam pronašao ispravne grupe? #### (e) Završno, isprobat ćemo algoritam na sljedećem umjetno stvorenom skupu podataka: ``` X31, y31 = make_blobs(n_samples=1000, n_features=2, centers=[[0, 0]], cluster_std=[0.2], random_state=69) X32, y32 = make_blobs(n_samples=50, n_features=2, centers=[[0.7, 0.5]], cluster_std=[0.15], random_state=69) X33, y33 = make_blobs(n_samples=600, n_features=2, centers=[[0.8, -0.4]], cluster_std=[0.2], random_state=69) plt.scatter(X31[:,0], X31[:,1], c="#00FFFF", s=20) plt.scatter(X32[:,0], X32[:,1], c="#F400F4", s=20) plt.scatter(X33[:,0], X33[:,1], c="#8975FF", s=20) y31 = y31 + np.ones(y31.shape) y32 = y32 + np.ones(y32.shape) * 2 y33 = y33 + np.ones(y33.shape) * 3 # Just join all the groups in a single X. X3 = np.vstack([X31, X32, X33]) y3 = np.hstack([y31, y32, y33]) ``` Ponovno, naučite model k-sredina (ovaj put idealno pretpostavljajući $K=3$) na gornjim podatcima i prikažite dobiveno grupiranje (proučite funkciju [`scatter`](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.scatter), posebice argument `c`). ``` km = KMeans(n_clusters=3) km.fit(X3) plt.scatter(X3[:,0], X3[:,1], c=km.predict(X3), cmap=plt.get_cmap("cool"), s=20, marker='o') plt.show() ``` **Q:** Što se dogodilo? Koja je pretpostavka algoritma k-sredina ovdje narušena? **Q:** Što biste morali osigurati kako bi algoritam pronašao ispravne grupe? #### (f) Sada kada ste se upoznali s ograničenjima algoritma k-sredina, isprobat ćete grupiranje modelom mješavine Gaussa (*Gaussian Mixture Models; GMM*), koji je generalizacija algoritma k-sredina (odnosno, algoritam k-sredina specijalizacija je GMM-a). Implementacija ovog modela dostupna je u [`mixture.GaussianMixture`](http://scikit-learn.org/stable/modules/generated/sklearn.mixture.GaussianMixture.html#sklearn.mixture.GaussianMixture). Isprobajte ovaj model (s istim pretpostavkama o broju grupa) na podacima iz podzadataka (c)-(e). Ne morate mijenjati nikakve hiperparametre ni postavke osim broja komponenti. ``` from sklearn.mixture import GaussianMixture gm = GaussianMixture(n_components=2) gm.fit(X1) plt.scatter(X1[:,0], X1[:,1], c=gm.predict(X1), cmap=plt.get_cmap("cool"), s=20, marker='D') plt.show() gm = GaussianMixture(n_components=2) gm.fit(X2) plt.scatter(X2[:,0], X2[:,1], c=gm.predict(X2), cmap=plt.get_cmap("cool"), s=20, marker='D') plt.show() gm = GaussianMixture(n_components=3) gm.fit(X3) plt.scatter(X3[:,0], X3[:,1], c=gm.predict(X3), cmap=plt.get_cmap("cool"), s=20, marker='o') plt.show() ``` #### (g) Kako vrednovati točnost modela grupiranja ako imamo stvarne oznake svih primjera (a u našem slučaju imamo, jer smo mi ti koji smo generirali podatke)? Često korištena mjera jest **Randov indeks** koji je zapravo pandan točnosti u zadatcima klasifikacije. Implementirajte funkciju `rand_index_score(y_gold, y_predict)` koja ga računa. Funkcija prima dva argumenta: listu stvarnih grupa kojima primjeri pripadaju (`y_gold`) i listu predviđenih grupa (`y_predict`). Dobro će vam doći funkcija [`itertools.combinations`](https://docs.python.org/2/library/itertools.html#itertools.combinations). ``` import itertools as it from scipy.special import binom def rand_index_score(y_gold, y_predict): l = y_gold.shape[0] a = 0 b = 0 for i,j in it.combinations(range(l), 2): gold_pair = (y_gold[i], y_gold[j]) predict_pair = (y_predict[i], y_predict[j]) a = a + 1 if gold_pair[0] == gold_pair[1] and predict_pair[0] == predict_pair[1] else a b = b + 1 if gold_pair[0] != gold_pair[1] and predict_pair[0] != predict_pair[1] else b return (a + b) / binom(l, 2) print('Gaussian Mixture') gm = GaussianMixture(n_components=2) gm.fit(X1) print(f"X1 Rand index: {rand_index_score(gm.predict(X1), y1)}") gm = GaussianMixture(n_components=2) gm.fit(X2) print(f"X2 Rand index: {rand_index_score(gm.predict(X2), y2)}") gm = GaussianMixture(n_components=3) gm.fit(X3) print(f"X3 Rand index: {rand_index_score(gm.predict(X3), y3)}") ``` **Q:** Zašto je Randov indeks pandan točnosti u klasifikacijskim problemima? **Q:** Koji su glavni problemi ove metrike? **Q:** Kako vrednovati kvalitetu grupiranja ako nenamo stvarne oznake primjera? Je li to uopće moguće?
github_jupyter
``` import math import numpy as np import h5py import matplotlib.pyplot as plt import pandas as pd import tensorflow as tf from tensorflow.python.framework import ops %matplotlib inline # Load training data set train = pd.read_json('../input/train.json') train.head() def convert_to_one_hot(arr, c): one_hot_arr = np.zeros((c, arr.shape[1]), dtype=np.int8) for i in range(arr.shape[1]): one_hot_arr[arr[0,i],i] = 1 return one_hot_arr y = np.array([[0,1,0,1,1,1]]) print(y) print(convert_to_one_hot(y,2)) train_flatten = np.array(train['band_1'].tolist()) train_x = train_flatten.transpose() y = np.array(train['is_iceberg'].tolist()).reshape(1,-1) train_y = convert_to_one_hot(y,2) print(train_x.shape) print(train_y.shape) test = pd.read_json('../input/test.json') test.head() raw = np.array(train.iloc[1]['band_1']) raw = raw.reshape((75,75)) plt.imshow(raw) def create_placeholders(n_x, n_y): X = tf.placeholder(tf.float32, name='X', shape=[n_x, None]) Y = tf.placeholder(tf.float32, name='Y', shape=[n_y, None]) return X, Y X, Y = create_placeholders(10, 1) print(X, Y) def initialize_parameters(): """ Initializes parameters to build a neural network with tensorflow. The shapes are: W1 : [25, 12288] b1 : [25, 1] W2 : [12, 25] b2 : [12, 1] W3 : [2, 12] b3 : [2, 1] Returns: parameters -- a dictionary of tensors containing W1, b1, W2, b2, W3, b3 """ tf.set_random_seed(1) # so that your "random" numbers match ours ### START CODE HERE ### (approx. 6 lines of code) W1 = tf.get_variable("W1", [25,5625], initializer = tf.contrib.layers.xavier_initializer(seed = 1)) b1 = tf.get_variable("b1", [25,1], initializer = tf.zeros_initializer()) W2 = tf.get_variable("W2", [12, 25], initializer = tf.contrib.layers.xavier_initializer(seed = 1)) b2 = tf.get_variable("b2", [12, 1], initializer=tf.zeros_initializer()) W3 = tf.get_variable("W3", [2, 12], initializer = tf.contrib.layers.xavier_initializer(seed = 1)) b3 = tf.get_variable("b3", [2, 1], initializer=tf.zeros_initializer()) ### END CODE HERE ### parameters = {"W1": W1, "b1": b1, "W2": W2, "b2": b2, "W3": W3, "b3": b3} return parameters tf.reset_default_graph() with tf.Session() as sess: parameters = initialize_parameters() print("W1 = " + str(parameters["W1"])) print("b1 = " + str(parameters["b1"])) print("W2 = " + str(parameters["W2"])) print("b2 = " + str(parameters["b2"])) def forward_propagation(X, parameters): """ Implements the forward propagation for the model: LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SOFTMAX Arguments: X -- input dataset placeholder, of shape (input size, number of examples) parameters -- python dictionary containing your parameters "W1", "b1", "W2", "b2", "W3", "b3" the shapes are given in initialize_parameters Returns: Z3 -- the output of the last LINEAR unit """ # Retrieve the parameters from the dictionary "parameters" W1 = parameters['W1'] b1 = parameters['b1'] W2 = parameters['W2'] b2 = parameters['b2'] W3 = parameters['W3'] b3 = parameters['b3'] ### START CODE HERE ### (approx. 5 lines) # Numpy Equivalents: Z1 = tf.add(tf.matmul(W1, X), b1) # Z1 = np.dot(W1, X) + b1 A1 = tf.nn.relu(Z1) # A1 = relu(Z1) Z2 = tf.add(tf.matmul(W2, A1), b2) # Z2 = np.dot(W2, a1) + b2 A2 = tf.nn.relu(Z2) # A2 = relu(Z2) Z3 = tf.add(tf.matmul(W3, A2), b3) # Z3 = np.dot(W3,Z2) + b3 A3 = tf.nn.sigmoid(Z3) ### END CODE HERE ### return Z3 tf.reset_default_graph() with tf.Session() as sess: X, Y = create_placeholders(75*75, 6) parameters = initialize_parameters() Z3 = forward_propagation(X, parameters) print("Z3 = " + str(Z3)) def compute_cost(Z3, Y): """ Computes the cost Arguments: Z3 -- output of forward propagation (output of the last LINEAR unit), of shape (6, number of examples) Y -- "true" labels vector placeholder, same shape as Z3 Returns: cost - Tensor of the cost function """ # to fit the tensorflow requirement for tf.nn.softmax_cross_entropy_with_logits(...,...) logits = tf.transpose(Z3) labels = tf.transpose(Y) ### START CODE HERE ### (1 line of code) cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels = labels, logits=logits)) ### END CODE HERE ### return cost tf.reset_default_graph() with tf.Session() as sess: X, Y = create_placeholders(75*75, 1) parameters = initialize_parameters() Z3 = forward_propagation(X, parameters) cost = compute_cost(Z3, Y) print("cost = " + str(cost)) print(type(train_x)) tmp_X = train_x.copy() tmp1 = np.array([]) def random_mini_batches(X, Y, mini_batch_size): tmp_X = X.copy() tmp_Y = Y.copy() while(tmp_X.shape[1]>0): pick_size = tmp_X.shape[1] if tmp_X.shape[1]<mini_batch_size else mini_batch_size mini_batch_x = None mini_batch_y = None for _ in range(pick_size): pick_num = int(np.ceil(np.random.rand() * tmp_X.shape[1]))-1 if mini_batch_x is None: mini_batch_x = tmp_X[:,pick_num].reshape(X.shape[0],-1) mini_batch_y = tmp_Y[:,pick_num].reshape(Y.shape[0],-1) else: mini_batch_x = np.concatenate((mini_batch_x, tmp_X[:,pick_num].reshape(X.shape[0],-1)), axis=1) mini_batch_y = np.concatenate((mini_batch_y, tmp_Y[:,pick_num].reshape(Y.shape[0],-1)), axis=1) tmp_X = np.delete(tmp_X, pick_num, axis=1) tmp_Y = np.delete(tmp_Y, pick_num, axis=1) yield mini_batch_x, mini_batch_y sample_x = np.array([[1,2,3],[4,5,6],[7,8,9]]) sample_y = np.array([[1,0,1],[1,1,0],[0,1,1]]) get_mini_batches = random_mini_batches(sample_x, sample_y,2) print(next(get_mini_batches)) order_id = np.random.rand(1, train_x.shape[1]) print(order_id + train_x) def model(X_train, Y_train, X_test, Y_test, learning_rate = 0.0001, num_epochs = 1000, minibatch_size = 16, print_cost = True): """ Implements a three-layer tensorflow neural network: LINEAR->RELU->LINEAR->RELU->LINEAR->SOFTMAX. Arguments: X_train -- training set, of shape (input size = 12288, number of training examples = 1080) Y_train -- test set, of shape (output size = 6, number of training examples = 1080) X_test -- training set, of shape (input size = 12288, number of training examples = 120) Y_test -- test set, of shape (output size = 6, number of test examples = 120) learning_rate -- learning rate of the optimization num_epochs -- number of epochs of the optimization loop minibatch_size -- size of a minibatch print_cost -- True to print the cost every 100 epochs Returns: parameters -- parameters learnt by the model. They can then be used to predict. """ ops.reset_default_graph() # to be able to rerun the model without overwriting tf variables tf.set_random_seed(1) # to keep consistent results seed = 3 # to keep consistent results (n_x, m) = X_train.shape # (n_x: input size, m : number of examples in the train set) n_y = Y_train.shape[0] # n_y : output size costs = [] # To keep track of the cost # Create Placeholders of shape (n_x, n_y) ### START CODE HERE ### (1 line) X, Y = create_placeholders(n_x, n_y) ### END CODE HERE ### # Initialize parameters ### START CODE HERE ### (1 line) parameters = initialize_parameters() ### END CODE HERE ### # Forward propagation: Build the forward propagation in the tensorflow graph ### START CODE HERE ### (1 line) Z3 = forward_propagation(X, parameters) ### END CODE HERE ### # Cost function: Add cost function to tensorflow graph ### START CODE HERE ### (1 line) cost = compute_cost(Z3, Y) ### END CODE HERE ### # Backpropagation: Define the tensorflow optimizer. Use an AdamOptimizer. ### START CODE HERE ### (1 line) optimizer = tf.train.AdamOptimizer(learning_rate).minimize(cost) ### END CODE HERE ### # Initialize all the variables init = tf.global_variables_initializer() # Start the session to compute the tensorflow graph with tf.Session() as sess: # Run the initialization sess.run(init) # Do the training loop for epoch in range(num_epochs): epoch_cost = 0. # Defines a cost related to an epoch num_minibatches = int(m / minibatch_size) # number of minibatches of size minibatch_size in the train set seed = seed + 1 minibatches = random_mini_batches(X_train, Y_train, minibatch_size) for i_minibatch in range(num_minibatches): # Select a minibatch (minibatch_X, minibatch_Y) = next(minibatches) # IMPORTANT: The line that runs the graph on a minibatch. # Run the session to execute the "optimizer" and the "cost", the feedict should contain a minibatch for (X,Y). ### START CODE HERE ### (1 line) _ , minibatch_cost = sess.run([optimizer, cost], feed_dict={X: minibatch_X, Y: minibatch_Y}) ### END CODE HERE ### epoch_cost += minibatch_cost / num_minibatches # if i_minibatch % 10 == 0: # print("Cost after minibatch {}: {}".format(i_minibatch, minibatch_cost)) # Print the cost every epoch if print_cost == True and epoch % 100 == 0: print ("Cost after epoch %i: %f" % (epoch, epoch_cost)) if print_cost == True and epoch % 5 == 0: costs.append(epoch_cost) # plot the cost plt.plot(np.squeeze(costs)) plt.ylabel('cost') plt.xlabel('iterations (per tens)') plt.title("Learning rate =" + str(learning_rate)) plt.show() # lets save the parameters in a variable parameters = sess.run(parameters) print ("Parameters have been trained!") # Calculate the correct predictions correct_prediction = tf.equal(tf.argmax(Z3), tf.argmax(Y)) # Calculate accuracy on the test set accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) print ("Train Accuracy:", accuracy.eval({X: X_train, Y: Y_train})) # print ("Test Accuracy:", accuracy.eval({X: X_test, Y: Y_test})) return parameters parameters = model(train_x, train_y, train_x, train_y) a = np.array([[[-0.3224172, -0.38405435, 1.13376944], [-1.09989127, -0.17242821, -0.87785842]], [[ 0.90085595, -0.68372786, -0.12289023], [-0.93576943, -0.26788808, 0.53035547]]]) w = np.array([[[ 0.5924728, 0.45194604, 0.057121], [ 0.55607351, 0.55743945, 0.71304905]], [[ 0.38271517, -0.73153098, -1.15498263], [ 1.47016034, 3.9586027, 1.85300949]]]) res = np.multiply(a , w) res.shape np.sum(res)-0.6294416 ```
github_jupyter
# Natural Language Processing ## Importing the libraries ``` import numpy as np import matplotlib.pyplot as plt import pandas as pd ``` ## Importing the dataset ``` dataset = pd.read_csv('Restaurant_Reviews.tsv', delimiter = '\t', quoting = 3) ``` ## Cleaning the texts ``` import re import nltk nltk.download('stopwords') from nltk.corpus import stopwords from nltk.stem.porter import PorterStemmer corpus = [] for i in range(0, 1000): review = re.sub('[^a-zA-Z]', ' ', dataset['Review'][i]) review = review.lower() review = review.split() ps = PorterStemmer() all_stopwords = stopwords.words('english') all_stopwords.remove('not') review = [ps.stem(word) for word in review if not word in set(all_stopwords)] review = ' '.join(review) corpus.append(review) print(corpus) ``` ## Creating the Bag of Words model ``` from sklearn.feature_extraction.text import CountVectorizer cv = CountVectorizer(max_features = 1500) X = cv.fit_transform(corpus).toarray() y = dataset.iloc[:, -1].values ``` ## Splitting the dataset into the Training set and Test set ``` from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.20, random_state = 0) ``` ## Training the Naive Bayes model on the Training set ``` from sklearn.naive_bayes import GaussianNB classifier = GaussianNB() classifier.fit(X_train, y_train) ``` ## Predicting the Test set results ``` y_pred = classifier.predict(X_test) print(np.concatenate((y_pred.reshape(len(y_pred),1), y_test.reshape(len(y_test),1)),1)) ``` ## Making the Confusion Matrix ``` from sklearn.metrics import confusion_matrix, accuracy_score cm = confusion_matrix(y_test, y_pred) print(cm) accuracy_score(y_test, y_pred) print(X_test) ``` ## Predicting if a single review is positive or negative ### Positive review Use our model to predict if the following review: "I love this restaurant so much" is positive or negative. **Solution:** We just repeat the same text preprocessing process we did before, but this time with a single review. ``` new_review = 'I love this restaurant so much' new_review = re.sub('[^a-zA-Z]', ' ', new_review) new_review = new_review.lower() new_review = new_review.split() ps = PorterStemmer() all_stopwords = stopwords.words('english') all_stopwords.remove('not') new_review = [ps.stem(word) for word in new_review if not word in set(all_stopwords)] new_review = ' '.join(new_review) new_corpus = [new_review] new_X_test = cv.transform(new_corpus).toarray() new_y_pred = classifier.predict(new_X_test) print(new_y_pred) ``` The review was correctly predicted as positive by our model. ### Negative review Use our model to predict if the following review: "I hate this restaurant so much" is positive or negative. **Solution:** We just repeat the same text preprocessing process we did before, but this time with a single review. ``` new_review = 'I hate this restaurant so much' new_review = re.sub('[^a-zA-Z]', ' ', new_review) new_review = new_review.lower() new_review = new_review.split() ps = PorterStemmer() all_stopwords = stopwords.words('english') all_stopwords.remove('not') new_review = [ps.stem(word) for word in new_review if not word in set(all_stopwords)] new_review = ' '.join(new_review) new_corpus = [new_review] new_X_test = cv.transform(new_corpus).toarray() new_y_pred = classifier.predict(new_X_test) print(new_y_pred) ``` The review was correctly predicted as negative by our model. ``` ```
github_jupyter
--- # A simple regression example using parametric and non-parametric methods --- This is a simple example where we use two regression methods to enhance the overall data distribution from a dataset. 1. A Linear fit (<i>parametric</i> method). 2. The LOWESS method method (<i>non-parametric</i> method) that is often used in exploratory data analysis to reveal trends in the data. LOWESS stands for Locally Weighted Scatterplot Smoothing. We use a dataset that contains information about used-car resaling prices and their physical characteristics, such as engine power. ``` import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt sns.set(color_codes=True) # Hides warning messages import warnings warnings.filterwarnings("ignore") ``` Extract and clean the data: ``` # Get the headers for this dataset cols = ["symboling", "normalized_losses", "make", "fuel_type", "aspiration", "num_doors", "body_style", "drive_wheels", "engine_location", "wheel_base", "length", "width", "height", "curb_weight", "engine_type", "num_cylinders", "engine_size", "fuel_system", "bore", "stroke", "compression_ratio", "horsepower", "peak_rpm", "city_mpg", "highway_mpg", "price"] # Extract the data cars = pd.read_csv("https://archive.ics.uci.edu/ml/machine-learning-databases/autos//imports-85.data", names=cols) # Replace unknowns by NaNs cars = cars.replace('?', np.nan) # Now lets make things numeric num_vars = ['normalized_losses', "bore", "stroke", "horsepower", "peak_rpm", "price"] for i in num_vars: cars[i] = cars[i].astype('float64') # Delete car data for which price and MPG is unavailable cars = cars.dropna(subset = ['price', 'city_mpg']) # Display the factors and the response (car price) cars.head() ``` ## Parametric method The following figure shows a <i>robust</i> linear fit between the selling price and the cars mileage in cities. The various body styles are indicated. ``` fig = plt.figure(figsize=(8, 8)) ax = sns.lmplot(x="city_mpg", y="price", data=cars, robust=True, height=5, aspect=1.8); sns.scatterplot(x="city_mpg", y="price", hue="body_style", data=cars); ax.set(xlabel='City Milage (miles/gallon)', ylabel='Selling Price ($US)') ax.set(ylim=(0, 50000)) plt.savefig('Parametric fit (Linear fit) all cars.png') plt.savefig('Parametric fit (Linear fit) all cars.pdf') plt.show() ``` The above linear fit does not look very good; it is usually better to do linear regressions with objects in the same class, in this case with cars with the same body style. This is shown in the next figure for wagon vehicles. The fit is better; the data points are uniformly spread along the line. ``` wagon = cars.loc[cars['body_style'] == 'wagon'] fig = plt.figure(figsize=(8, 8)) ax = sns.lmplot(x="city_mpg", y="price", data=wagon, robust=True, height=5, aspect=1.8); sns.scatterplot(x="city_mpg", y="price", hue="body_style", data=wagon); ax.set(xlabel='City Milage (miles/gallon)', ylabel='Selling Price ($US)') ax.set(ylim=(0, 30000)) plt.savefig('Parametric fit (Linear fit) wagon cars.png') plt.savefig('Parametric fit (Linear fit) wagon cars.pdf') plt.show() ``` ## Non-Parametric method The following figure shows a robust non-linear fit through the data. This is more a signal smoothing that an actual fit since no fit parameter is extracted from the analysis. At each point, a linear fit is made using only the data in a neighbourhood of that point. This example shows a well-known fact for buyers on the used-car market; the cars with the largest mileage are less desirable, and are sold at lower prices. ``` import statsmodels.api as sm lowess = sm.nonparametric.lowess x = cars["city_mpg"].array y = cars["price"].array # Non-parametric fit xy = lowess(y, x, frac=0.33, is_sorted=False, return_sorted=True) fig = plt.figure(figsize=(8, 8)) ax = sns.scatterplot(x="city_mpg", y="price", hue="body_style", data=cars); ax.plot(xy[:,0],xy[:,1],color='blue') ax.set_ylim([y.min(), y.max()]) ax.set(xlabel='City Milage (miles/gallon)', ylabel='Selling Price ($US)') ax.set(ylim=(0, 50000)) plt.savefig('Non-parametric fit (LOWESS) all cars.png') plt.savefig('Non-parametric fit (LOWESS) all cars.pdf') plt.show() ```
github_jupyter
# Ungraded Lab: Mask R-CNN Image Segmentation Demo In this lab, you will see how to use a [Mask R-CNN](https://arxiv.org/abs/1703.06870) model from Tensorflow Hub for object detection and instance segmentation. This means that aside from the bounding boxes, the model is also able to predict segmentation masks for each instance of a class in the image. You have already encountered most of the commands here when you worked with the Object Dection API and you will see how you can use it with instance segmentation models. Let's begin! *Note: You should use a TPU runtime for this colab because of the processing requirements for this model. We have already enabled it for you but if you'll be using it in another colab, you can change the runtime from `Runtime --> Change runtime type` then select `TPU`.* ## Installation As mentioned, you will be using the Tensorflow 2 [Object Detection API](https://github.com/tensorflow/models/tree/master/research/object_detection). You can do that by cloning the [Tensorflow Model Garden](https://github.com/tensorflow/models) and installing the object detection packages just like you did in Week 2. ``` # Clone the tensorflow models repository !git clone --depth 1 https://github.com/tensorflow/models %%bash sudo apt install -y protobuf-compiler cd models/research/ protoc object_detection/protos/*.proto --python_out=. cp object_detection/packages/tf2/setup.py . python -m pip install . ``` ## Import libraries ``` import tensorflow as tf import tensorflow_hub as hub import matplotlib import matplotlib.pyplot as plt import numpy as np from six import BytesIO from PIL import Image from six.moves.urllib.request import urlopen from object_detection.utils import label_map_util from object_detection.utils import visualization_utils as viz_utils from object_detection.utils import ops as utils_ops tf.get_logger().setLevel('ERROR') %matplotlib inline ``` ## Utilities For convenience, you will use a function to convert an image to a numpy array. You can pass in a relative path to an image (e.g. to a local directory) or a URL. You can see this in the `TEST_IMAGES` dictionary below. Some paths point to test images that come with the API package (e.g. `Beach`) while others are URLs that point to images online (e.g. `Street`). ``` def load_image_into_numpy_array(path): """Load an image from file into a numpy array. Puts image into numpy array to feed into tensorflow graph. Note that by convention we put it into a numpy array with shape (height, width, channels), where channels=3 for RGB. Args: path: the file path to the image Returns: uint8 numpy array with shape (img_height, img_width, 3) """ image = None if(path.startswith('http')): response = urlopen(path) image_data = response.read() image_data = BytesIO(image_data) image = Image.open(image_data) else: image_data = tf.io.gfile.GFile(path, 'rb').read() image = Image.open(BytesIO(image_data)) (im_width, im_height) = (image.size) return np.array(image.getdata()).reshape( (1, im_height, im_width, 3)).astype(np.uint8) # dictionary with image tags as keys, and image paths as values TEST_IMAGES = { 'Beach' : 'models/research/object_detection/test_images/image2.jpg', 'Dogs' : 'models/research/object_detection/test_images/image1.jpg', # By Américo Toledano, Source: https://commons.wikimedia.org/wiki/File:Biblioteca_Maim%C3%B3nides,_Campus_Universitario_de_Rabanales_007.jpg 'Phones' : 'https://upload.wikimedia.org/wikipedia/commons/thumb/0/0d/Biblioteca_Maim%C3%B3nides%2C_Campus_Universitario_de_Rabanales_007.jpg/1024px-Biblioteca_Maim%C3%B3nides%2C_Campus_Universitario_de_Rabanales_007.jpg', # By 663highland, Source: https://commons.wikimedia.org/wiki/File:Kitano_Street_Kobe01s5s4110.jpg 'Street' : 'https://upload.wikimedia.org/wikipedia/commons/thumb/0/08/Kitano_Street_Kobe01s5s4110.jpg/2560px-Kitano_Street_Kobe01s5s4110.jpg' } ``` ## Load the Model Tensorflow Hub provides a Mask-RCNN model that is built with the Object Detection API. You can read about the details [here](https://tfhub.dev/tensorflow/mask_rcnn/inception_resnet_v2_1024x1024/1). Let's first load the model and see how to use it for inference in the next section. ``` model_display_name = 'Mask R-CNN Inception ResNet V2 1024x1024' model_handle = 'https://tfhub.dev/tensorflow/mask_rcnn/inception_resnet_v2_1024x1024/1' print('Selected model:'+ model_display_name) print('Model Handle at TensorFlow Hub: {}'.format(model_handle)) # This will take 10 to 15 minutes to finish print('loading model...') hub_model = hub.load(model_handle) print('model loaded!') ``` ## Inference You will use the model you just loaded to do instance segmentation on an image. First, choose one of the test images you specified earlier and load it into a numpy array. ``` # Choose one and use as key for TEST_IMAGES below: # ['Beach', 'Street', 'Dogs','Phones'] image_path = TEST_IMAGES['Street'] image_np = load_image_into_numpy_array(image_path) plt.figure(figsize=(24,32)) plt.imshow(image_np[0]) plt.show() ``` You can run inference by simply passing the numpy array of a *single* image to the model. Take note that this model does not support batching. As you've seen in the notebooks in Week 2, this will output a dictionary containing the results. These are described in the `Outputs` section of the [documentation](https://tfhub.dev/tensorflow/mask_rcnn/inception_resnet_v2_1024x1024/1) ``` # run inference results = hub_model(image_np) # output values are tensors and we only need the numpy() # parameter when we visualize the results result = {key:value.numpy() for key,value in results.items()} # print the keys for key in result.keys(): print(key) ``` ## Visualizing the results You can now plot the results on the original image. First, you need to create the `category_index` dictionary that will contain the class IDs and names. The model was trained on the [COCO2017 dataset](https://cocodataset.org/) and the API package has the labels saved in a different format (i.e. `mscoco_label_map.pbtxt`). You can use the [create_category_index_from_labelmap](https://github.com/tensorflow/models/blob/5ee7a4627edcbbaaeb8a564d690b5f1bc498a0d7/research/object_detection/utils/label_map_util.py#L313) internal utility function to convert this to the required dictionary format. ``` PATH_TO_LABELS = './models/research/object_detection/data/mscoco_label_map.pbtxt' category_index = label_map_util.create_category_index_from_labelmap(PATH_TO_LABELS, use_display_name=True) # sample output print(category_index[1]) print(category_index[2]) print(category_index[4]) ``` Next, you will preprocess the masks then finally plot the results. * The result dictionary contains a `detection_masks` key containing segmentation masks for each box. That will be converted first to masks that will overlay to the full image size. * You will also select mask pixel values that are above a certain threshold. We picked a value of `0.6` but feel free to modify this and see what results you will get. If you pick something lower, then you'll most likely notice mask pixels that are outside the object. * As you've seen before, you can use `visualize_boxes_and_labels_on_image_array()` to plot the results on the image. The difference this time is the parameter `instance_masks` and you will pass in the reframed detection boxes to see the segmentation masks on the image. You can see how all these are handled in the code below. ``` # Handle models with masks: label_id_offset = 0 image_np_with_mask = image_np.copy() if 'detection_masks' in result: # convert np.arrays to tensors detection_masks = tf.convert_to_tensor(result['detection_masks'][0]) detection_boxes = tf.convert_to_tensor(result['detection_boxes'][0]) # reframe the the bounding box mask to the image size. detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks( detection_masks, detection_boxes, image_np.shape[1], image_np.shape[2]) # filter mask pixel values that are above a specified threshold detection_masks_reframed = tf.cast(detection_masks_reframed > 0.6, tf.uint8) # get the numpy array result['detection_masks_reframed'] = detection_masks_reframed.numpy() # overlay labeled boxes and segmentation masks on the image viz_utils.visualize_boxes_and_labels_on_image_array( image_np_with_mask[0], result['detection_boxes'][0], (result['detection_classes'][0] + label_id_offset).astype(int), result['detection_scores'][0], category_index, use_normalized_coordinates=True, max_boxes_to_draw=100, min_score_thresh=.70, agnostic_mode=False, instance_masks=result.get('detection_masks_reframed', None), line_thickness=8) plt.figure(figsize=(24,32)) plt.imshow(image_np_with_mask[0]) plt.show() ```
github_jupyter
``` import pandas as pd df_budget = pd.read_csv('Resources/budget_data.csv') dates = df_budget.Date.to_list() profits = df_budget['Profit/Losses'].to_list() number_months = len(dates) total_amount = sum(profits) change_weight = 1/(number_months - 1) average_change = sum((profits[i] - profits[i-1]) * change_weight for i in range(1,len(profits))) average_change = round(average_change, 2) greatest_increase = profits[0] month_g_i = dates[0] greatest_decrease = profits[0] month_g_d = dates[0] for idx, amount in enumerate(profits): if amount > greatest_increase: greatest_increase = amount month_g_i = dates[idx] if amount < greatest_decrease: greatest_decrease = amount month_g_d = dates[idx] my_string = 'Financial Analysis\n' my_string += '-'*20 + '\n' my_string += 'Total Months: ' + str(number_months) +'\n' my_string += 'Total: ' + '$' + str(total_amount) +'\n' my_string += '\tAverage Change: ' + '$' + str(average_change) +'\n' my_string += 'Greatest Inrease in Profits: ' + month_g_i + ' ($' + str(greatest_increase) + ')\n' my_string += 'Greatest Decrease in Profits: ' + month_g_d + ' ($' + str(greatest_decrease) + ')' print(my_string) with open('fin_analysis.txt', 'w') as writer: writer.write(my_string) ``` # Pandas ``` import numpy as np import pandas as pd df_budget = pd.read_csv('Resources/budget_data.csv', index_col='Date') #The total number of months included in the dataset. number_months = df_budget.shape[0] #The net total amount of Profit/Losses over the entire period. total_amount = df_budget['Profit/Losses'].sum() # The average of the changes in Profit/Losses over the entire period. average_change = (df_budget['Profit/Losses'] - df_budget['Profit/Losses'].shift(1)).mean(skipna=True).round(2) #average_change = df_budget['Profit/Losses'].mean(skipna=True) # The greatest increase in profits (date and amount) over the entire period. greatest_increase = df_budget['Profit/Losses'].max() month_g_i = df_budget.index[df_budget['Profit/Losses'] == greatest_increase].tolist()[0] #The greatest decrease in losses (date and amount) over the entire period. greatest_decrease = df_budget['Profit/Losses'].min() month_g_d = df_budget.index[df_budget['Profit/Losses'] == greatest_decrease].tolist()[0] my_string = 'Financial Analysis\n' my_string += '-'*20 + '\n' my_string += 'Total Months: ' + str(number_months) +'\n' my_string += 'Total: ' + '$' + str(total_amount) +'\n' my_string += '\tAverage Change: ' + '$' + str(average_change) +'\n' my_string += 'Greatest Inrease in Profits: ' + month_g_i + ' ($' + str(greatest_increase) + ')\n' my_string += 'Greatest Decrease in Profits: ' + month_g_d + ' ($' + str(greatest_decrease) + ')' print(my_string) with open('fin_anaalysis.txt', 'w') as writer: writer.write(my_string) ```
github_jupyter
<a href="https://colab.research.google.com/github/AI4Finance-Foundation/FinRL/blob/master/FinRL_Ensemble_StockTrading_ICAIF_2020.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Deep Reinforcement Learning for Stock Trading from Scratch: Multiple Stock Trading Using Ensemble Strategy Tutorials to use OpenAI DRL to trade multiple stocks using ensemble strategy in one Jupyter Notebook | Presented at ICAIF 2020 * This notebook is the reimplementation of our paper: Deep Reinforcement Learning for Automated Stock Trading: An Ensemble Strategy, using FinRL. * Check out medium blog for detailed explanations: https://medium.com/@ai4finance/deep-reinforcement-learning-for-automated-stock-trading-f1dad0126a02 * Please report any issues to our Github: https://github.com/AI4Finance-LLC/FinRL-Library/issues * **Pytorch Version** # Content * [1. Problem Definition](#0) * [2. Getting Started - Load Python packages](#1) * [2.1. Install Packages](#1.1) * [2.2. Check Additional Packages](#1.2) * [2.3. Import Packages](#1.3) * [2.4. Create Folders](#1.4) * [3. Download Data](#2) * [4. Preprocess Data](#3) * [4.1. Technical Indicators](#3.1) * [4.2. Perform Feature Engineering](#3.2) * [5.Build Environment](#4) * [5.1. Training & Trade Data Split](#4.1) * [5.2. User-defined Environment](#4.2) * [5.3. Initialize Environment](#4.3) * [6.Implement DRL Algorithms](#5) * [7.Backtesting Performance](#6) * [7.1. BackTestStats](#6.1) * [7.2. BackTestPlot](#6.2) * [7.3. Baseline Stats](#6.3) * [7.3. Compare to Stock Market Index](#6.4) <a id='0'></a> # Part 1. Problem Definition This problem is to design an automated trading solution for single stock trading. We model the stock trading process as a Markov Decision Process (MDP). We then formulate our trading goal as a maximization problem. The algorithm is trained using Deep Reinforcement Learning (DRL) algorithms and the components of the reinforcement learning environment are: * Action: The action space describes the allowed actions that the agent interacts with the environment. Normally, a ∈ A includes three actions: a ∈ {−1, 0, 1}, where −1, 0, 1 represent selling, holding, and buying one stock. Also, an action can be carried upon multiple shares. We use an action space {−k, ..., −1, 0, 1, ..., k}, where k denotes the number of shares. For example, "Buy 10 shares of AAPL" or "Sell 10 shares of AAPL" are 10 or −10, respectively * Reward function: r(s, a, s′) is the incentive mechanism for an agent to learn a better action. The change of the portfolio value when action a is taken at state s and arriving at new state s', i.e., r(s, a, s′) = v′ − v, where v′ and v represent the portfolio values at state s′ and s, respectively * State: The state space describes the observations that the agent receives from the environment. Just as a human trader needs to analyze various information before executing a trade, so our trading agent observes many different features to better learn in an interactive environment. * Environment: Dow 30 consituents The data of the single stock that we will be using for this case study is obtained from Yahoo Finance API. The data contains Open-High-Low-Close price and volume. <a id='1'></a> # Part 2. Getting Started- Load Python Packages <a id='1.1'></a> ## 2.1. Install all the packages through FinRL library ``` # ## install finrl library !pip install git+https://github.com/AI4Finance-LLC/FinRL-Library.git ``` <a id='1.2'></a> ## 2.2. Check if the additional packages needed are present, if not install them. * Yahoo Finance API * pandas * numpy * matplotlib * stockstats * OpenAI gym * stable-baselines * tensorflow * pyfolio <a id='1.3'></a> ## 2.3. Import Packages ``` import warnings warnings.filterwarnings("ignore") import pandas as pd import numpy as np import matplotlib import matplotlib.pyplot as plt # matplotlib.use('Agg') import datetime %matplotlib inline from finrl import config from finrl import config_tickers from finrl.finrl_meta.preprocessor.yahoodownloader import YahooDownloader from finrl.finrl_meta.preprocessor.preprocessors import FeatureEngineer, data_split from finrl.finrl_meta.env_stock_trading.env_stocktrading import StockTradingEnv from finrl.agents.stablebaselines3.models import DRLAgent,DRLEnsembleAgent from finrl.plot import backtest_stats, backtest_plot, get_daily_return, get_baseline from pprint import pprint import sys sys.path.append("../FinRL-Library") import itertools ``` <a id='1.4'></a> ## 2.4. Create Folders ``` import os if not os.path.exists("./" + config.DATA_SAVE_DIR): os.makedirs("./" + config.DATA_SAVE_DIR) if not os.path.exists("./" + config.TRAINED_MODEL_DIR): os.makedirs("./" + config.TRAINED_MODEL_DIR) if not os.path.exists("./" + config.TENSORBOARD_LOG_DIR): os.makedirs("./" + config.TENSORBOARD_LOG_DIR) if not os.path.exists("./" + config.RESULTS_DIR): os.makedirs("./" + config.RESULTS_DIR) ``` <a id='2'></a> # Part 3. Download Data Yahoo Finance is a website that provides stock data, financial news, financial reports, etc. All the data provided by Yahoo Finance is free. * FinRL uses a class **YahooDownloader** to fetch data from Yahoo Finance API * Call Limit: Using the Public API (without authentication), you are limited to 2,000 requests per hour per IP (or up to a total of 48,000 requests a day). ----- class YahooDownloader: Provides methods for retrieving daily stock data from Yahoo Finance API Attributes ---------- start_date : str start date of the data (modified from config.py) end_date : str end date of the data (modified from config.py) ticker_list : list a list of stock tickers (modified from config.py) Methods ------- fetch_data() Fetches data from yahoo API ``` # from config.py start_date is a string config.START_DATE print(config_tickers.DOW_30_TICKER) df = YahooDownloader(start_date = '2009-01-01', end_date = '2021-07-06', ticker_list = config_tickers.DOW_30_TICKER).fetch_data() df.head() df.tail() df.shape df.sort_values(['date','tic']).head() len(df.tic.unique()) df.tic.value_counts() ``` # Part 4: Preprocess Data Data preprocessing is a crucial step for training a high quality machine learning model. We need to check for missing data and do feature engineering in order to convert the data into a model-ready state. * Add technical indicators. In practical trading, various information needs to be taken into account, for example the historical stock prices, current holding shares, technical indicators, etc. In this article, we demonstrate two trend-following technical indicators: MACD and RSI. * Add turbulence index. Risk-aversion reflects whether an investor will choose to preserve the capital. It also influences one's trading strategy when facing different market volatility level. To control the risk in a worst-case scenario, such as financial crisis of 2007–2008, FinRL employs the financial turbulence index that measures extreme asset price fluctuation. ``` tech_indicators = ['macd', 'rsi_30', 'cci_30', 'dx_30'] fe = FeatureEngineer( use_technical_indicator=True, tech_indicator_list = tech_indicators, use_turbulence=True, user_defined_feature = False) processed = fe.preprocess_data(df) processed = processed.copy() processed = processed.fillna(0) processed = processed.replace(np.inf,0) processed.sample(5) ``` <a id='4'></a> # Part 5. Design Environment Considering the stochastic and interactive nature of the automated stock trading tasks, a financial task is modeled as a **Markov Decision Process (MDP)** problem. The training process involves observing stock price change, taking an action and reward's calculation to have the agent adjusting its strategy accordingly. By interacting with the environment, the trading agent will derive a trading strategy with the maximized rewards as time proceeds. Our trading environments, based on OpenAI Gym framework, simulate live stock markets with real market data according to the principle of time-driven simulation. The action space describes the allowed actions that the agent interacts with the environment. Normally, action a includes three actions: {-1, 0, 1}, where -1, 0, 1 represent selling, holding, and buying one share. Also, an action can be carried upon multiple shares. We use an action space {-k,…,-1, 0, 1, …, k}, where k denotes the number of shares to buy and -k denotes the number of shares to sell. For example, "Buy 10 shares of AAPL" or "Sell 10 shares of AAPL" are 10 or -10, respectively. The continuous action space needs to be normalized to [-1, 1], since the policy is defined on a Gaussian distribution, which needs to be normalized and symmetric. ``` stock_dimension = len(processed.tic.unique()) state_space = 1 + 2*stock_dimension + len(tech_indicators)*stock_dimension print(f"Stock Dimension: {stock_dimension}, State Space: {state_space}") env_kwargs = { "hmax": 100, "initial_amount": 1000000, "buy_cost_pct": 0.001, "sell_cost_pct": 0.001, "state_space": state_space, "stock_dim": stock_dimension, "tech_indicator_list": tech_indicators, "action_space": stock_dimension, "reward_scaling": 1e-4, "print_verbosity":5 } ``` <a id='5'></a> # Part 6: Implement DRL Algorithms * The implementation of the DRL algorithms are based on **OpenAI Baselines** and **Stable Baselines**. Stable Baselines is a fork of OpenAI Baselines, with a major structural refactoring, and code cleanups. * FinRL library includes fine-tuned standard DRL algorithms, such as DQN, DDPG, Multi-Agent DDPG, PPO, SAC, A2C and TD3. We also allow users to design their own DRL algorithms by adapting these DRL algorithms. * In this notebook, we are training and validating 3 agents (A2C, PPO, DDPG) using Rolling-window Ensemble Method ([reference code](https://github.com/AI4Finance-LLC/Deep-Reinforcement-Learning-for-Automated-Stock-Trading-Ensemble-Strategy-ICAIF-2020/blob/80415db8fa7b2179df6bd7e81ce4fe8dbf913806/model/models.py#L92)) ``` rebalance_window = 63 # rebalance_window is the number of days to retrain the model validation_window = 63 # validation_window is the number of days to do validation and trading (e.g. if validation_window=63, then both validation and trading period will be 63 days) train_start = '2009-01-01' train_end = '2020-04-01' val_test_start = '2020-04-01' val_test_end = '2021-07-20' ensemble_agent = DRLEnsembleAgent(df=processed, train_period=(train_start,train_end), val_test_period=(val_test_start,val_test_end), rebalance_window=rebalance_window, validation_window=validation_window, **env_kwargs) A2C_model_kwargs = { 'n_steps': 5, 'ent_coef': 0.01, 'learning_rate': 0.0005 } PPO_model_kwargs = { "ent_coef":0.01, "n_steps": 2048, "learning_rate": 0.00025, "batch_size": 64 } DDPG_model_kwargs = { #"action_noise":"ornstein_uhlenbeck", "buffer_size": 100_000, "learning_rate": 0.000005, "batch_size": 64 } timesteps_dict = {'a2c' : 30_000, 'ppo' : 100_000, 'ddpg' : 10_000 } timesteps_dict = {'a2c' : 10_000, 'ppo' : 10_000, 'ddpg' : 10_000 } df_summary = ensemble_agent.run_ensemble_strategy(A2C_model_kwargs, PPO_model_kwargs, DDPG_model_kwargs, timesteps_dict) df_summary ``` <a id='6'></a> # Part 7: Backtest Our Strategy Backtesting plays a key role in evaluating the performance of a trading strategy. Automated backtesting tool is preferred because it reduces the human error. We usually use the Quantopian pyfolio package to backtest our trading strategies. It is easy to use and consists of various individual plots that provide a comprehensive image of the performance of a trading strategy. ``` unique_trade_date = processed[(processed.date > val_test_start)&(processed.date <= val_test_end)].date.unique() df_trade_date = pd.DataFrame({'datadate':unique_trade_date}) df_account_value=pd.DataFrame() for i in range(rebalance_window+validation_window, len(unique_trade_date)+1,rebalance_window): temp = pd.read_csv('results/account_value_trade_{}_{}.csv'.format('ensemble',i)) df_account_value = df_account_value.append(temp,ignore_index=True) sharpe=(252**0.5)*df_account_value.account_value.pct_change(1).mean()/df_account_value.account_value.pct_change(1).std() print('Sharpe Ratio: ',sharpe) df_account_value=df_account_value.join(df_trade_date[validation_window:].reset_index(drop=True)) df_account_value.head() %matplotlib inline df_account_value.account_value.plot() ``` <a id='6.1'></a> ## 7.1 BackTestStats pass in df_account_value, this information is stored in env class ``` print("==============Get Backtest Results===========") now = datetime.datetime.now().strftime('%Y%m%d-%Hh%M') perf_stats_all = backtest_stats(account_value=df_account_value) perf_stats_all = pd.DataFrame(perf_stats_all) #baseline stats print("==============Get Baseline Stats===========") baseline_df = get_baseline( ticker="^DJI", start = df_account_value.loc[0,'date'], end = df_account_value.loc[len(df_account_value)-1,'date']) stats = backtest_stats(baseline_df, value_col_name = 'close') ``` <a id='6.2'></a> ## 7.2 BackTestPlot ``` print("==============Compare to DJIA===========") %matplotlib inline # S&P 500: ^GSPC # Dow Jones Index: ^DJI # NASDAQ 100: ^NDX backtest_plot(df_account_value, baseline_ticker = '^DJI', baseline_start = df_account_value.loc[0,'date'], baseline_end = df_account_value.loc[len(df_account_value)-1,'date']) ```
github_jupyter
# GRU 212 * Operate on 16000 GenCode 34 seqs. * 5-way cross validation. Save best model per CV. * Report mean accuracy from final re-validation with best 5. * Use Adam with a learn rate decay schdule. ``` NC_FILENAME='ncRNA.gc34.processed.fasta' PC_FILENAME='pcRNA.gc34.processed.fasta' DATAPATH="" try: from google.colab import drive IN_COLAB = True PATH='/content/drive/' drive.mount(PATH) DATAPATH=PATH+'My Drive/data/' # must end in "/" NC_FILENAME = DATAPATH+NC_FILENAME PC_FILENAME = DATAPATH+PC_FILENAME except: IN_COLAB = False DATAPATH="" EPOCHS=200 SPLITS=1 K=3 VOCABULARY_SIZE=4**K+1 # e.g. K=3 => 64 DNA K-mers + 'NNN' EMBED_DIMEN=16 FILENAME='GRU212' NEURONS=64 DROP=0.0 ACT="tanh" import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.model_selection import ShuffleSplit from sklearn.model_selection import cross_val_score from sklearn.model_selection import RepeatedKFold from sklearn.model_selection import StratifiedKFold import tensorflow as tf from tensorflow import keras from keras.wrappers.scikit_learn import KerasRegressor from keras.models import Sequential from keras.layers import Bidirectional from keras.layers import GRU from keras.layers import Dense from keras.layers import LayerNormalization import time dt='float32' tf.keras.backend.set_floatx(dt) ``` ## Build model ``` def compile_model(model): adam_default_learn_rate = 0.001 schedule = tf.keras.optimizers.schedules.ExponentialDecay( initial_learning_rate = adam_default_learn_rate*10, #decay_steps=100000, decay_rate=0.96, staircase=True) decay_steps=10000, decay_rate=0.99, staircase=True) # learn rate = initial_learning_rate * decay_rate ^ (step / decay_steps) alrd = tf.keras.optimizers.Adam(learning_rate=schedule) bc=tf.keras.losses.BinaryCrossentropy(from_logits=False) print("COMPILE...") #model.compile(loss=bc, optimizer=alrd, metrics=["accuracy"]) model.compile(loss=bc, optimizer="adam", metrics=["accuracy"]) print("...COMPILED") return model def build_model(): embed_layer = keras.layers.Embedding( #VOCABULARY_SIZE, EMBED_DIMEN, input_length=1000, input_length=1000, mask_zero=True) #input_dim=[None,VOCABULARY_SIZE], output_dim=EMBED_DIMEN, mask_zero=True) input_dim=VOCABULARY_SIZE, output_dim=EMBED_DIMEN, mask_zero=True) #rnn1_layer = keras.layers.Bidirectional( rnn1_layer = keras.layers.GRU(NEURONS, return_sequences=True, input_shape=[1000,EMBED_DIMEN], activation=ACT, dropout=DROP) #)#bi #rnn2_layer = keras.layers.Bidirectional( rnn2_layer = keras.layers.GRU(NEURONS, return_sequences=False, activation=ACT, dropout=DROP) #)#bi dense1_layer = keras.layers.Dense(NEURONS, activation=ACT,dtype=dt) #drop1_layer = keras.layers.Dropout(DROP) dense2_layer = keras.layers.Dense(NEURONS, activation=ACT,dtype=dt) #drop2_layer = keras.layers.Dropout(DROP) output_layer = keras.layers.Dense(1, activation="sigmoid", dtype=dt) mlp = keras.models.Sequential() mlp.add(embed_layer) mlp.add(rnn1_layer) mlp.add(rnn2_layer) mlp.add(dense1_layer) #mlp.add(drop1_layer) mlp.add(dense2_layer) #mlp.add(drop2_layer) mlp.add(output_layer) mlpc = compile_model(mlp) return mlpc ``` ## Load and partition sequences ``` # Assume file was preprocessed to contain one line per seq. # Prefer Pandas dataframe but df does not support append. # For conversion to tensor, must avoid python lists. def load_fasta(filename,label): DEFLINE='>' labels=[] seqs=[] lens=[] nums=[] num=0 with open (filename,'r') as infile: for line in infile: if line[0]!=DEFLINE: seq=line.rstrip() num += 1 # first seqnum is 1 seqlen=len(seq) nums.append(num) labels.append(label) seqs.append(seq) lens.append(seqlen) df1=pd.DataFrame(nums,columns=['seqnum']) df2=pd.DataFrame(labels,columns=['class']) df3=pd.DataFrame(seqs,columns=['sequence']) df4=pd.DataFrame(lens,columns=['seqlen']) df=pd.concat((df1,df2,df3,df4),axis=1) return df def separate_X_and_y(data): y= data[['class']].copy() X= data.drop(columns=['class','seqnum','seqlen']) return (X,y) ``` ## Make K-mers ``` def make_kmer_table(K): npad='N'*K shorter_kmers=[''] for i in range(K): longer_kmers=[] for mer in shorter_kmers: longer_kmers.append(mer+'A') longer_kmers.append(mer+'C') longer_kmers.append(mer+'G') longer_kmers.append(mer+'T') shorter_kmers = longer_kmers all_kmers = shorter_kmers kmer_dict = {} kmer_dict[npad]=0 value=1 for mer in all_kmers: kmer_dict[mer]=value value += 1 return kmer_dict KMER_TABLE=make_kmer_table(K) def strings_to_vectors(data,uniform_len): all_seqs=[] for seq in data['sequence']: i=0 seqlen=len(seq) kmers=[] while i < seqlen-K+1 -1: # stop at minus one for spaced seed #kmer=seq[i:i+2]+seq[i+3:i+5] # SPACED SEED 2/1/2 for K=4 kmer=seq[i:i+K] i += 1 value=KMER_TABLE[kmer] kmers.append(value) pad_val=0 while i < uniform_len: kmers.append(pad_val) i += 1 all_seqs.append(kmers) pd2d=pd.DataFrame(all_seqs) return pd2d # return 2D dataframe, uniform dimensions def make_kmers(MAXLEN,train_set): (X_train_all,y_train_all)=separate_X_and_y(train_set) X_train_kmers=strings_to_vectors(X_train_all,MAXLEN) # From pandas dataframe to numpy to list to numpy num_seqs=len(X_train_kmers) tmp_seqs=[] for i in range(num_seqs): kmer_sequence=X_train_kmers.iloc[i] tmp_seqs.append(kmer_sequence) X_train_kmers=np.array(tmp_seqs) tmp_seqs=None labels=y_train_all.to_numpy() return (X_train_kmers,labels) def make_frequencies(Xin): Xout=[] VOCABULARY_SIZE= 4**K + 1 # plus one for 'NNN' for seq in Xin: freqs =[0] * VOCABULARY_SIZE total = 0 for kmerval in seq: freqs[kmerval] += 1 total += 1 for c in range(VOCABULARY_SIZE): freqs[c] = freqs[c]/total Xout.append(freqs) Xnum = np.asarray(Xout) return (Xnum) def make_slice(data_set,min_len,max_len): slice = data_set.query('seqlen <= '+str(max_len)+' & seqlen>= '+str(min_len)) return slice ``` ## Cross validation ``` def do_cross_validation(X,y,given_model): cv_scores = [] fold=0 splitter = ShuffleSplit(n_splits=SPLITS, test_size=0.1, random_state=37863) for train_index,valid_index in splitter.split(X): fold += 1 X_train=X[train_index] # use iloc[] for dataframe y_train=y[train_index] X_valid=X[valid_index] y_valid=y[valid_index] # Avoid continually improving the same model. model = compile_model(keras.models.clone_model(given_model)) bestname=DATAPATH+FILENAME+".cv."+str(fold)+".best" mycallbacks = [keras.callbacks.ModelCheckpoint( filepath=bestname, save_best_only=True, monitor='val_accuracy', mode='max')] print("FIT") start_time=time.time() history=model.fit(X_train, y_train, # batch_size=10, default=32 works nicely epochs=EPOCHS, verbose=1, # verbose=1 for ascii art, verbose=0 for none callbacks=mycallbacks, validation_data=(X_valid,y_valid) ) end_time=time.time() elapsed_time=(end_time-start_time) print("Fold %d, %d epochs, %d sec"%(fold,EPOCHS,elapsed_time)) pd.DataFrame(history.history).plot(figsize=(8,5)) plt.grid(True) plt.gca().set_ylim(0,1) plt.show() best_model=keras.models.load_model(bestname) scores = best_model.evaluate(X_valid, y_valid, verbose=0) print("%s: %.2f%%" % (best_model.metrics_names[1], scores[1]*100)) cv_scores.append(scores[1] * 100) print() print("%d-way Cross Validation mean %.2f%% (+/- %.2f%%)" % (fold, np.mean(cv_scores), np.std(cv_scores))) ``` ## Train on RNA lengths 200-1Kb ``` MINLEN=200 MAXLEN=1000 print("Load data from files.") nc_seq=load_fasta(NC_FILENAME,0) pc_seq=load_fasta(PC_FILENAME,1) train_set=pd.concat((nc_seq,pc_seq),axis=0) nc_seq=None pc_seq=None print("Ready: train_set") #train_set subset=make_slice(train_set,MINLEN,MAXLEN)# One array to two: X and y print ("Data reshape") (X_train,y_train)=make_kmers(MAXLEN,subset) #print ("Data prep") #X_train=make_frequencies(X_train) print ("Compile the model") model=build_model() print ("Summarize the model") print(model.summary()) # Print this only once model.save(DATAPATH+FILENAME+'.model') print ("Cross valiation") do_cross_validation(X_train,y_train,model) print ("Done") ```
github_jupyter
# Lambda School Data Science Module 141 ## Statistics, Probability, and Inference ## Prepare - examine what's available in SciPy As we delve into statistics, we'll be using more libraries - in particular the [stats package from SciPy](https://docs.scipy.org/doc/scipy/reference/tutorial/stats.html). ``` from scipy import stats dir(stats) # As usual, lots of stuff here! There's our friend, the normal distribution norm = stats.norm() print(norm.mean()) print(norm.std()) print(norm.var()) # And a new friend - t t1 = stats.t(5) # 5 is df "shape" parameter print(t1.mean()) print(t1.std()) print(t1.var()) ``` ![T distribution PDF with different shape parameters](https://upload.wikimedia.org/wikipedia/commons/4/41/Student_t_pdf.svg) *(Picture from [Wikipedia](https://en.wikipedia.org/wiki/Student's_t-distribution#/media/File:Student_t_pdf.svg))* The t-distribution is "normal-ish" - the larger the parameter (which reflects its degrees of freedom - more input data/features will increase it), the closer to true normal. ``` t2 = stats.t(30) # Will be closer to normal print(t2.mean()) print(t2.std()) print(t2.var()) ``` Why is it different from normal? To better reflect the tendencies of small data and situations with unknown population standard deviation. In other words, the normal distribution is still the nice pure ideal in the limit (thanks to the central limit theorem), but the t-distribution is much more useful in many real-world situations. History sidenote - this is "Student": ![William Sealy Gosset](https://upload.wikimedia.org/wikipedia/commons/4/42/William_Sealy_Gosset.jpg) *(Picture from [Wikipedia](https://en.wikipedia.org/wiki/File:William_Sealy_Gosset.jpg))* His real name is William Sealy Gosset, and he published under the pen name "Student" because he was not an academic. He was a brewer, working at Guinness and using trial and error to determine the best ways to yield barley. He's also proof that, even 100 years ago, you don't need official credentials to do real data science! ## Live Lecture - let's perform and interpret a t-test We'll generate our own data, so we can know and alter the "ground truth" that the t-test should find. We will learn about p-values and how to interpret "statistical significance" based on the output of a hypothesis test. We will also dig a bit deeper into how the test statistic is calculated based on the sample error, and visually what it looks like to have 1 or 2 "tailed" t-tests. ``` # Just making som data to play around with lambda_heights = [72,72,77,72,73,67,64,58,63,78] import pandas as pd df = pd.DataFrame({'heights': lambda_heights}) df.head(10) df.heights.mean() # Making random data 0's and 1's import random random.seed(10) population = [] for _ in range(1000): population.append(random.randint(0,1)) print(population) print(len(population)) # Take a sample from the data randomly sample = random.sample(population, 100) print(sample) print(len(sample)) df = pd.DataFrame({'likes_coke': sample}) df.head() df.likes_coke.mean() df.plot.hist() df.likes_coke.describe() import numpy as np def mean(list): average = np.sum(list)/len(list) return average print('Population Mean:', mean(population)) print('Sample Mean:', mean(sample)) def variance(list): n = len(list) return np.sum((list - mean(list))**2)/(n-1) variance(df.likes_coke) def stddev(list): var = variance(list) return var**(1/2) stddev(df.likes_coke) n = len(df.likes_coke) t_stat = (mean(df.likes_coke) - .5)/(stddev(df.likes_coke)/n**(1/2)) print(t_stat) import scipy scipy.stats.ttest_1samp(df['likes_coke'], .5) ``` #P-Value P-value is a threshold that we set for ourselves to denote "statistical significance" Statistical Significance means - the odds of me getting unlucky that I'm willing to deal with. The probability that I would have to see that says that these two differences are not just due to chance. 5% - Will only accept this result as reliable or significant if I calculate that this outcome has a 5% chance or less of happening just due to chance. The probability that the pattern in our data that we're seeing could be produced by random data. ## Assignment - apply the t-test to real data Your assignment is to determine which issues have "statistically significant" differences between political parties in this [1980s congressional voting data](https://archive.ics.uci.edu/ml/datasets/Congressional+Voting+Records). The data consists of 435 instances (one for each congressperson), a class (democrat or republican), and 16 binary attributes (yes or no for voting for or against certain issues). Be aware - there are missing values! Your goals: 1. Load and clean the data (or determine the best method to drop observations when running tests) 2. Using hypothesis testing, find an issue that democrats support more than republicans with p < 0.01 3. Using hypothesis testing, find an issue that republicans support more than democrats with p < 0.01 4. Using hypothesis testing, find an issue where the difference between republicans and democrats has p > 0.1 (i.e. there may not be much of a difference) Note that this data will involve *2 sample* t-tests, because you're comparing averages across two groups (republicans and democrats) rather than a single group against a null hypothesis. Stretch goals: 1. Refactor your code into functions so it's easy to rerun with arbitrary variables 2. Apply hypothesis testing to your personal project data (for the purposes of this notebook you can type a summary of the hypothesis you formed and tested) ``` column_names = ['Class Name', 'handicapped-infants', 'water-project-cost-sharing','adoption-of-the-budget-resolution', 'physician-fee-freeze', 'el-salvador-aid', 'religious-groups-in-schools', 'anti-satellite-test-ban', 'aid-to-nicaraguan-contras', 'mx-missile', 'immigration', 'synfuels-corporation-cutback', 'education-spending', 'superfund-right-to-sue', 'crime', 'duty-free-exports', 'export-administration-act-south-africa'] df = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/voting-records/house-votes-84.data', header=None, names=column_names, na_values='?') df.head() df = df.fillna(-1) for column in df.columns: df[column] = df[column].replace({'n':0, 'y':1}) df.head() rep = df[df['Class Name']=='republican'] dem= df[df['Class Name']=='democrat'] rep.head() dem.head() for column in rep.columns: print(rep[column].value_counts(normalize=True),'\n#####################################################\n') for column in dem.columns: print(dem[column].value_counts(normalize=True),'\n#####################################################\n') print('All Mean:', mean(dem['handicapped-infants'])) print('Sample Mean:', mean(dem['handicapped-infants'])) scipy.stats.ttest_1samp(dem['handicapped-infants'], .5) print('All Mean:', mean(rep['handicapped-infants'])) print('Sample Mean:', mean(rep['handicapped-infants'])) scipy.stats.ttest_1samp(rep['handicapped-infants'], .5) rep_nonan = rep[rep['handicapped-infants']!=-1] dem_nonan = dem[dem['handicapped-infants']!=-1] scipy.stats.ttest_1samp(dem_nonan['handicapped-infants'], .5) scipy.stats.ttest_1samp(rep_nonan['handicapped-infants'], .5) ``` Democrats support Handicapped Infants more than Republicans ``` ``` # Resources - https://homepage.divms.uiowa.edu/~mbognar/applets/t.html - https://rpsychologist.com/d3/tdist/ - https://gallery.shinyapps.io/tdist/ - https://en.wikipedia.org/wiki/Standard_deviation#Sample_standard_deviation_of_metabolic_rate_of_northern_fulmars
github_jupyter
# Chaper 8 - Intrinsic Curiosity Module #### Deep Reinforcement Learning *in Action* ##### Listing 8.1 ``` import gym from nes_py.wrappers import BinarySpaceToDiscreteSpaceEnv #A import gym_super_mario_bros from gym_super_mario_bros.actions import SIMPLE_MOVEMENT, COMPLEX_MOVEMENT #B env = gym_super_mario_bros.make('SuperMarioBros-v0') env = BinarySpaceToDiscreteSpaceEnv(env, COMPLEX_MOVEMENT) #C done = True for step in range(2500): #D if done: state = env.reset() state, reward, done, info = env.step(env.action_space.sample()) env.render() env.close() ``` ##### Listing 8.2 ``` import matplotlib.pyplot as plt from skimage.transform import resize #A import numpy as np def downscale_obs(obs, new_size=(42,42), to_gray=True): if to_gray: return resize(obs, new_size, anti_aliasing=True).max(axis=2) #B else: return resize(obs, new_size, anti_aliasing=True) plt.imshow(env.render("rgb_array")) plt.imshow(downscale_obs(env.render("rgb_array"))) ``` ##### Listing 8.4 ``` import torch from torch import nn from torch import optim import torch.nn.functional as F from collections import deque def prepare_state(state): #A return torch.from_numpy(downscale_obs(state, to_gray=True)).float().unsqueeze(dim=0) def prepare_multi_state(state1, state2): #B state1 = state1.clone() tmp = torch.from_numpy(downscale_obs(state2, to_gray=True)).float() state1[0][0] = state1[0][1] state1[0][1] = state1[0][2] state1[0][2] = tmp return state1 def prepare_initial_state(state,N=3): #C state_ = torch.from_numpy(downscale_obs(state, to_gray=True)).float() tmp = state_.repeat((N,1,1)) return tmp.unsqueeze(dim=0) ``` ##### Listing 8.5 ``` def policy(qvalues, eps=None): #A if eps is not None: if torch.rand(1) < eps: return torch.randint(low=0,high=7,size=(1,)) else: return torch.argmax(qvalues) else: return torch.multinomial(F.softmax(F.normalize(qvalues)), num_samples=1) #B ``` ##### Listing 8.6 ``` from random import shuffle import torch from torch import nn from torch import optim import torch.nn.functional as F class ExperienceReplay: def __init__(self, N=500, batch_size=100): self.N = N #A self.batch_size = batch_size #B self.memory = [] self.counter = 0 def add_memory(self, state1, action, reward, state2): self.counter +=1 if self.counter % 500 == 0: #C self.shuffle_memory() if len(self.memory) < self.N: #D self.memory.append( (state1, action, reward, state2) ) else: rand_index = np.random.randint(0,self.N-1) self.memory[rand_index] = (state1, action, reward, state2) def shuffle_memory(self): #E shuffle(self.memory) def get_batch(self): #F if len(self.memory) < self.batch_size: batch_size = len(self.memory) else: batch_size = self.batch_size if len(self.memory) < 1: print("Error: No data in memory.") return None #G ind = np.random.choice(np.arange(len(self.memory)),batch_size,replace=False) batch = [self.memory[i] for i in ind] #batch is a list of tuples state1_batch = torch.stack([x[0].squeeze(dim=0) for x in batch],dim=0) action_batch = torch.Tensor([x[1] for x in batch]).long() reward_batch = torch.Tensor([x[2] for x in batch]) state2_batch = torch.stack([x[3].squeeze(dim=0) for x in batch],dim=0) return state1_batch, action_batch, reward_batch, state2_batch ``` ##### Listing 8.7 ``` class Phi(nn.Module): #A def __init__(self): super(Phi, self).__init__() self.conv1 = nn.Conv2d(3, 32, kernel_size=(3,3), stride=2, padding=1) self.conv2 = nn.Conv2d(32, 32, kernel_size=(3,3), stride=2, padding=1) self.conv3 = nn.Conv2d(32, 32, kernel_size=(3,3), stride=2, padding=1) self.conv4 = nn.Conv2d(32, 32, kernel_size=(3,3), stride=2, padding=1) def forward(self,x): x = F.normalize(x) y = F.elu(self.conv1(x)) y = F.elu(self.conv2(y)) y = F.elu(self.conv3(y)) y = F.elu(self.conv4(y)) #size [1, 32, 3, 3] batch, channels, 3 x 3 y = y.flatten(start_dim=1) #size N, 288 return y class Gnet(nn.Module): #B def __init__(self): super(Gnet, self).__init__() self.linear1 = nn.Linear(576,256) self.linear2 = nn.Linear(256,12) def forward(self, state1,state2): x = torch.cat( (state1, state2) ,dim=1) y = F.relu(self.linear1(x)) y = self.linear2(y) y = F.softmax(y,dim=1) return y class Fnet(nn.Module): #C def __init__(self): super(Fnet, self).__init__() self.linear1 = nn.Linear(300,256) self.linear2 = nn.Linear(256,288) def forward(self,state,action): action_ = torch.zeros(action.shape[0],12) #D indices = torch.stack( (torch.arange(action.shape[0]), action.squeeze()), dim=0) indices = indices.tolist() action_[indices] = 1. x = torch.cat( (state,action_) ,dim=1) y = F.relu(self.linear1(x)) y = self.linear2(y) return y ``` ##### Listing 8.8 ``` class Qnetwork(nn.Module): def __init__(self): super(Qnetwork, self).__init__() #in_channels, out_channels, kernel_size, stride=1, padding=0 self.conv1 = nn.Conv2d(in_channels=3, out_channels=32, kernel_size=(3,3), stride=2, padding=1) self.conv2 = nn.Conv2d(32, 32, kernel_size=(3,3), stride=2, padding=1) self.conv3 = nn.Conv2d(32, 32, kernel_size=(3,3), stride=2, padding=1) self.conv4 = nn.Conv2d(32, 32, kernel_size=(3,3), stride=2, padding=1) self.linear1 = nn.Linear(288,100) self.linear2 = nn.Linear(100,12) def forward(self,x): x = F.normalize(x) y = F.elu(self.conv1(x)) y = F.elu(self.conv2(y)) y = F.elu(self.conv3(y)) y = F.elu(self.conv4(y)) y = y.flatten(start_dim=2) y = y.view(y.shape[0], -1, 32) y = y.flatten(start_dim=1) y = F.elu(self.linear1(y)) y = self.linear2(y) #size N, 12 return y ``` ##### Listing 8.9 ``` params = { 'batch_size':150, 'beta':0.2, 'lambda':0.1, 'eta': 1.0, 'gamma':0.2, 'max_episode_len':100, 'min_progress':15, 'action_repeats':6, 'frames_per_state':3 } replay = ExperienceReplay(N=1000, batch_size=params['batch_size']) Qmodel = Qnetwork() encoder = Phi() forward_model = Fnet() inverse_model = Gnet() forward_loss = nn.MSELoss(reduction='none') inverse_loss = nn.CrossEntropyLoss(reduction='none') qloss = nn.MSELoss() all_model_params = list(Qmodel.parameters()) + list(encoder.parameters()) #A all_model_params += list(forward_model.parameters()) + list(inverse_model.parameters()) opt = optim.Adam(lr=0.001, params=all_model_params) ``` ##### Listing 8.10 ``` def loss_fn(q_loss, inverse_loss, forward_loss): loss_ = (1 - params['beta']) * inverse_loss loss_ += params['beta'] * forward_loss loss_ = loss_.sum() / loss_.flatten().shape[0] loss = loss_ + params['lambda'] * q_loss return loss def reset_env(): """ Reset the environment and return a new initial state """ env.reset() state1 = prepare_initial_state(env.render('rgb_array')) return state1 ``` ##### Listing 8.11 ``` def ICM(state1, action, state2, forward_scale=1., inverse_scale=1e4): state1_hat = encoder(state1) #A state2_hat = encoder(state2) state2_hat_pred = forward_model(state1_hat.detach(), action.detach()) #B forward_pred_err = forward_scale * forward_loss(state2_hat_pred, \ state2_hat.detach()).sum(dim=1).unsqueeze(dim=1) pred_action = inverse_model(state1_hat, state2_hat) #C inverse_pred_err = inverse_scale * inverse_loss(pred_action, \ action.detach().flatten()).unsqueeze(dim=1) return forward_pred_err, inverse_pred_err ``` ##### Listing 8.12 ``` def minibatch_train(use_extrinsic=True): state1_batch, action_batch, reward_batch, state2_batch = replay.get_batch() action_batch = action_batch.view(action_batch.shape[0],1) #A reward_batch = reward_batch.view(reward_batch.shape[0],1) forward_pred_err, inverse_pred_err = ICM(state1_batch, action_batch, state2_batch) #B i_reward = (1. / params['eta']) * forward_pred_err #C reward = i_reward.detach() #D if use_explicit: #E reward += reward_batch qvals = Qmodel(state2_batch) #F reward += params['gamma'] * torch.max(qvals) reward_pred = Qmodel(state1_batch) reward_target = reward_pred.clone() indices = torch.stack( (torch.arange(action_batch.shape[0]), \ action_batch.squeeze()), dim=0) indices = indices.tolist() reward_target[indices] = reward.squeeze() q_loss = 1e5 * qloss(F.normalize(reward_pred), F.normalize(reward_target.detach())) return forward_pred_err, inverse_pred_err, q_loss ``` ##### Listing 8.13 ``` epochs = 5000 env.reset() state1 = prepare_initial_state(env.render('rgb_array')) eps=0.15 losses = [] episode_length = 0 switch_to_eps_greedy = 1000 state_deque = deque(maxlen=params['frames_per_state']) e_reward = 0. last_x_pos = env.env.env._x_position #A ep_lengths = [] use_explicit = False for i in range(epochs): opt.zero_grad() episode_length += 1 q_val_pred = Qmodel(state1) #B if i > switch_to_eps_greedy: #C action = int(policy(q_val_pred,eps)) else: action = int(policy(q_val_pred)) for j in range(params['action_repeats']): #D state2, e_reward_, done, info = env.step(action) last_x_pos = info['x_pos'] if done: state1 = reset_env() break e_reward += e_reward_ state_deque.append(prepare_state(state2)) state2 = torch.stack(list(state_deque),dim=1) #E replay.add_memory(state1, action, e_reward, state2) #F e_reward = 0 if episode_length > params['max_episode_len']: #G if (info['x_pos'] - last_x_pos) < params['min_progress']: done = True else: last_x_pos = info['x_pos'] if done: ep_lengths.append(info['x_pos']) state1 = reset_env() last_x_pos = env.env.env._x_position episode_length = 0 else: state1 = state2 if len(replay.memory) < params['batch_size']: continue forward_pred_err, inverse_pred_err, q_loss = minibatch_train(use_extrinsic=False) #H loss = loss_fn(q_loss, forward_pred_err, inverse_pred_err) #I loss_list = (q_loss.mean(), forward_pred_err.flatten().mean(),\ inverse_pred_err.flatten().mean()) losses.append(loss_list) loss.backward() opt.step() ``` ##### Test Trained Agent ``` done = True state_deque = deque(maxlen=params['frames_per_state']) for step in range(5000): if done: env.reset() state1 = prepare_initial_state(env.render('rgb_array')) q_val_pred = Qmodel(state1) action = int(policy(q_val_pred,eps)) state2, reward, done, info = env.step(action) state2 = prepare_multi_state(state1,state2) state1=state2 env.render() ```
github_jupyter
``` import pandas as pd import numpy as np import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Conv2D, MaxPool2D, Dense, Flatten, Dropout from tensorflow.keras.utils import to_categorical import os import datetime %load_ext tensorboard import matplotlib.pyplot as plt from skimage import color, exposure from sklearn.metrics import accuracy_score cd '/content/drive/My Drive/Colab Notebooks/Matrix/dw_matrix-/matrix_tree' train = pd.read_pickle('data/train.p') test = pd.read_pickle('data/test.p') X_train, y_train = train['features'], train['labels'] X_test, y_test = test['features'], test['labels'] y_train len(np.unique(y_train)) to_categorical(y_train)[0] np.unique(y_train) if y_train.ndim == 1: y_train = to_categorical(y_train) if y_test.ndim == 1: y_test = to_categorical(y_test) input_shape = X_train.shape[1:] num_classes = y_train.shape[1] def get_cnn_v1(input_shape, num_classes): return Sequential([ Conv2D(filters=64, kernel_size=(3,3), activation='relu', input_shape=input_shape), Flatten(), Dense(num_classes, activation='softmax') ]) def train_model(model, X_train, y_train, params_fit={}): model.compile(loss='categorical_crossentropy', optimizer='Adam', metrics=['accuracy']) logdir = os.path.join('logs', datetime.datetime.now().strftime("%Y%m%d-%H%M%S")) tensorboard_callback = tf.keras.callbacks.TensorBoard(logdir, histogram_freq=1) model.fit(X_train, y_train, batch_size=params_fit.get('batch_size', 128), epochs=params_fit.get('epochs', 5), verbose=params_fit.get('verbose', 1), validation_data=params_fit.get('validation_data', (X_train, y_train)), callbacks=[tensorboard_callback] ) return model model = get_cnn_v1(input_shape, num_classes) model_trained = train_model(model, X_train, y_train) y_pred_prob = model_trained.predict(X_test) y_pred_prob y_pred_prob[400] np.sum([1.8309039e-12, 8.3091247e-01, 3.9765782e-12, 1.9530295e-18, 1.6908756e-01, 1.4008565e-10, 8.5738119e-21, 2.2408531e-24, 5.4893188e-22, 1.8297317e-11, 8.1105787e-23, 6.6644010e-25, 3.4779175e-28, 1.8838944e-17, 2.9940773e-32, 3.4073123e-32, 3.2674885e-20, 1.8934992e-31, 2.8295588e-18, 3.7037542e-33, 1.0314749e-23, 8.9143100e-26, 1.9489775e-29, 6.2612767e-23, 4.4554421e-27, 3.4258839e-25, 3.1946413e-24, 5.3853781e-32, 5.1257782e-19, 1.5215109e-30, 9.1346340e-31, 2.7345416e-26, 7.5727543e-33, 8.0035479e-26, 0.0000000e+00, 1.3156333e-30, 0.0000000e+00, 6.8313645e-28, 3.5761218e-32, 1.6024535e-34, 1.2879560e-27, 2.0423062e-31, 0.0000000e+00]) df = pd.read_csv('data/signnames.csv') labels_dict = df.to_dict()['b'] def predict(model_trained, X_test, y_test, scoring=accuracy_score): y_test_norm = np.argmax(y_test, axis=1) y_pred_prob = model_trained.predict(X_test) y_pred = np.argmax(y_pred_prob, axis=1) return scoring(y_test_norm, y_pred) predict(model_trained, X_test, y_test) def train_and_predict(model): model_trained = train_model(model, X_train, y_train) return predict(model_trained, X_test, y_test) def get_cnn_v2(input_shape, num_classes): return Sequential([ Conv2D(filters=32, kernel_size=(3,3), activation='relu', input_shape=input_shape), MaxPool2D(), Dropout(0.3), Conv2D(filters=64, kernel_size=(3,3), activation='relu'), MaxPool2D(), Flatten(), Dense(1024, activation='relu'), Dropout(0.3), Dense(num_classes, activation='softmax') ]) train_and_predict(get_cnn_v2(input_shape, num_classes)) def get_cnn_v3(input_shape, num_classes): return Sequential([ Conv2D(filters=32, kernel_size=(3,3), activation='relu', input_shape=input_shape), Conv2D(filters=32, kernel_size=(3,3), activation='relu', input_shape=input_shape), MaxPool2D(), Dropout(0.3), Conv2D(filters=64, kernel_size=(3,3), activation='relu'), Conv2D(filters=64, kernel_size=(3,3), activation='relu'), MaxPool2D(), Dropout(0.3), Flatten(), Dense(1024, activation='relu'), Dropout(0.3), Dense(num_classes, activation='softmax') ]) train_and_predict(get_cnn_v3(input_shape, num_classes)) def get_cnn_v4(input_shape, num_classes): return Sequential([ Conv2D(filters=32, kernel_size=(3,3), activation='relu', input_shape=input_shape), Conv2D(filters=32, kernel_size=(3,3), activation='relu', padding='same'), MaxPool2D(), Dropout(0.3), Conv2D(filters=64, kernel_size=(3,3), activation='relu', padding='same'), Conv2D(filters=64, kernel_size=(3,3), activation='relu'), MaxPool2D(), Dropout(0.3), Conv2D(filters=64, kernel_size=(3,3), activation='relu', padding='same'), Conv2D(filters=64, kernel_size=(3,3), activation='relu'), MaxPool2D(), Dropout(0.3), Flatten(), Dense(1024, activation='relu'), Dropout(0.3), Dense(num_classes, activation='softmax') ]) # get_cnn_v4(input_shape, num_classes).summary() train_and_predict(get_cnn_v4(input_shape, num_classes)) def get_cnn_v5(input_shape, num_classes): return Sequential([ Conv2D(filters=32, kernel_size=(3,3), activation='relu', input_shape=input_shape), Conv2D(filters=32, kernel_size=(3,3), activation='relu', padding='same'), MaxPool2D(), Dropout(0.3), Conv2D(filters=64, kernel_size=(3,3), activation='relu', padding='same'), Conv2D(filters=64, kernel_size=(3,3), activation='relu'), MaxPool2D(), Dropout(0.3), Conv2D(filters=64, kernel_size=(3,3), activation='relu', padding='same'), Conv2D(filters=64, kernel_size=(3,3), activation='relu'), MaxPool2D(), Dropout(0.3), Flatten(), Dense(1024, activation='relu'), Dropout(0.3), Dense(1024, activation='relu'), Dropout(0.3), Dense(num_classes, activation='softmax') ]) # get_cnn_v4(input_shape, num_classes).summary() train_and_predict(get_cnn_v5(input_shape, num_classes)) X_train_gray = color.rgb2gray(X_train).reshape(-1, 32, 32, 1) X_test_gray = color.rgb2gray(X_test).reshape(-1, 32, 32, 1) model = get_cnn_v5((32,32,1), num_classes) model_trained = train_model(model, X_train_gray, y_train, params_fit={}) predict(model_trained, X_test_gray, y_test, scoring=accuracy_score) # model.compile(loss='category_crosse') plt.imshow(color.rgb2gray(X_train[0]), cmap=plt.get_cmap('gray')) X_train[0].shape color.rgb2gray(X_train[0]).shape def preproc_img(img): hsv = color.rgb2hsv(img) hsv[:, :, 2] = exposure.equalize_adapthist(hsv[:, :, 2]) img = color.hsv2rgb(hsv) return img plt.imshow(preproc_img(X_train[400])) plt.imshow(X_train[400]) labels_dict[ np.argmax(y_pred_prob[400]) ] plt.imshow(X_test[400]) ```
github_jupyter
# Fuzzing with Grammars In the chapter on ["Mutation-Based Fuzzing"](MutationFuzzer.ipynb), we have seen how to use extra hints – such as sample input files – to speed up test generation. In this chapter, we take this idea one step further, by providing a _specification_ of the legal inputs to a program. Specifying inputs via a _grammar_ allows for very systematic and efficient test generation, in particular for complex input formats. Grammars also serve as the base for configuration fuzzing, API fuzzing, GUI fuzzing, and many more. ``` from bookutils import YouTubeVideo YouTubeVideo('mswyS3Wok1c') ``` **Prerequisites** * You should know how basic fuzzing works, e.g. from the [Chapter introducing fuzzing](Fuzzer.ipynb). * Knowledge on [mutation-based fuzzing](MutationFuzzer.ipynb) and [coverage](Coverage.ipynb) is _not_ required yet, but still recommended. ``` import bookutils from typing import List, Dict, Union, Any, Tuple, Optional import Fuzzer ``` ## Synopsis <!-- Automatically generated. Do not edit. --> To [use the code provided in this chapter](Importing.ipynb), write ```python >>> from fuzzingbook.Grammars import <identifier> ``` and then make use of the following features. This chapter introduces _grammars_ as a simple means to specify input languages, and to use them for testing programs with syntactically valid inputs. A grammar is defined as a mapping of nonterminal symbols to lists of alternative expansions, as in the following example: ```python >>> US_PHONE_GRAMMAR: Grammar = { >>> "<start>": ["<phone-number>"], >>> "<phone-number>": ["(<area>)<exchange>-<line>"], >>> "<area>": ["<lead-digit><digit><digit>"], >>> "<exchange>": ["<lead-digit><digit><digit>"], >>> "<line>": ["<digit><digit><digit><digit>"], >>> "<lead-digit>": ["2", "3", "4", "5", "6", "7", "8", "9"], >>> "<digit>": ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] >>> } >>> >>> assert is_valid_grammar(US_PHONE_GRAMMAR) ``` Nonterminal symbols are enclosed in angle brackets (say, `<digit>`). To generate an input string from a grammar, a _producer_ starts with the start symbol (`<start>`) and randomly chooses a random expansion for this symbol. It continues the process until all nonterminal symbols are expanded. The function `simple_grammar_fuzzer()` does just that: ```python >>> [simple_grammar_fuzzer(US_PHONE_GRAMMAR) for i in range(5)] ['(692)449-5179', '(519)230-7422', '(613)761-0853', '(979)881-3858', '(810)914-5475'] ``` In practice, though, instead of `simple_grammar_fuzzer()`, you should use [the `GrammarFuzzer` class](GrammarFuzzer.ipynb) or one of its [coverage-based](GrammarCoverageFuzzer.ipynb), [probabilistic-based](ProbabilisticGrammarFuzzer.ipynb), or [generator-based](GeneratorGrammarFuzzer.ipynb) derivatives; these are more efficient, protect against infinite growth, and provide several additional features. This chapter also introduces a [grammar toolbox](#A-Grammar-Toolbox) with several helper functions that ease the writing of grammars, such as using shortcut notations for character classes and repetitions, or extending grammars ## Input Languages All possible behaviors of a program can be triggered by its input. "Input" here can be a wide range of possible sources: We are talking about data that is read from files, from the environment, or over the network, data input by the user, or data acquired from interaction with other resources. The set of all these inputs determines how the program will behave – including its failures. When testing, it is thus very helpful to think about possible input sources, how to get them under control, and _how to systematically test them_. For the sake of simplicity, we will assume for now that the program has only one source of inputs; this is the same assumption we have been using in the previous chapters, too. The set of valid inputs to a program is called a _language_. Languages range from the simple to the complex: the CSV language denotes the set of valid comma-separated inputs, whereas the Python language denotes the set of valid Python programs. We commonly separate data languages and programming languages, although any program can also be treated as input data (say, to a compiler). The [Wikipedia page on file formats](https://en.wikipedia.org/wiki/List_of_file_formats) lists more than 1,000 different file formats, each of which is its own language. To formally describe languages, the field of *formal languages* has devised a number of *language specifications* that describe a language. *Regular expressions* represent the simplest class of these languages to denote sets of strings: The regular expression `[a-z]*`, for instance, denotes a (possibly empty) sequence of lowercase letters. *Automata theory* connects these languages to automata that accept these inputs; *finite state machines*, for instance, can be used to specify the language of regular expressions. Regular expressions are great for not-too-complex input formats, and the associated finite state machines have many properties that make them great for reasoning. To specify more complex inputs, though, they quickly encounter limitations. At the other end of the language spectrum, we have *universal grammars* that denote the language accepted by *Turing machines*. A Turing machine can compute anything that can be computed; and with Python being Turing-complete, this means that we can also use a Python program $p$ to specify or even enumerate legal inputs. But then, computer science theory also tells us that each such testing program has to be written specifically for the program to be tested, which is not the level of automation we want. ## Grammars The middle ground between regular expressions and Turing machines is covered by *grammars*. Grammars are among the most popular (and best understood) formalisms to formally specify input languages. Using a grammar, one can express a wide range of the properties of an input language. Grammars are particularly great for expressing the *syntactical structure* of an input, and are the formalism of choice to express nested or recursive inputs. The grammars we use are so-called *context-free grammars*, one of the easiest and most popular grammar formalisms. ### Rules and Expansions A grammar consists of a *start symbol* and a set of *expansion rules* (or simply *rules*) which indicate how the start symbol (and other symbols) can be expanded. As an example, consider the following grammar, denoting a sequence of two digits: ``` <start> ::= <digit><digit> <digit> ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 ``` To read such a grammar, start with the start symbol (`<start>`). An expansion rule `<A> ::= <B>` means that the symbol on the left side (`<A>`) can be replaced by the string on the right side (`<B>`). In the above grammar, `<start>` would be replaced by `<digit><digit>`. In this string again, `<digit>` would be replaced by the string on the right side of the `<digit>` rule. The special operator `|` denotes *expansion alternatives* (or simply *alternatives*), meaning that any of the digits can be chosen for an expansion. Each `<digit>` thus would be expanded into one of the given digits, eventually yielding a string between `00` and `99`. There are no further expansions for `0` to `9`, so we are all set. The interesting thing about grammars is that they can be *recursive*. That is, expansions can make use of symbols expanded earlier – which would then be expanded again. As an example, consider a grammar that describes integers: ``` <start> ::= <integer> <integer> ::= <digit> | <digit><integer> <digit> ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 ``` Here, a `<integer>` is either a single digit, or a digit followed by another integer. The number `1234` thus would be represented as a single digit `1`, followed by the integer `234`, which in turn is a digit `2`, followed by the integer `34`. If we wanted to express that an integer can be preceded by a sign (`+` or `-`), we would write the grammar as ``` <start> ::= <number> <number> ::= <integer> | +<integer> | -<integer> <integer> ::= <digit> | <digit><integer> <digit> ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 ``` These rules formally define the language: Anything that can be derived from the start symbol is part of the language; anything that cannot is not. ``` from bookutils import quiz quiz("Which of these strings cannot be produced " "from the above `<start>` symbol?", [ "`007`", "`-42`", "`++1`", "`3.14`" ], "[27 ** (1/3), 256 ** (1/4)]") ``` ### Arithmetic Expressions Let us expand our grammar to cover full *arithmetic expressions* – a poster child example for a grammar. We see that an expression (`<expr>`) is either a sum, or a difference, or a term; a term is either a product or a division, or a factor; and a factor is either a number or a parenthesized expression. Almost all rules can have recursion, and thus allow arbitrary complex expressions such as `(1 + 2) * (3.4 / 5.6 - 789)`. ``` <start> ::= <expr> <expr> ::= <term> + <expr> | <term> - <expr> | <term> <term> ::= <term> * <factor> | <term> / <factor> | <factor> <factor> ::= +<factor> | -<factor> | (<expr>) | <integer> | <integer>.<integer> <integer> ::= <digit><integer> | <digit> <digit> ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 ``` In such a grammar, if we start with `<start>` and then expand one symbol after another, randomly choosing alternatives, we can quickly produce one valid arithmetic expression after another. Such *grammar fuzzing* is highly effective as it comes to produce complex inputs, and this is what we will implement in this chapter. ``` quiz("Which of these strings cannot be produced " "from the above `<start>` symbol?", [ "`1 + 1`", "`1+1`", "`+1`", "`+(1)`", ], "4 ** 0.5") ``` ## Representing Grammars in Python Our first step in building a grammar fuzzer is to find an appropriate format for grammars. To make the writing of grammars as simple as possible, we use a format that is based on strings and lists. Our grammars in Python take the format of a _mapping_ between symbol names and expansions, where expansions are _lists_ of alternatives. A one-rule grammar for digits thus takes the form ``` DIGIT_GRAMMAR = { "<start>": ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] } ``` ### Excursion: A `Grammar` Type Let us define a type for grammars, such that we can check grammar types statically. A first attempt at a grammar type would be that each symbol (a string) is mapped to a list of expansions (strings): ``` SimpleGrammar = Dict[str, List[str]] ``` However, our `opts()` feature for adding optional attributes, which we will introduce later in this chapter, also allows expansions to be _pairs_ that consist of strings and options, where options are mappings of strings to values: ``` Option = Dict[str, Any] ``` Hence, an expansion is either a string – or a pair of a string and an option. ``` Expansion = Union[str, Tuple[str, Option]] ``` With this, we can now define a `Grammar` as a mapping of strings to `Expansion` lists. ### End of Excursion We can capture the grammar structure in a _`Grammar`_ type, in which each symbol (a string) is mapped to a list of expansions (strings): ``` Grammar = Dict[str, List[Expansion]] ``` With this `Grammar` type, the full grammar for arithmetic expressions looks like this: ``` EXPR_GRAMMAR: Grammar = { "<start>": ["<expr>"], "<expr>": ["<term> + <expr>", "<term> - <expr>", "<term>"], "<term>": ["<factor> * <term>", "<factor> / <term>", "<factor>"], "<factor>": ["+<factor>", "-<factor>", "(<expr>)", "<integer>.<integer>", "<integer>"], "<integer>": ["<digit><integer>", "<digit>"], "<digit>": ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] } ``` In the grammar, every symbol can be defined exactly once. We can access any rule by its symbol... ``` EXPR_GRAMMAR["<digit>"] ``` ....and we can check whether a symbol is in the grammar: ``` "<identifier>" in EXPR_GRAMMAR ``` Note that we assume that on the left hand side of a rule (i.e., the key in the mapping) is always a single symbol. This is the property that gives our grammars the characterization of _context-free_. ## Some Definitions We assume that the canonical start symbol is `<start>`: ``` START_SYMBOL = "<start>" ``` The handy `nonterminals()` function extracts the list of nonterminal symbols (i.e., anything between `<` and `>`, except spaces) from an expansion. ``` import re RE_NONTERMINAL = re.compile(r'(<[^<> ]*>)') def nonterminals(expansion): # In later chapters, we allow expansions to be tuples, # with the expansion being the first element if isinstance(expansion, tuple): expansion = expansion[0] return RE_NONTERMINAL.findall(expansion) assert nonterminals("<term> * <factor>") == ["<term>", "<factor>"] assert nonterminals("<digit><integer>") == ["<digit>", "<integer>"] assert nonterminals("1 < 3 > 2") == [] assert nonterminals("1 <3> 2") == ["<3>"] assert nonterminals("1 + 2") == [] assert nonterminals(("<1>", {'option': 'value'})) == ["<1>"] ``` Likewise, `is_nonterminal()` checks whether some symbol is a nonterminal: ``` def is_nonterminal(s): return RE_NONTERMINAL.match(s) assert is_nonterminal("<abc>") assert is_nonterminal("<symbol-1>") assert not is_nonterminal("+") ``` ## A Simple Grammar Fuzzer Let us now put the above grammars to use. We will build a very simple grammar fuzzer that starts with a start symbol (`<start>`) and then keeps on expanding it. To avoid expansion to infinite inputs, we place a limit (`max_nonterminals`) on the number of nonterminals. Furthermore, to avoid being stuck in a situation where we cannot reduce the number of symbols any further, we also limit the total number of expansion steps. ``` import random class ExpansionError(Exception): pass def simple_grammar_fuzzer(grammar: Grammar, start_symbol: str = START_SYMBOL, max_nonterminals: int = 10, max_expansion_trials: int = 100, log: bool = False) -> str: """Produce a string from `grammar`. `start_symbol`: use a start symbol other than `<start>` (default). `max_nonterminals`: the maximum number of nonterminals still left for expansion `max_expansion_trials`: maximum # of attempts to produce a string `log`: print expansion progress if True""" term = start_symbol expansion_trials = 0 while len(nonterminals(term)) > 0: symbol_to_expand = random.choice(nonterminals(term)) expansions = grammar[symbol_to_expand] expansion = random.choice(expansions) # In later chapters, we allow expansions to be tuples, # with the expansion being the first element if isinstance(expansion, tuple): expansion = expansion[0] new_term = term.replace(symbol_to_expand, expansion, 1) if len(nonterminals(new_term)) < max_nonterminals: term = new_term if log: print("%-40s" % (symbol_to_expand + " -> " + expansion), term) expansion_trials = 0 else: expansion_trials += 1 if expansion_trials >= max_expansion_trials: raise ExpansionError("Cannot expand " + repr(term)) return term ``` Let us see how this simple grammar fuzzer obtains an arithmetic expression from the start symbol: ``` simple_grammar_fuzzer(grammar=EXPR_GRAMMAR, max_nonterminals=3, log=True) ``` By increasing the limit of nonterminals, we can quickly get much longer productions: ``` for i in range(10): print(simple_grammar_fuzzer(grammar=EXPR_GRAMMAR, max_nonterminals=5)) ``` Note that while fuzzer does the job in most cases, it has a number of drawbacks. ``` quiz("What drawbacks does `simple_grammar_fuzzer()` have?", [ "It has a large number of string search and replace operations", "It may fail to produce a string (`ExpansionError`)", "It often picks some symbol to expand " "that does not even occur in the string", "All of the above" ], "1 << 2") ``` Indeed, `simple_grammar_fuzzer()` is rather inefficient due to the large number of search and replace operations, and it may even fail to produce a string. On the other hand, the implementation is straightforward and does the job in most cases. For this chapter, we'll stick to it; in the [next chapter](GrammarFuzzer.ipynb), we'll show how to build a more efficient one. ## Visualizing Grammars as Railroad Diagrams With grammars, we can easily specify the format for several of the examples we discussed earlier. The above arithmetic expressions, for instance, can be directly sent into `bc` (or any other program that takes arithmetic expressions). Before we introduce a few additional grammars, let us give a means to _visualize_ them, giving an alternate view to aid their understanding. _Railroad diagrams_, also called _syntax diagrams_, are a graphical representation of context-free grammars. They are read left to right, following possible "rail" tracks; the sequence of symbols encountered on the track defines the language. To produce railroad diagrams, we implement a function `syntax_diagram()`. ### Excursion: Implementing `syntax_diagram()` We use [RailroadDiagrams](RailroadDiagrams.ipynb), an external library for visualization. ``` from RailroadDiagrams import NonTerminal, Terminal, Choice, HorizontalChoice, Sequence from RailroadDiagrams import show_diagram from IPython.display import SVG ``` We first define the method `syntax_diagram_symbol()` to visualize a given symbol. Terminal symbols are denoted as ovals, whereas nonterminal symbols (such as `<term>`) are denoted as rectangles. ``` def syntax_diagram_symbol(symbol: str) -> Any: if is_nonterminal(symbol): return NonTerminal(symbol[1:-1]) else: return Terminal(symbol) SVG(show_diagram(syntax_diagram_symbol('<term>'))) ``` We define `syntax_diagram_expr()` to visualize expansion alternatives. ``` def syntax_diagram_expr(expansion: Expansion) -> Any: # In later chapters, we allow expansions to be tuples, # with the expansion being the first element if isinstance(expansion, tuple): expansion = expansion[0] symbols = [sym for sym in re.split(RE_NONTERMINAL, expansion) if sym != ""] if len(symbols) == 0: symbols = [""] # special case: empty expansion return Sequence(*[syntax_diagram_symbol(sym) for sym in symbols]) SVG(show_diagram(syntax_diagram_expr(EXPR_GRAMMAR['<term>'][0]))) ``` This is the first alternative of `<term>` – a `<factor>` followed by `*` and a `<term>`. Next, we define `syntax_diagram_alt()` for displaying alternate expressions. ``` from itertools import zip_longest def syntax_diagram_alt(alt: List[Expansion]) -> Any: max_len = 5 alt_len = len(alt) if alt_len > max_len: iter_len = alt_len // max_len alts = list(zip_longest(*[alt[i::iter_len] for i in range(iter_len)])) exprs = [[syntax_diagram_expr(expr) for expr in alt if expr is not None] for alt in alts] choices = [Choice(len(expr) // 2, *expr) for expr in exprs] return HorizontalChoice(*choices) else: return Choice(alt_len // 2, *[syntax_diagram_expr(expr) for expr in alt]) SVG(show_diagram(syntax_diagram_alt(EXPR_GRAMMAR['<digit>']))) ``` We see that a `<digit>` can be any single digit from `0` to `9`. Finally, we define `syntax_diagram()` which given a grammar, displays the syntax diagram of its rules. ``` def syntax_diagram(grammar: Grammar) -> None: from IPython.display import SVG, display for key in grammar: print("%s" % key[1:-1]) display(SVG(show_diagram(syntax_diagram_alt(grammar[key])))) ``` ### End of Excursion Let us use `syntax_diagram()` to produce a railroad diagram of our expression grammar: ``` syntax_diagram(EXPR_GRAMMAR) ``` This railroad representation will come in handy as it comes to visualizing the structure of grammars – especially for more complex grammars. ## Some Grammars Let us create (and visualize) some more grammars and use them for fuzzing. ### A CGI Grammar Here's a grammar for `cgi_decode()` introduced in the [chapter on coverage](Coverage.ipynb). ``` CGI_GRAMMAR: Grammar = { "<start>": ["<string>"], "<string>": ["<letter>", "<letter><string>"], "<letter>": ["<plus>", "<percent>", "<other>"], "<plus>": ["+"], "<percent>": ["%<hexdigit><hexdigit>"], "<hexdigit>": ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"], "<other>": # Actually, could be _all_ letters ["0", "1", "2", "3", "4", "5", "a", "b", "c", "d", "e", "-", "_"], } syntax_diagram(CGI_GRAMMAR) ``` In contrast to [basic fuzzing](Fuzzer.ipynb) or [mutation-based fuzzing](MutationFuzzer.ipynb), the grammar quickly produces all sorts of combinations: ``` for i in range(10): print(simple_grammar_fuzzer(grammar=CGI_GRAMMAR, max_nonterminals=10)) ``` ### A URL Grammar The same properties we have seen for CGI input also hold for more complex inputs. Let us use a grammar to produce a large number of valid URLs: ``` URL_GRAMMAR: Grammar = { "<start>": ["<url>"], "<url>": ["<scheme>://<authority><path><query>"], "<scheme>": ["http", "https", "ftp", "ftps"], "<authority>": ["<host>", "<host>:<port>", "<userinfo>@<host>", "<userinfo>@<host>:<port>"], "<host>": # Just a few ["cispa.saarland", "www.google.com", "fuzzingbook.com"], "<port>": ["80", "8080", "<nat>"], "<nat>": ["<digit>", "<digit><digit>"], "<digit>": ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], "<userinfo>": # Just one ["user:password"], "<path>": # Just a few ["", "/", "/<id>"], "<id>": # Just a few ["abc", "def", "x<digit><digit>"], "<query>": ["", "?<params>"], "<params>": ["<param>", "<param>&<params>"], "<param>": # Just a few ["<id>=<id>", "<id>=<nat>"], } syntax_diagram(URL_GRAMMAR) ``` Again, within milliseconds, we can produce plenty of valid inputs. ``` for i in range(10): print(simple_grammar_fuzzer(grammar=URL_GRAMMAR, max_nonterminals=10)) ``` ### A Natural Language Grammar Finally, grammars are not limited to *formal languages* such as computer inputs, but can also be used to produce *natural language*. This is the grammar we used to pick a title for this book: ``` TITLE_GRAMMAR: Grammar = { "<start>": ["<title>"], "<title>": ["<topic>: <subtopic>"], "<topic>": ["Generating Software Tests", "<fuzzing-prefix>Fuzzing", "The Fuzzing Book"], "<fuzzing-prefix>": ["", "The Art of ", "The Joy of "], "<subtopic>": ["<subtopic-main>", "<subtopic-prefix><subtopic-main>", "<subtopic-main><subtopic-suffix>"], "<subtopic-main>": ["Breaking Software", "Generating Software Tests", "Principles, Techniques and Tools"], "<subtopic-prefix>": ["", "Tools and Techniques for "], "<subtopic-suffix>": [" for <reader-property> and <reader-property>", " for <software-property> and <software-property>"], "<reader-property>": ["Fun", "Profit"], "<software-property>": ["Robustness", "Reliability", "Security"], } syntax_diagram(TITLE_GRAMMAR) from typing import Set titles: Set[str] = set() while len(titles) < 10: titles.add(simple_grammar_fuzzer( grammar=TITLE_GRAMMAR, max_nonterminals=10)) titles ``` (If you find that there is redundancy ("Robustness and Robustness") in here: In [our chapter on coverage-based fuzzing](GrammarCoverageFuzzer.ipynb), we will show how to cover each expansion only once. And if you like some alternatives more than others, [probabilistic grammar fuzzing](ProbabilisticGrammarFuzzer.ipynb) will be there for you.) ## Grammars as Mutation Seeds One very useful property of grammars is that they produce mostly valid inputs. From a syntactical standpoint, the inputs are actually _always_ valid, as they satisfy the constraints of the given grammar. (Of course, one needs a valid grammar in the first place.) However, there are also _semantical_ properties that cannot be easily expressed in a grammar. If, say, for a URL, the port range is supposed to be between 1024 and 2048, this is hard to write in a grammar. If one has to satisfy more complex constraints, one quickly reaches the limits of what a grammar can express. One way around this is to attach constraints to grammars, as we will discuss [later in this book](ConstraintFuzzer.ipynb). Another possibility is to put together the strengths of grammar-based fuzzing and [mutation-based fuzzing](MutationFuzzer.ipynb). The idea is to use the grammar-generated inputs as *seeds* for further mutation-based fuzzing. This way, we can explore not only _valid_ inputs, but also check out the _boundaries_ between valid and invalid inputs. This is particularly interesting as slightly invalid inputs allow to find parser errors (which are often abundant). As with fuzzing in general, it is the unexpected which reveals errors in programs. To use our generated inputs as seeds, we can feed them directly into the mutation fuzzers introduced earlier: ``` from MutationFuzzer import MutationFuzzer # minor dependency number_of_seeds = 10 seeds = [ simple_grammar_fuzzer( grammar=URL_GRAMMAR, max_nonterminals=10) for i in range(number_of_seeds)] seeds m = MutationFuzzer(seeds) [m.fuzz() for i in range(20)] ``` While the first 10 `fuzz()` calls return the seeded inputs (as designed), the later ones again create arbitrary mutations. Using `MutationCoverageFuzzer` instead of `MutationFuzzer`, we could again have our search guided by coverage – and thus bring together the best of multiple worlds. ## A Grammar Toolbox Let us now introduce a few techniques that help us writing grammars. ### Escapes With `<` and `>` delimiting nonterminals in our grammars, how can we actually express that some input should contain `<` and `>`? The answer is simple: Just introduce a symbol for them. ``` simple_nonterminal_grammar: Grammar = { "<start>": ["<nonterminal>"], "<nonterminal>": ["<left-angle><identifier><right-angle>"], "<left-angle>": ["<"], "<right-angle>": [">"], "<identifier>": ["id"] # for now } ``` In `simple_nonterminal_grammar`, neither the expansion for `<left-angle>` nor the expansion for `<right-angle>` can be mistaken as a nonterminal. Hence, we can produce as many as we want. ### Extending Grammars In the course of this book, we frequently run into the issue of creating a grammar by _extending_ an existing grammar with new features. Such an extension is very much like subclassing in object-oriented programming. To create a new grammar $g'$ from an existing grammar $g$, we first copy $g$ into $g'$, and then go and extend existing rules with new alternatives and/or add new symbols. Here's an example, extending the above `nonterminal` grammar with a better rule for identifiers: ``` import copy nonterminal_grammar = copy.deepcopy(simple_nonterminal_grammar) nonterminal_grammar["<identifier>"] = ["<idchar>", "<identifier><idchar>"] nonterminal_grammar["<idchar>"] = ['a', 'b', 'c', 'd'] # for now nonterminal_grammar ``` Since such an extension of grammars is a common operation, we introduce a custom function `extend_grammar()` which first copies the given grammar and then updates it from a dictionary, using the Python dictionary `update()` method: ``` def extend_grammar(grammar: Grammar, extension: Grammar = {}) -> Grammar: new_grammar = copy.deepcopy(grammar) new_grammar.update(extension) return new_grammar ``` This call to `extend_grammar()` extends `simple_nonterminal_grammar` to `nonterminal_grammar` just like the "manual" example above: ``` nonterminal_grammar = extend_grammar(simple_nonterminal_grammar, { "<identifier>": ["<idchar>", "<identifier><idchar>"], # for now "<idchar>": ['a', 'b', 'c', 'd'] } ) ``` ### Character Classes In the above `nonterminal_grammar`, we have enumerated only the first few letters; indeed, enumerating all letters or digits in a grammar manually, as in `<idchar> ::= 'a' | 'b' | 'c' ...` is a bit painful. However, remember that grammars are part of a program, and can thus also be constructed programmatically. We introduce a function `srange()` which constructs a list of characters in a string: ``` import string def srange(characters: str) -> List[Expansion]: """Construct a list with all characters in the string""" return [c for c in characters] ``` If we pass it the constant `string.ascii_letters`, which holds all ASCII letters, `srange()` returns a list of all ASCII letters: ``` string.ascii_letters srange(string.ascii_letters)[:10] ``` We can use such constants in our grammar to quickly define identifiers: ``` nonterminal_grammar = extend_grammar(nonterminal_grammar, { "<idchar>": (srange(string.ascii_letters) + srange(string.digits) + srange("-_")) } ) [simple_grammar_fuzzer(nonterminal_grammar, "<identifier>") for i in range(10)] ``` The shortcut `crange(start, end)` returns a list of all characters in the ASCII range of `start` to (including) `end`: ``` def crange(character_start: str, character_end: str) -> List[Expansion]: return [chr(i) for i in range(ord(character_start), ord(character_end) + 1)] ``` We can use this to express ranges of characters: ``` crange('0', '9') assert crange('a', 'z') == srange(string.ascii_lowercase) ``` ### Grammar Shortcuts In the above `nonterminal_grammar`, as in other grammars, we have to express repetitions of characters using _recursion_, that is, by referring to the original definition: ``` nonterminal_grammar["<identifier>"] ``` It could be a bit easier if we simply could state that a nonterminal should be a non-empty sequence of letters – for instance, as in ``` <identifier> = <idchar>+ ``` where `+` denotes a non-empty repetition of the symbol it follows. Operators such as `+` are frequently introduced as handy _shortcuts_ in grammars. Formally, our grammars come in the so-called [Backus-Naur form](https://en.wikipedia.org/wiki/Backus-Naur_form), or *BNF* for short. Operators _extend_ BNF to so-called _extended BNF*, or *EBNF* for short: * The form `<symbol>?` indicates that `<symbol>` is optional – that is, it can occur 0 or 1 times. * The form `<symbol>+` indicates that `<symbol>` can occur 1 or more times repeatedly. * The form `<symbol>*` indicates that `<symbol>` can occur 0 or more times. (In other words, it is an optional repetition.) To make matters even more interesting, we would like to use _parentheses_ with the above shortcuts. Thus, `(<foo><bar>)?` indicates that the sequence of `<foo>` and `<bar>` is optional. Using such operators, we can define the identifier rule in a simpler way. To this end, let us create a copy of the original grammar and modify the `<identifier>` rule: ``` nonterminal_ebnf_grammar = extend_grammar(nonterminal_grammar, { "<identifier>": ["<idchar>+"] } ) ``` Likewise, we can simplify the expression grammar. Consider how signs are optional, and how integers can be expressed as sequences of digits. ``` EXPR_EBNF_GRAMMAR: Grammar = { "<start>": ["<expr>"], "<expr>": ["<term> + <expr>", "<term> - <expr>", "<term>"], "<term>": ["<factor> * <term>", "<factor> / <term>", "<factor>"], "<factor>": ["<sign>?<factor>", "(<expr>)", "<integer>(.<integer>)?"], "<sign>": ["+", "-"], "<integer>": ["<digit>+"], "<digit>": srange(string.digits) } ``` Let us implement a function `convert_ebnf_grammar()` that takes such an EBNF grammar and automatically translates it into a BNF grammar. #### Excursion: Implementing `convert_ebnf_grammar()` Our aim is to convert EBNF grammars such as the ones above into a regular BNF grammar. This is done by four rules: 1. An expression `(content)op`, where `op` is one of `?`, `+`, `*`, becomes `<new-symbol>op`, with a new rule `<new-symbol> ::= content`. 2. An expression `<symbol>?` becomes `<new-symbol>`, where `<new-symbol> ::= <empty> | <symbol>`. 3. An expression `<symbol>+` becomes `<new-symbol>`, where `<new-symbol> ::= <symbol> | <symbol><new-symbol>`. 4. An expression `<symbol>*` becomes `<new-symbol>`, where `<new-symbol> ::= <empty> | <symbol><new-symbol>`. Here, `<empty>` expands to the empty string, as in `<empty> ::= `. (This is also called an *epsilon expansion*.) If these operators remind you of _regular expressions_, this is not by accident: Actually, any basic regular expression can be converted into a grammar using the above rules (and character classes with `crange()`, as defined above). Applying these rules on the examples above yields the following results: * `<idchar>+` becomes `<idchar><new-symbol>` with `<new-symbol> ::= <idchar> | <idchar><new-symbol>`. * `<integer>(.<integer>)?` becomes `<integer><new-symbol>` with `<new-symbol> ::= <empty> | .<integer>`. Let us implement these rules in three steps. ##### Creating New Symbols First, we need a mechanism to create new symbols. This is fairly straightforward. ``` def new_symbol(grammar: Grammar, symbol_name: str = "<symbol>") -> str: """Return a new symbol for `grammar` based on `symbol_name`""" if symbol_name not in grammar: return symbol_name count = 1 while True: tentative_symbol_name = symbol_name[:-1] + "-" + repr(count) + ">" if tentative_symbol_name not in grammar: return tentative_symbol_name count += 1 assert new_symbol(EXPR_EBNF_GRAMMAR, '<expr>') == '<expr-1>' ``` ##### Expanding Parenthesized Expressions Next, we need a means to extract parenthesized expressions from our expansions and expand them according to the rules above. Let's start with extracting expressions: ``` RE_PARENTHESIZED_EXPR = re.compile(r'\([^()]*\)[?+*]') def parenthesized_expressions(expansion: Expansion) -> List[str]: # In later chapters, we allow expansions to be tuples, # with the expansion being the first element if isinstance(expansion, tuple): expansion = expansion[0] return re.findall(RE_PARENTHESIZED_EXPR, expansion) assert parenthesized_expressions("(<foo>)* (<foo><bar>)+ (+<foo>)? <integer>(.<integer>)?") == [ '(<foo>)*', '(<foo><bar>)+', '(+<foo>)?', '(.<integer>)?'] ``` We can now use these to apply rule number 1, above, introducing new symbols for expressions in parentheses. ``` def convert_ebnf_parentheses(ebnf_grammar: Grammar) -> Grammar: """Convert a grammar in extended BNF to BNF""" grammar = extend_grammar(ebnf_grammar) for nonterminal in ebnf_grammar: expansions = ebnf_grammar[nonterminal] for i in range(len(expansions)): expansion = expansions[i] if not isinstance(expansion, str): expansion = expansion[0] while True: parenthesized_exprs = parenthesized_expressions(expansion) if len(parenthesized_exprs) == 0: break for expr in parenthesized_exprs: operator = expr[-1:] contents = expr[1:-2] new_sym = new_symbol(grammar) exp = grammar[nonterminal][i] opts = None if isinstance(exp, tuple): (exp, opts) = exp assert isinstance(exp, str) expansion = exp.replace(expr, new_sym + operator, 1) if opts: grammar[nonterminal][i] = (expansion, opts) else: grammar[nonterminal][i] = expansion grammar[new_sym] = [contents] return grammar ``` This does the conversion as sketched above: ``` convert_ebnf_parentheses({"<number>": ["<integer>(.<integer>)?"]}) ``` It even works for nested parenthesized expressions: ``` convert_ebnf_parentheses({"<foo>": ["((<foo>)?)+"]}) ``` ##### Expanding Operators After expanding parenthesized expressions, we now need to take care of symbols followed by operators (`?`, `*`, `+`). As with `convert_ebnf_parentheses()`, above, we first extract all symbols followed by an operator. ``` RE_EXTENDED_NONTERMINAL = re.compile(r'(<[^<> ]*>[?+*])') def extended_nonterminals(expansion: Expansion) -> List[str]: # In later chapters, we allow expansions to be tuples, # with the expansion being the first element if isinstance(expansion, tuple): expansion = expansion[0] return re.findall(RE_EXTENDED_NONTERMINAL, expansion) assert extended_nonterminals( "<foo>* <bar>+ <elem>? <none>") == ['<foo>*', '<bar>+', '<elem>?'] ``` Our converter extracts the symbol and the operator, and adds new symbols according to the rules laid out above. ``` def convert_ebnf_operators(ebnf_grammar: Grammar) -> Grammar: """Convert a grammar in extended BNF to BNF""" grammar = extend_grammar(ebnf_grammar) for nonterminal in ebnf_grammar: expansions = ebnf_grammar[nonterminal] for i in range(len(expansions)): expansion = expansions[i] extended_symbols = extended_nonterminals(expansion) for extended_symbol in extended_symbols: operator = extended_symbol[-1:] original_symbol = extended_symbol[:-1] assert original_symbol in ebnf_grammar, \ f"{original_symbol} is not defined in grammar" new_sym = new_symbol(grammar, original_symbol) exp = grammar[nonterminal][i] opts = None if isinstance(exp, tuple): (exp, opts) = exp assert isinstance(exp, str) new_exp = exp.replace(extended_symbol, new_sym, 1) if opts: grammar[nonterminal][i] = (new_exp, opts) else: grammar[nonterminal][i] = new_exp if operator == '?': grammar[new_sym] = ["", original_symbol] elif operator == '*': grammar[new_sym] = ["", original_symbol + new_sym] elif operator == '+': grammar[new_sym] = [ original_symbol, original_symbol + new_sym] return grammar convert_ebnf_operators({"<integer>": ["<digit>+"], "<digit>": ["0"]}) ``` ##### All Together We can combine the two, first extending parentheses and then operators: ``` def convert_ebnf_grammar(ebnf_grammar: Grammar) -> Grammar: return convert_ebnf_operators(convert_ebnf_parentheses(ebnf_grammar)) ``` #### End of Excursion Here's an example of using `convert_ebnf_grammar()`: ``` convert_ebnf_grammar({"<authority>": ["(<userinfo>@)?<host>(:<port>)?"]}) expr_grammar = convert_ebnf_grammar(EXPR_EBNF_GRAMMAR) expr_grammar ``` Success! We have nicely converted the EBNF grammar into BNF. With character classes and EBNF grammar conversion, we have two powerful tools that make the writing of grammars easier. We will use these again and again as it comes to working with grammars. ### Grammar Extensions During the course of this book, we frequently want to specify _additional information_ for grammars, such as [_probabilities_](ProbabilisticGrammarFuzzer.ipynb) or [_constraints_](GeneratorGrammarFuzzer.ipynb). To support these extensions, as well as possibly others, we define an _annotation_ mechanism. Our concept for annotating grammars is to add _annotations_ to individual expansions. To this end, we allow that an expansion cannot only be a string, but also a _pair_ of a string and a set of attributes, as in ```python "<expr>": [("<term> + <expr>", opts(min_depth=10)), ("<term> - <expr>", opts(max_depth=2)), "<term>"] ``` Here, the `opts()` function would allow us to express annotations that apply to the individual expansions; in this case, the addition would be annotated with a `min_depth` value of 10, and the subtraction with a `max_depth` value of 2. The meaning of these annotations is left to the individual algorithms dealing with the grammars; the general idea, though, is that they can be ignored. #### Excursion: Implementing `opts()` Our `opts()` helper function returns a mapping of its arguments to values: ``` def opts(**kwargs: Any) -> Dict[str, Any]: return kwargs opts(min_depth=10) ``` To deal with both expansion strings and pairs of expansions and annotations, we access the expansion string and the associated annotations via designated helper functions, `exp_string()` and `exp_opts()`: ``` def exp_string(expansion: Expansion) -> str: """Return the string to be expanded""" if isinstance(expansion, str): return expansion return expansion[0] exp_string(("<term> + <expr>", opts(min_depth=10))) def exp_opts(expansion: Expansion) -> Dict[str, Any]: """Return the options of an expansion. If options are not defined, return {}""" if isinstance(expansion, str): return {} return expansion[1] def exp_opt(expansion: Expansion, attribute: str) -> Any: """Return the given attribution of an expansion. If attribute is not defined, return None""" return exp_opts(expansion).get(attribute, None) exp_opts(("<term> + <expr>", opts(min_depth=10))) exp_opt(("<term> - <expr>", opts(max_depth=2)), 'max_depth') ``` Finally, we define a helper function that sets a particular option: ``` def set_opts(grammar: Grammar, symbol: str, expansion: Expansion, opts: Option = {}) -> None: """Set the options of the given expansion of grammar[symbol] to opts""" expansions = grammar[symbol] for i, exp in enumerate(expansions): if exp_string(exp) != exp_string(expansion): continue new_opts = exp_opts(exp) if opts == {} or new_opts == {}: new_opts = opts else: for key in opts: new_opts[key] = opts[key] if new_opts == {}: grammar[symbol][i] = exp_string(exp) else: grammar[symbol][i] = (exp_string(exp), new_opts) return raise KeyError( "no expansion " + repr(symbol) + " -> " + repr( exp_string(expansion))) ``` #### End of Excursion ## Checking Grammars Since grammars are represented as strings, it is fairly easy to introduce errors. So let us introduce a helper function that checks a grammar for consistency. The helper function `is_valid_grammar()` iterates over a grammar to check whether all used symbols are defined, and vice versa, which is very useful for debugging; it also checks whether all symbols are reachable from the start symbol. You don't have to delve into details here, but as always, it is important to get the input data straight before we make use of it. ### Excursion: Implementing `is_valid_grammar()` ``` import sys def def_used_nonterminals(grammar: Grammar, start_symbol: str = START_SYMBOL) -> Tuple[Optional[Set[str]], Optional[Set[str]]]: """Return a pair (`defined_nonterminals`, `used_nonterminals`) in `grammar`. In case of error, return (`None`, `None`).""" defined_nonterminals = set() used_nonterminals = {start_symbol} for defined_nonterminal in grammar: defined_nonterminals.add(defined_nonterminal) expansions = grammar[defined_nonterminal] if not isinstance(expansions, list): print(repr(defined_nonterminal) + ": expansion is not a list", file=sys.stderr) return None, None if len(expansions) == 0: print(repr(defined_nonterminal) + ": expansion list empty", file=sys.stderr) return None, None for expansion in expansions: if isinstance(expansion, tuple): expansion = expansion[0] if not isinstance(expansion, str): print(repr(defined_nonterminal) + ": " + repr(expansion) + ": not a string", file=sys.stderr) return None, None for used_nonterminal in nonterminals(expansion): used_nonterminals.add(used_nonterminal) return defined_nonterminals, used_nonterminals def reachable_nonterminals(grammar: Grammar, start_symbol: str = START_SYMBOL) -> Set[str]: reachable = set() def _find_reachable_nonterminals(grammar, symbol): nonlocal reachable reachable.add(symbol) for expansion in grammar.get(symbol, []): for nonterminal in nonterminals(expansion): if nonterminal not in reachable: _find_reachable_nonterminals(grammar, nonterminal) _find_reachable_nonterminals(grammar, start_symbol) return reachable def unreachable_nonterminals(grammar: Grammar, start_symbol=START_SYMBOL) -> Set[str]: return grammar.keys() - reachable_nonterminals(grammar, start_symbol) def opts_used(grammar: Grammar) -> Set[str]: used_opts = set() for symbol in grammar: for expansion in grammar[symbol]: used_opts |= set(exp_opts(expansion).keys()) return used_opts def is_valid_grammar(grammar: Grammar, start_symbol: str = START_SYMBOL, supported_opts: Set[str] = set()) -> bool: """Check if the given `grammar` is valid. `start_symbol`: optional start symbol (default: `<start>`) `supported_opts`: options supported (default: none)""" defined_nonterminals, used_nonterminals = \ def_used_nonterminals(grammar, start_symbol) if defined_nonterminals is None or used_nonterminals is None: return False # Do not complain about '<start>' being not used, # even if start_symbol is different if START_SYMBOL in grammar: used_nonterminals.add(START_SYMBOL) for unused_nonterminal in defined_nonterminals - used_nonterminals: print(repr(unused_nonterminal) + ": defined, but not used", file=sys.stderr) for undefined_nonterminal in used_nonterminals - defined_nonterminals: print(repr(undefined_nonterminal) + ": used, but not defined", file=sys.stderr) # Symbols must be reachable either from <start> or given start symbol unreachable = unreachable_nonterminals(grammar, start_symbol) msg_start_symbol = start_symbol if START_SYMBOL in grammar: unreachable = unreachable - \ reachable_nonterminals(grammar, START_SYMBOL) if start_symbol != START_SYMBOL: msg_start_symbol += " or " + START_SYMBOL for unreachable_nonterminal in unreachable: print(repr(unreachable_nonterminal) + ": unreachable from " + msg_start_symbol, file=sys.stderr) used_but_not_supported_opts = set() if len(supported_opts) > 0: used_but_not_supported_opts = opts_used( grammar).difference(supported_opts) for opt in used_but_not_supported_opts: print( "warning: option " + repr(opt) + " is not supported", file=sys.stderr) return used_nonterminals == defined_nonterminals and len(unreachable) == 0 ``` ### End of Excursion Let us make use of `is_valid_grammar()`. Our grammars defined above pass the test: ``` assert is_valid_grammar(EXPR_GRAMMAR) assert is_valid_grammar(CGI_GRAMMAR) assert is_valid_grammar(URL_GRAMMAR) ``` The check can also be applied to EBNF grammars: ``` assert is_valid_grammar(EXPR_EBNF_GRAMMAR) ``` These ones do not pass the test, though: ``` assert not is_valid_grammar({"<start>": ["<x>"], "<y>": ["1"]}) # type: ignore assert not is_valid_grammar({"<start>": "123"}) # type: ignore assert not is_valid_grammar({"<start>": []}) # type: ignore assert not is_valid_grammar({"<start>": [1, 2, 3]}) # type: ignore ``` (The `#type: ignore` annotations avoid static checkers flagging the above as errors). From here on, we will always use `is_valid_grammar()` when defining a grammar. ## Synopsis This chapter introduces _grammars_ as a simple means to specify input languages, and to use them for testing programs with syntactically valid inputs. A grammar is defined as a mapping of nonterminal symbols to lists of alternative expansions, as in the following example: ``` US_PHONE_GRAMMAR: Grammar = { "<start>": ["<phone-number>"], "<phone-number>": ["(<area>)<exchange>-<line>"], "<area>": ["<lead-digit><digit><digit>"], "<exchange>": ["<lead-digit><digit><digit>"], "<line>": ["<digit><digit><digit><digit>"], "<lead-digit>": ["2", "3", "4", "5", "6", "7", "8", "9"], "<digit>": ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] } assert is_valid_grammar(US_PHONE_GRAMMAR) ``` Nonterminal symbols are enclosed in angle brackets (say, `<digit>`). To generate an input string from a grammar, a _producer_ starts with the start symbol (`<start>`) and randomly chooses a random expansion for this symbol. It continues the process until all nonterminal symbols are expanded. The function `simple_grammar_fuzzer()` does just that: ``` [simple_grammar_fuzzer(US_PHONE_GRAMMAR) for i in range(5)] ``` In practice, though, instead of `simple_grammar_fuzzer()`, you should use [the `GrammarFuzzer` class](GrammarFuzzer.ipynb) or one of its [coverage-based](GrammarCoverageFuzzer.ipynb), [probabilistic-based](ProbabilisticGrammarFuzzer.ipynb), or [generator-based](GeneratorGrammarFuzzer.ipynb) derivatives; these are more efficient, protect against infinite growth, and provide several additional features. This chapter also introduces a [grammar toolbox](#A-Grammar-Toolbox) with several helper functions that ease the writing of grammars, such as using shortcut notations for character classes and repetitions, or extending grammars ## Lessons Learned * Grammars are powerful tools to express and produce syntactically valid inputs. * Inputs produced from grammars can be used as is, or used as seeds for mutation-based fuzzing. * Grammars can be extended with character classes and operators to make writing easier. ## Next Steps As they make a great foundation for generating software tests, we use grammars again and again in this book. As a sneak preview, we can use grammars to [fuzz configurations](ConfigurationFuzzer.ipynb): ``` <options> ::= <option>* <option> ::= -h | --version | -v | -d | -i | --global-config <filename> ``` We can use grammars for [fuzzing functions and APIs](APIFuzzer.ipynb) and [fuzzing graphical user interfaces](WebFuzzer.ipynb): ``` <call-sequence> ::= <call>* <call> ::= urlparse(<url>) | urlsplit(<url>) ``` We can assign [probabilities](ProbabilisticGrammarFuzzer.ipynb) and [constraints](GeneratorGrammarFuzzer.ipynb) to individual expansions: ``` <term>: 50% <factor> * <term> | 30% <factor> / <term> | 20% <factor> <integer>: <digit>+ { <integer> >= 100 } ``` All these extras become especially valuable as we can 1. _infer grammars automatically_, dropping the need to specify them manually, and 2. _guide them towards specific goals_ such as coverage or critical functions; which we also discuss for all techniques in this book. To get there, however, we still have bit of homework to do. In particular, we first have to learn how to * [create an efficient grammar fuzzer](GrammarFuzzer.ipynb) ## Background As one of the foundations of human language, grammars have been around as long as human language existed. The first _formalization_ of generative grammars was by Dakṣiputra Pāṇini in 350 BC \cite{Panini350bce}. As a general means to express formal languages for both data and programs, their role in computer science cannot be overstated. The seminal work by Chomsky \cite{Chomsky1956} introduced the central models of regular languages, context-free grammars, context-sensitive grammars, and universal grammars as they are used (and taught) in computer science as a means to specify input and programming languages ever since. The use of grammars for _producing_ test inputs goes back to Burkhardt \cite{Burkhardt1967}, to be later rediscovered and applied by Hanford \cite{Hanford1970} and Purdom \cite{Purdom1972}. The most important use of grammar testing since then has been *compiler testing*. Actually, grammar-based testing is one important reason why compilers and Web browsers work as they should: * The [CSmith](https://embed.cs.utah.edu/csmith/) tool \cite{Yang2011} specifically targets C programs, starting with a C grammar and then applying additional steps, such as referring to variables and functions defined earlier or ensuring integer and type safety. Their authors have used it "to find and report more than 400 previously unknown compiler bugs." * The [LangFuzz](http://issta2016.cispa.saarland/interview-with-christian-holler/) work \cite{Holler2012}, which shares two authors with this book, uses a generic grammar to produce outputs, and is used day and night to generate JavaScript programs and test their interpreters; as of today, it has found more than 2,600 bugs in browsers such as Mozilla Firefox, Google Chrome, and Microsoft Edge. * The [EMI Project](http://web.cs.ucdavis.edu/~su/emi-project/) \cite{Le2014} uses grammars to stress-test C compilers, transforming known tests into alternative programs that should be semantically equivalent over all inputs. Again, this has led to more than 100 bugs in C compilers being fixed. * [Grammarinator](https://github.com/renatahodovan/grammarinator) \cite{Hodovan2018} is an open-source grammar fuzzer (written in Python!), using the popular ANTLR format as grammar specification. Like LangFuzz, it uses the grammar for both parsing and producing, and has found more than 100 issues in the *JerryScript* lightweight JavaScript engine and an associated platform. * [Domato](https://github.com/googleprojectzero/domato) is a generic grammar generation engine that is specifically used for fuzzing DOM input. It has revealed a number of security issues in popular Web browsers. Compilers and Web browsers, of course, are not only domains where grammars are needed for testing, but also domains where grammars are well-known. Our claim in this book is that grammars can be used to generate almost _any_ input, and our aim is to empower you to do precisely that. ## Exercises ### Exercise 1: A JSON Grammar Take a look at the [JSON specification](http://www.json.org) and derive a grammar from it: * Use _character classes_ to express valid characters * Use EBNF to express repetitions and optional parts * Assume that - a string is a sequence of digits, ASCII letters, punctuation and space characters without quotes or escapes - whitespace is just a single space. * Use `is_valid_grammar()` to ensure the grammar is valid. Feed the grammar into `simple_grammar_fuzzer()`. Do you encounter any errors, and why? **Solution.** This is a fairly straightforward translation: ``` CHARACTERS_WITHOUT_QUOTE = (string.digits + string.ascii_letters + string.punctuation.replace('"', '').replace('\\', '') + ' ') JSON_EBNF_GRAMMAR: Grammar = { "<start>": ["<json>"], "<json>": ["<element>"], "<element>": ["<ws><value><ws>"], "<value>": ["<object>", "<array>", "<string>", "<number>", "true", "false", "null", "'; DROP TABLE STUDENTS"], "<object>": ["{<ws>}", "{<members>}"], "<members>": ["<member>(,<members>)*"], "<member>": ["<ws><string><ws>:<element>"], "<array>": ["[<ws>]", "[<elements>]"], "<elements>": ["<element>(,<elements>)*"], "<element>": ["<ws><value><ws>"], "<string>": ['"' + "<characters>" + '"'], "<characters>": ["<character>*"], "<character>": srange(CHARACTERS_WITHOUT_QUOTE), "<number>": ["<int><frac><exp>"], "<int>": ["<digit>", "<onenine><digits>", "-<digits>", "-<onenine><digits>"], "<digits>": ["<digit>+"], "<digit>": ['0', "<onenine>"], "<onenine>": crange('1', '9'), "<frac>": ["", ".<digits>"], "<exp>": ["", "E<sign><digits>", "e<sign><digits>"], "<sign>": ["", '+', '-'], # "<ws>": srange(string.whitespace) "<ws>": [" "] } assert is_valid_grammar(JSON_EBNF_GRAMMAR) JSON_GRAMMAR = convert_ebnf_grammar(JSON_EBNF_GRAMMAR) from ExpectError import ExpectError for i in range(50): with ExpectError(): print(simple_grammar_fuzzer(JSON_GRAMMAR, '<object>')) ``` We get these errors because `simple_grammar_fuzzer()` first expands to a maximum number of elements, and then is limited because every further expansion would _increase_ the number of nonterminals, even though these may eventually reduce the string length. This issue is addressed in the [next chapter](GrammarFuzzer.ipynb), introducing a more solid algorithm for producing strings from grammars. ### Exercise 2: Finding Bugs The name `simple_grammar_fuzzer()` does not come by accident: The way it expands grammars is limited in several ways. What happens if you apply `simple_grammar_fuzzer()` on `nonterminal_grammar` and `expr_grammar`, as defined above, and why? **Solution**. `nonterminal_grammar` does not work because `simple_grammar_fuzzer()` eventually tries to expand the just generated nonterminal: ``` from ExpectError import ExpectError, ExpectTimeout with ExpectError(): simple_grammar_fuzzer(nonterminal_grammar, log=True) ``` For `expr_grammar`, things are even worse, as `simple_grammar_fuzzer()` can start a series of infinite expansions: ``` with ExpectTimeout(1): for i in range(10): print(simple_grammar_fuzzer(expr_grammar)) ``` Both issues are addressed and discussed in the [next chapter](GrammarFuzzer.ipynb), introducing a more solid algorithm for producing strings from grammars. ### Exercise 3: Grammars with Regular Expressions In a _grammar extended with regular expressions_, we can use the special form ``` /regex/ ``` to include regular expressions in expansions. For instance, we can have a rule ``` <integer> ::= /[+-]?[0-9]+/ ``` to quickly express that an integer is an optional sign, followed by a sequence of digits. #### Part 1: Convert regular expressions Write a converter `convert_regex(r)` that takes a regular expression `r` and creates an equivalent grammar. Support the following regular expression constructs: * `*`, `+`, `?`, `()` should work just in EBNFs, above. * `a|b` should translate into a list of alternatives `[a, b]`. * `.` should match any character except newline. * `[abc]` should translate into `srange("abc")` * `[^abc]` should translate into the set of ASCII characters _except_ `srange("abc")`. * `[a-b]` should translate into `crange(a, b)` * `[^a-b]` should translate into the set of ASCII characters _except_ `crange(a, b)`. Example: `convert_regex(r"[0-9]+")` should yield a grammar such as ```python { "<start>": ["<s1>"], "<s1>": [ "<s2>", "<s1><s2>" ], "<s2>": crange('0', '9') } ``` **Solution.** Left as exercise to the reader. #### Part 2: Identify and expand regular expressions Write a converter `convert_regex_grammar(g)` that takes a EBNF grammar `g` containing regular expressions in the form `/.../` and creates an equivalent BNF grammar. Support the regular expression constructs as above. Example: `convert_regex_grammar({ "<integer>" : "/[+-]?[0-9]+/" })` should yield a grammar such as ```python { "<integer>": ["<s1><s3>"], "<s1>": [ "", "<s2>" ], "<s2>": srange("+-"), "<s3>": [ "<s4>", "<s4><s3>" ], "<s4>": crange('0', '9') } ``` Optional: Support _escapes_ in regular expressions: `\c` translates to the literal character `c`; `\/` translates to `/` (and thus does not end the regular expression); `\\` translates to `\`. **Solution.** Left as exercise to the reader. ### Exercise 4: Defining Grammars as Functions (Advanced) To obtain a nicer syntax for specifying grammars, one can make use of Python constructs which then will be _parsed_ by an additional function. For instance, we can imagine a grammar definition which uses `|` as a means to separate alternatives: ``` def expression_grammar_fn(): start = "<expr>" expr = "<term> + <expr>" | "<term> - <expr>" term = "<factor> * <term>" | "<factor> / <term>" | "<factor>" factor = "+<factor>" | "-<factor>" | "(<expr>)" | "<integer>.<integer>" | "<integer>" integer = "<digit><integer>" | "<digit>" digit = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' ``` If we execute `expression_grammar_fn()`, this will yield an error. Yet, the purpose of `expression_grammar_fn()` is not to be executed, but to be used as _data_ from which the grammar will be constructed. ``` with ExpectError(): expression_grammar_fn() ``` To this end, we make use of the `ast` (abstract syntax tree) and `inspect` (code inspection) modules. ``` import ast import inspect ``` First, we obtain the source code of `expression_grammar_fn()`... ``` source = inspect.getsource(expression_grammar_fn) source ``` ... which we then parse into an abstract syntax tree: ``` tree = ast.parse(source) ``` We can now parse the tree to find operators and alternatives. `get_alternatives()` iterates over all nodes `op` of the tree; If the node looks like a binary _or_ (`|` ) operation, we drill deeper and recurse. If not, we have reached a single production, and we try to get the expression from the production. We define the `to_expr` parameter depending on how we want to represent the production. In this case, we represent a single production by a single string. ``` def get_alternatives(op, to_expr=lambda o: o.s): if isinstance(op, ast.BinOp) and isinstance(op.op, ast.BitOr): return get_alternatives(op.left, to_expr) + [to_expr(op.right)] return [to_expr(op)] ``` `funct_parser()` takes the abstract syntax tree of a function (say, `expression_grammar_fn()`) and iterates over all assignments: ``` def funct_parser(tree, to_expr=lambda o: o.s): return {assign.targets[0].id: get_alternatives(assign.value, to_expr) for assign in tree.body[0].body} ``` The result is a grammar in our regular format: ``` grammar = funct_parser(tree) for symbol in grammar: print(symbol, "::=", grammar[symbol]) ``` #### Part 1 (a): One Single Function Write a single function `define_grammar(fn)` that takes a grammar defined as function (such as `expression_grammar_fn()`) and returns a regular grammar. **Solution**. This is straightforward: ``` def define_grammar(fn, to_expr=lambda o: o.s): source = inspect.getsource(fn) tree = ast.parse(source) grammar = funct_parser(tree, to_expr) return grammar define_grammar(expression_grammar_fn) ``` **Note.** Python allows us to directly bind the generated grammar to the name `expression_grammar_fn` using function decorators. This can be used to ensure that we do not have a faulty function lying around: ```python @define_grammar def expression_grammar(): start = "<expr>" expr = "<term> + <expr>" | "<term> - <expr>" #... ``` #### Part 1 (b): Alternative representations We note that the grammar representation we designed previously does not allow simple generation of alternatives such as `srange()` and `crange()`. Further, one may find the string representation of expressions limiting. It turns out that it is simple to extend our grammar definition to support grammars such as below: ``` def define_name(o): return o.id if isinstance(o, ast.Name) else o.s def define_expr(op): if isinstance(op, ast.BinOp) and isinstance(op.op, ast.Add): return (*define_expr(op.left), define_name(op.right)) return (define_name(op),) def define_ex_grammar(fn): return define_grammar(fn, define_expr) ``` The grammar: ```python @define_ex_grammar def expression_grammar(): start = expr expr = (term + '+' + expr | term + '-' + expr) term = (factor + '*' + term | factor + '/' + term | factor) factor = ('+' + factor | '-' + factor | '(' + expr + ')' | integer + '.' + integer | integer) integer = (digit + integer | digit) digit = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' for symbol in expression_grammar: print(symbol, "::=", expression_grammar[symbol]) ``` **Note.** The grammar data structure thus obtained is a little more detailed than the standard data structure. It represents each production as a tuple. We note that we have not enabled `srange()` or `crange()` in the above grammar. How would you go about adding these? (*Hint:* wrap `define_expr()` to look for `ast.Call`) #### Part 2: Extended Grammars Introduce an operator `*` that takes a pair `(min, max)` where `min` and `max` are the minimum and maximum number of repetitions, respectively. A missing value `min` stands for zero; a missing value `max` for infinity. ``` def identifier_grammar_fn(): identifier = idchar * (1,) ``` With the `*` operator, we can generalize the EBNF operators – `?` becomes (0,1), `*` becomes (0,), and `+` becomes (1,). Write a converter that takes an extended grammar defined using `*`, parse it, and convert it into BNF. **Solution.** No solution yet :-)
github_jupyter
``` import requests import json import re # Setting the base URL for the ARAX reasoner and its endpoint endpoint_url = 'https://arax.rtx.ai/api/rtx/v1/query' # Given we have some chemical substances which are linked to asthma exacerbations for a certain cohort of patients, # we want to find what diseases are associated with them # This DSL command extracts the pathways to view which diseases are associated with those chemicals. # We do this by creating a dict of the request, specifying a start previous Message and the list of DSL commands query = {"previous_message_processing_plan": {"processing_actions": [ "add_qnode(curie=CHEMBL.COMPOUND:CHEMBL896, type= chemical_substance, id=n0)", "add_qnode(type=protein, id=n1)", "add_qnode(type=disease, id=n2)", "add_qedge(source_id=n0, target_id=n1, id=e0)", "add_qedge(source_id=n1, target_id=n2, id=e1)", "expand()", #"expand(kp=RTX-KG2)". "resultify()", "filter_results(action=limit_number_of_results, max_results=20)", "return(message=true, store=true)", ]}} # Sending the request to RTX and check the status print(f"Executing query at {endpoint_url}\nPlease wait...") response_content = requests.post(endpoint_url, json=query, headers={'accept': 'application/json'}) status_code = response_content.status_code if status_code != 200: print("ERROR returned with status "+str(status_code)) print(response_content.json()) else: print(f"Response returned with status {status_code}") # Unpack respsonse from JSON and display the information log response_dict = response_content.json() for message in response_dict['log']: if message['level'] >= 20: print(message['prefix']+message['message']) # These URLs provide direct access to resulting data and GUI if 'id' in response_dict and response_dict['id'] is not None: print(f"Data: {response_dict['id']}") match = re.search(r'(\d+)$', response_dict['id']) if match: print(f"GUI: https://arax.rtx.ai/?m={match.group(1)}") else: print("No id was returned in response") # Or you can view the entire Translator API response Message print(json.dumps(response_dict, indent=2, sort_keys=True)) # Setting the base URL for the ARAX reasoner and its endpoint endpoint_url = 'https://arax.rtx.ai/api/rtx/v1/query' # Given we have some chemical substances which are linked to asthma exacerbations for a certain cohort of patients, we want to # find what diseases are associated with them # This DSL command extracts the pathways to view which phenotypes are associated with those chemicals. # We do this by creating a dict of the request, specifying a start previous Message and the list of DSL commands query = {"previous_message_processing_plan": {"processing_actions": [ "add_qnode(curie=CHEMBL.COMPOUND:CHEMBL896, type= chemical_substance, id=n0)", "add_qnode(type=protein, id=n1)", "add_qnode(type=phenotypic_feature, id=n2)", "add_qedge(source_id=n0, target_id=n1, id=e0)", "add_qedge(source_id=n1, target_id=n2, id=e1)", "expand()", #"expand(kp=RTX-KG2)". "resultify()", "filter_results(action=limit_number_of_results, max_results=20)", "return(message=true, store=true)", ]}} # Sending the request to RTX and check the status print(f"Executing query at {endpoint_url}\nPlease wait...") response_content = requests.post(endpoint_url, json=query, headers={'accept': 'application/json'}) status_code = response_content.status_code if status_code != 200: print("ERROR returned with status "+str(status_code)) print(response_content.json()) else: print(f"Response returned with status {status_code}") # Unpack respsonse from JSON and display the information log response_dict = response_content.json() for message in response_dict['log']: if message['level'] >= 20: print(message['prefix']+message['message']) # These URLs provide direct access to resulting data and GUI if 'id' in response_dict and response_dict['id'] is not None: print(f"Data: {response_dict['id']}") match = re.search(r'(\d+)$', response_dict['id']) if match: print(f"GUI: https://arax.rtx.ai/?m={match.group(1)}") else: print("No id was returned in response") # Or you can view the entire Translator API response Message print(json.dumps(response_dict, indent=2, sort_keys=True)) ```
github_jupyter
# Python: the basics Python is a general purpose programming language that supports rapid development of scripts and applications. Python's main advantages: * Open Source software, supported by Python Software Foundation * Available on all major platforms (ie. Windows, Linux and MacOS) * It is a general-purpose programming language, designed for readability * Supports multiple programming paradigms ('functional', 'object oriented') * Very large community with a rich ecosystem of third-party packages ## Interpreter Python is an interpreted language[*](https://softwareengineering.stackexchange.com/a/24560) which can be used in two ways: * "Interactive" Mode: It functions like an "advanced calculator", executing one command at a time: ```bash user:host:~$ python Python 3.5.1 (default, Oct 23 2015, 18:05:06) [GCC 4.8.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 2 + 2 4 >>> print("Hello World") Hello World ``` * "Scripting" Mode: Executing a series of "commands" saved in text file, usually with a `.py` extension after the name of your file: ```bash user:host:~$ python my_script.py Hello World ``` ## Using interactive Python in Jupyter-style notebooks A convenient and powerful way to use interactive-mode Python is via a Jupyter Notebook, or similar browser-based interface. This particularly lends itself to data analysis since the notebook records a history of commands and shows output and graphs immediately in the browser. There are several ways you can run a Jupyter(-style) notebook - locally installed on your computer or hosted as a service on the web. Today we will use a Jupyter notebook service provided by Google: https://colab.research.google.com (Colaboratory). ### Jupyter-style notebooks: a quick tour Go to https://colab.research.google.com and login with your Google account. Select ***NEW NOTEBOOK → NEW PYTHON 3 NOTEBOOK*** - a new notebook will be created. --- Type some Python code in the top cell, eg: ```python print("Hello Jupyter !") ``` ***Shift-Enter*** to run the contents of the cell --- You can add new cells. ***Insert → Insert Code Cell*** --- NOTE: When the text on the left hand of the cell is: `In [*]` (with an asterisk rather than a number), the cell is still running. It's usually best to wait until one cell has finished running before running the next. Let's begin writing some code in our notebook. ``` print("Hello Jupyter !") ``` In Jupyter/Collaboratory, just typing the name of a variable in the cell prints its representation: ``` message = "Hello again !" message # A 'hash' symbol denotes a comment # This is a comment. Anything after the 'hash' symbol on the line is ignored by the Python interpreter print("No comment") # comment ``` ## Variables and data types ### Integers, floats, strings ``` a = 5 a type(a) ``` Adding a decimal point creates a `float` ``` b = 5.0 b type(b) ``` `int` and `float` are collectively called 'numeric' types (There are also other numeric types like `hex` for hexidemical and `complex` for complex numbers) ## Challenge - Types What is the **type** of the variable `letters` defined below ? `letters = "ABACBS"` * A) `int` * B) `str` * C) `float` * D) `text` Write some code the outputs the type - paste your answer into the Etherpad. ## Solution Option B - `str`. ``` letters = "ABACBS" type(letters) ``` ### Strings ``` some_words = "Python3 strings are Unicode (UTF-8) ❤❤❤ 😸 蛇" some_words type(some_words) ``` The variable `some_words` is of type `str`, short for "string". Strings hold sequences of characters, which can be letters, numbers, punctuation or more exotic forms of text (even emoji!). ## Operators We can perform mathematical calculations in Python using the basic operators: `+` `-` `*` `/` `%` `//` `**` ``` 2 + 2 # Addition 6 * 7 # Multiplication 5/2 # Division 13 % 5 # Modulo 13 // 5 # Floor Division 2 ** 16 # Power # int + int = int a = 5 a + 1 # float + int = float b = 5.0 b + 1 a + b ``` ```python some_words = "I'm a string" a = 6 a + some_words ``` Outputs: ``` --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-1-781eba7cf148> in <module>() 1 some_words = "I'm a string" 2 a = 6 ----> 3 a + some_words TypeError: unsupported operand type(s) for +: 'int' and 'str' ``` ``` str(a) + " " + some_words # Shorthand: operators with assignment a += 1 a # Equivalent to: # a = a + 1 ``` ### Boolean operations We can also use comparison and logic operators: `<, >, ==, !=, <=, >=` and statements of identity such as `and, or, not`. The data type returned by this is called a _boolean_. ``` 3 > 4 True and True True or False ``` ## Lists and sequence types ### Lists ``` numbers = [2, 4, 6, 8, 10] numbers # `len` get the length of a list len(numbers) # Lists can contain multiple data types, including other lists mixed_list = ["asdf", 2, 3.142, numbers, ['a','b','c']] mixed_list ``` You can retrieve items from a list by their *index*. In Python, the first item has an index of 0 (zero). ``` numbers[0] numbers[3] ``` You can also assign a new value to any position in the list. ``` numbers[3] = numbers[3] * 100 numbers ``` You can append items to the end of the list. ``` numbers.append(12) numbers ``` You can add multiple items to the end of a list with `extend`. ``` numbers.extend([14, 16, 18]) numbers ``` ### Loops A for loop can be used to access the elements in a list or other Python data structure one at a time. We will learn about loops in other lesson. ``` for num in numbers: print(num) ``` **Indentation** is very important in Python. Note that the second line in the example above is indented, indicating the code that is the body of the loop. To find out what methods are available for an object, we can use the built-in `help` command: ``` help(numbers) ``` ### Tuples A tuple is similar to a list in that it's an ordered sequence of elements. However, tuples can not be changed once created (they are "immutable"). Tuples are created by placing comma-separated values inside parentheses `()`. ``` tuples_are_immutable = ("bar", 100, 200, "foo") tuples_are_immutable tuples_are_immutable[1] ``` ```python tuples_are_immutable[1] = 666 ``` Outputs: ``` --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-39-c91965b0815a> in <module>() ----> 1 tuples_are_immutable[1] = 666 TypeError: 'tuple' object does not support item assignment ``` ### Dictionaries Dictionaries are a container that store key-value pairs. They are unordered. Other programming languages might call this a 'hash', 'hashtable' or 'hashmap'. ``` pairs = {'Apple': 1, 'Orange': 2, 'Pear': 4} pairs pairs['Orange'] pairs['Orange'] = 16 pairs ``` The `items` method returns a sequence of the key-value pairs as tuples. `values` returns a sequence of just the values. `keys` returns a sequence of just the keys. --- In Python 3, the `.items()`, `.values()` and `.keys()` methods return a ['dictionary view' object](https://docs.python.org/3/library/stdtypes.html#dictionary-view-objects) that behaves like a list or tuple in for loops but doesn't support indexing. 'Dictionary views' stay in sync even when the dictionary changes. You can turn them into a normal list or tuple with the `list()` or `tuple()` functions. ``` pairs.items() # list(pairs.items()) pairs.values() # list(pairs.values()) pairs.keys() # list(pairs.keys()) len(pairs) dict_of_dicts = {'first': {1:2, 2: 4, 4: 8, 8: 16}, 'second': {'a': 2.2, 'b': 4.4}} dict_of_dicts ``` ## Challenge - Dictionaries Given the dictionary: ```python jam_ratings = {'Plum': 6, 'Apricot': 2, 'Strawberry': 8} ``` How would you change the value associated with the key `Apricot` to `9`. A) `jam_ratings = {'apricot': 9}` B) `jam_ratings[9] = 'Apricot'` C) `jam_ratings['Apricot'] = 9` D) `jam_ratings[2] = 'Apricot'` ## Solution - Dictionaries The correct answer is **C**. **A** assigns the name `jam_ratings` to a new dictionary with only the key `apricot` - not only are the other jam ratings now missing, but strings used as dictionary keys are *case sensitive* - `apricot` is not the same key as `Apricot`. **B** mixes up the value and the key. Assigning to a dictionary uses the form: `dictionary[key] = value`. **C** is correct. Bonus - another way to do this would be `jam_ratings.update({'Apricot': 9})` or even `jam_ratings.update(Apricot=9)`. **D** mixes up the value and the key (and doesn't actually include the new value to be assigned, `9`, anywhere). `2` is the original *value*, `Apricot` is the key. Assigning to a dictionary uses the form: `dictionary[key] = value`.
github_jupyter
# Tensor Manipulation: Psi4 and NumPy manipulation routines Contracting tensors together forms the core of the Psi4NumPy project. First let us consider the popluar [Einstein Summation Notation](https://en.wikipedia.org/wiki/Einstein_notation) which allows for very succinct descriptions of a given tensor contraction. For example, let us consider a [inner (dot) product](https://en.wikipedia.org/wiki/Dot_product): $$c = \sum_{ij} A_{ij} * B_{ij}$$ With the Einstein convention, all indices that are repeated are considered summed over, and the explicit summation symbol is dropped: $$c = A_{ij} * B_{ij}$$ This can be extended to [matrix multiplication](https://en.wikipedia.org/wiki/Matrix_multiplication): \begin{align} \rm{Conventional}\;\;\; C_{ik} &= \sum_{j} A_{ij} * B_{jk} \\ \rm{Einstein}\;\;\; C &= A_{ij} * B_{jk} \\ \end{align} Where the $C$ matrix has *implied* indices of $C_{ik}$ as the only repeated index is $j$. However, there are many cases where this notation fails. Thus we often use the generalized Einstein convention. To demonstrate let us examine a [Hadamard product](https://en.wikipedia.org/wiki/Hadamard_product_(matrices)): $$C_{ij} = \sum_{ij} A_{ij} * B_{ij}$$ This operation is nearly identical to the dot product above, and is not able to be written in pure Einstein convention. The generalized convention allows for the use of indices on the left hand side of the equation: $$C_{ij} = A_{ij} * B_{ij}$$ Usually it should be apparent within the context the exact meaning of a given expression. Finally we also make use of Matrix notation: \begin{align} {\rm Matrix}\;\;\; \bf{D} &= \bf{A B C} \\ {\rm Einstein}\;\;\; D_{il} &= A_{ij} B_{jk} C_{kl} \end{align} Note that this notation is signified by the use of bold characters to denote matrices and consecutive matrices next to each other imply a chain of matrix multiplications! ## Einsum To perform most operations we turn to [NumPy's einsum function](https://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html) which allows the Einsten convention as an input. In addition to being much easier to read, manipulate, and change, it is also much more efficient that a pure Python implementation. To begin let us consider the construction of the following tensor (which you may recognize): $$G_{pq} = 2.0 * I_{pqrs} D_{rs} - 1.0 * I_{prqs} D_{rs}$$ First let us import our normal suite of modules: ``` import numpy as np import psi4 import time ``` We can then use conventional Python loops and einsum to perform the same task. Keep size relatively small as these 4-index tensors grow very quickly in size. ``` size = 20 if size > 30: raise Exception("Size must be smaller than 30.") D = np.random.rand(size, size) I = np.random.rand(size, size, size, size) # Build the fock matrix using loops, while keeping track of time tstart_loop = time.time() Gloop = np.zeros((size, size)) for p in range(size): for q in range(size): for r in range(size): for s in range(size): Gloop[p, q] += 2 * I[p, q, r, s] * D[r, s] Gloop[p, q] -= I[p, r, q, s] * D[r, s] g_loop_time = time.time() - tstart_loop # Build the fock matrix using einsum, while keeping track of time tstart_einsum = time.time() J = np.einsum('pqrs,rs', I, D, optimize=True) K = np.einsum('prqs,rs', I, D, optimize=True) G = 2 * J - K einsum_time = time.time() - tstart_einsum # Make sure the correct answer is obtained print('The loop and einsum fock builds match: %s\n' % np.allclose(G, Gloop)) # Print out relative times for explicit loop vs einsum Fock builds print('Time for loop G build: %14.4f seconds' % g_loop_time) print('Time for einsum G build: %14.4f seconds' % einsum_time) print('G builds with einsum are {:3.4f} times faster than Python loops!'.format(g_loop_time / einsum_time)) ``` As you can see, the einsum function is considerably faster than the pure Python loops and, in this author's opinion, much cleaner and easier to use. ## Dot Now let us turn our attention to a more canonical matrix multiplication example such as: $$D_{il} = A_{ij} B_{jk} C_{kl}$$ We could perform this operation using einsum; however, matrix multiplication is an extremely common operation in all branches of linear algebra. Thus, these functions have been optimized to be more efficient than the `einsum` function. The matrix product will explicitly compute the following operation: $$C_{ij} = A_{ij} * B_{ij}$$ This can be called with [NumPy's dot function](https://docs.scipy.org/doc/numpy/reference/generated/numpy.dot.html#numpy.dot). ``` size = 200 A = np.random.rand(size, size) B = np.random.rand(size, size) C = np.random.rand(size, size) # First compute the pair product tmp_dot = np.dot(A, B) tmp_einsum = np.einsum('ij,jk->ik', A, B, optimize=True) print("Pair product allclose: %s" % np.allclose(tmp_dot, tmp_einsum)) ``` Now that we have proved exactly what the dot product does, let us consider the full chain and do a timing comparison: ``` D_dot = np.dot(A, B).dot(C) D_einsum = np.einsum('ij,jk,kl->il', A, B, C, optimize=True) print("Chain multiplication allclose: %s" % np.allclose(D_dot, D_einsum)) print("\nnp.dot time:") %timeit np.dot(A, B).dot(C) print("\nnp.einsum time") # no optimization here for illustrative purposes! %timeit np.einsum('ij,jk,kl->il', A, B, C) ``` On most machines the `np.dot` times are roughly ~2,000 times faster. The reason is twofold: - The `np.dot` routines typically call [Basic Linear Algebra Subprograms (BLAS)](https://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprograms). The BLAS routines are highly optimized and threaded versions of the code. - The `np.einsum` code will not factorize the operation by default; Thus, the overall cost is ${\cal O}(N^4)$ (as there are four indices) rather than the factored $(\bf{A B}) \bf{C}$ which runs ${\cal O}(N^3)$. The first issue is difficult to overcome; however, the second issue can be resolved by the following: ``` print("np.einsum factorized time:") # no optimization here for illustrative purposes! %timeit np.einsum('ik,kl->il', np.einsum('ij,jk->ik', A, B), C) ``` On most machines the factorized `einsum` expression is only ~10 times slower than `np.dot`. While a massive improvement, this is a clear demonstration the BLAS usage is usually recommended. It is a tradeoff between speed and readability. The Psi4NumPy project tends to lean toward `einsum` usage except in case where the benefit is too large to pass up. Starting in NumPy 1.12, the [einsum function](https://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html) has a `optimize` flag which will automatically factorize the einsum code for you using a greedy algorithm, leading to considerable speedups at almost no cost: ``` print("\nnp.einsum optimized time") %timeit np.einsum('ij,jk,kl->il', A, B, C, optimize=True) ``` In this example, using `optimize=True` for automatic factorization is only 25% slower than `np.dot`. Furthermore, it is ~5 times faster than factorizing the expression by hand, which represents a very good trade-off between speed and readability. When unsure, `optimize=True` is strongly recommended. ## Complex tensor manipulations Let us consider a popular index transformation example: $$M_{pqrs} = C_{pi} C_{qj} I_{ijkl} C_{rk} C_{sl}$$ Here, a naive `einsum` call would scale like $\mathcal{O}(N^8)$ which translates to an extremely costly computation for all but the smallest $N$. ``` # Grab orbitals size = 15 if size > 15: raise Exception("Size must be smaller than 15.") C = np.random.rand(size, size) I = np.random.rand(size, size, size, size) # Numpy einsum N^8 transformation. print("\nStarting Numpy's N^8 transformation...") n8_tstart = time.time() # no optimization here for illustrative purposes! MO_n8 = np.einsum('pI,qJ,pqrs,rK,sL->IJKL', C, C, I, C, C) n8_time = time.time() - n8_tstart print("...transformation complete in %.3f seconds." % (n8_time)) # Numpy einsum N^5 transformation. print("\n\nStarting Numpy's N^5 transformation with einsum...") n5_tstart = time.time() # no optimization here for illustrative purposes! MO_n5 = np.einsum('pA,pqrs->Aqrs', C, I) MO_n5 = np.einsum('qB,Aqrs->ABrs', C, MO_n5) MO_n5 = np.einsum('rC,ABrs->ABCs', C, MO_n5) MO_n5 = np.einsum('sD,ABCs->ABCD', C, MO_n5) n5_time = time.time() - n5_tstart print("...transformation complete in %.3f seconds." % n5_time) print("\nN^5 %4.2f faster than N^8 algorithm!" % (n8_time / n5_time)) print("Allclose: %s" % np.allclose(MO_n8, MO_n5)) # Numpy einsum optimized transformation. print("\nNow Numpy's optimized transformation...") n8_tstart = time.time() MO_n8 = np.einsum('pI,qJ,pqrs,rK,sL->IJKL', C, C, I, C, C, optimize=True) n8_time_opt = time.time() - n8_tstart print("...optimized transformation complete in %.3f seconds." % (n8_time_opt)) # Numpy GEMM N^5 transformation. # Try to figure this one out! print("\n\nStarting Numpy's N^5 transformation with dot...") dgemm_tstart = time.time() MO = np.dot(C.T, I.reshape(size, -1)) MO = np.dot(MO.reshape(-1, size), C) MO = MO.reshape(size, size, size, size).transpose(1, 0, 3, 2) MO = np.dot(C.T, MO.reshape(size, -1)) MO = np.dot(MO.reshape(-1, size), C) MO = MO.reshape(size, size, size, size).transpose(1, 0, 3, 2) dgemm_time = time.time() - dgemm_tstart print("...transformation complete in %.3f seconds." % dgemm_time) print("\nAllclose: %s" % np.allclose(MO_n8, MO)) print("N^5 %4.2f faster than N^8 algorithm!" % (n8_time / dgemm_time)) ```
github_jupyter
# Joint Probability This notebook is part of [Bite Size Bayes](https://allendowney.github.io/BiteSizeBayes/), an introduction to probability and Bayesian statistics using Python. Copyright 2020 Allen B. Downey License: [Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)](https://creativecommons.org/licenses/by-nc-sa/4.0/) The following cell downloads `utils.py`, which contains some utility function we'll need. ``` from os.path import basename, exists def download(url): filename = basename(url) if not exists(filename): from urllib.request import urlretrieve local, _ = urlretrieve(url, filename) print('Downloaded ' + local) download('https://github.com/AllenDowney/BiteSizeBayes/raw/master/utils.py') ``` If everything we need is installed, the following cell should run with no error messages. ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt ``` ## Review So far we have been working with distributions of only one variable. In this notebook we'll take a step toward multivariate distributions, starting with two variables. We'll use cross-tabulation to compute a **joint distribution**, then use the joint distribution to compute **conditional distributions** and **marginal distributions**. We will re-use `pmf_from_seq`, which I introduced in a previous notebook. ``` def pmf_from_seq(seq): """Make a PMF from a sequence of values. seq: sequence returns: Series representing a PMF """ pmf = pd.Series(seq).value_counts(sort=False).sort_index() pmf /= pmf.sum() return pmf ``` ## Cross tabulation To understand joint distributions, I'll start with cross tabulation. And to demonstrate cross tabulation, I'll generate a dataset of colors and fruits. Here are the possible values. ``` colors = ['red', 'yellow', 'green'] fruits = ['apple', 'banana', 'grape'] ``` And here's a random sample of 100 fruits. ``` np.random.seed(2) fruit_sample = np.random.choice(fruits, 100, replace=True) ``` We can use `pmf_from_seq` to compute the distribution of fruits. ``` pmf_fruit = pmf_from_seq(fruit_sample) pmf_fruit ``` And here's what it looks like. ``` pmf_fruit.plot.bar(color='C0') plt.ylabel('Probability') plt.title('Distribution of fruit'); ``` Similarly, here's a random sample of colors. ``` color_sample = np.random.choice(colors, 100, replace=True) ``` Here's the distribution of colors. ``` pmf_color = pmf_from_seq(color_sample) pmf_color ``` And here's what it looks like. ``` pmf_color.plot.bar(color='C1') plt.ylabel('Probability') plt.title('Distribution of colors'); ``` Looking at these distributions, we know the proportion of each fruit, ignoring color, and we know the proportion of each color, ignoring fruit type. But if we only have the distributions and not the original data, we don't know how many apples are green, for example, or how many yellow fruits are bananas. We can compute that information using `crosstab`, which computes the number of cases for each combination of fruit type and color. ``` xtab = pd.crosstab(color_sample, fruit_sample, rownames=['color'], colnames=['fruit']) xtab ``` The result is a DataFrame with colors along the rows and fruits along the columns. ## Heatmap The following function plots a cross tabulation using a pseudo-color plot, also known as a heatmap. It represents each element of the cross tabulation with a colored square, where the color corresponds to the magnitude of the element. The following function generates a heatmap using the Matplotlib function `pcolormesh`: ``` def plot_heatmap(xtab): """Make a heatmap to represent a cross tabulation. xtab: DataFrame containing a cross tabulation """ plt.pcolormesh(xtab) # label the y axis ys = xtab.index plt.ylabel(ys.name) locs = np.arange(len(ys)) + 0.5 plt.yticks(locs, ys) # label the x axis xs = xtab.columns plt.xlabel(xs.name) locs = np.arange(len(xs)) + 0.5 plt.xticks(locs, xs) plt.colorbar() plt.gca().invert_yaxis() plot_heatmap(xtab) ``` ## Joint Distribution A cross tabulation represents the "joint distribution" of two variables, which is a complete description of two distributions, including all of the conditional distributions. If we normalize `xtab` so the sum of the elements is 1, the result is a joint PMF: ``` joint = xtab / xtab.to_numpy().sum() joint ``` Each column in the joint PMF represents the conditional distribution of color for a given fruit. For example, we can select a column like this: ``` col = joint['apple'] col ``` If we normalize it, we get the conditional distribution of color for a given fruit. ``` col / col.sum() ``` Each row of the cross tabulation represents the conditional distribution of fruit for each color. If we select a row and normalize it, like this: ``` row = xtab.loc['red'] row / row.sum() ``` The result is the conditional distribution of fruit type for a given color. ## Conditional distributions The following function takes a joint PMF and computes conditional distributions: ``` def conditional(joint, name, value): """Compute a conditional distribution. joint: DataFrame representing a joint PMF name: string name of an axis value: value to condition on returns: Series representing a conditional PMF """ if joint.columns.name == name: cond = joint[value] elif joint.index.name == name: cond = joint.loc[value] return cond / cond.sum() ``` The second argument is a string that identifies which axis we want to select; in this example, `'fruit'` means we are selecting a column, like this: ``` conditional(joint, 'fruit', 'apple') ``` And `'color'` means we are selecting a row, like this: ``` conditional(joint, 'color', 'red') ``` **Exercise:** Compute the conditional distribution of color for bananas. What is the probability that a banana is yellow? ``` # Solution cond = conditional(joint, 'fruit', 'banana') cond # Solution cond['yellow'] ``` ## Marginal distributions Given a joint distribution, we can compute the unconditioned distribution of either variable. If we sum along the rows, which is axis 0, we get the distribution of fruit type, regardless of color. ``` joint.sum(axis=0) ``` If we sum along the columns, which is axis 1, we get the distribution of color, regardless of fruit type. ``` joint.sum(axis=1) ``` These distributions are called "[marginal](https://en.wikipedia.org/wiki/Marginal_distribution#Multivariate_distributions)" because of the way they are often displayed. We'll see an example later. As we did with conditional distributions, we can write a function that takes a joint distribution and computes the marginal distribution of a given variable: ``` def marginal(joint, name): """Compute a marginal distribution. joint: DataFrame representing a joint PMF name: string name of an axis returns: Series representing a marginal PMF """ if joint.columns.name == name: return joint.sum(axis=0) elif joint.index.name == name: return joint.sum(axis=1) ``` Here's the marginal distribution of fruit. ``` pmf_fruit = marginal(joint, 'fruit') pmf_fruit ``` And the marginal distribution of color: ``` pmf_color = marginal(joint, 'color') pmf_color ``` The sum of the marginal PMF is the same as the sum of the joint PMF, so if the joint PMF was normalized, the marginal PMF should be, too. ``` joint.to_numpy().sum() pmf_color.sum() ``` However, due to floating point error, the total might not be exactly 1. ``` pmf_fruit.sum() ``` **Exercise:** The following cells load the data from the General Social Survey that we used in Notebooks 1 and 2. ``` # Load the data file import os if not os.path.exists('gss_bayes.csv'): !wget https://github.com/AllenDowney/BiteSizeBayes/raw/master/gss_bayes.csv gss = pd.read_csv('gss_bayes.csv', index_col=0) ``` As an exercise, you can use this data to explore the joint distribution of two variables: * `partyid` encodes each respondent's political affiliation, that is, the party the belong to. [Here's the description](https://gssdataexplorer.norc.org/variables/141/vshow). * `polviews` encodes their political alignment on a spectrum from liberal to conservative. [Here's the description](https://gssdataexplorer.norc.org/variables/178/vshow). The values for `partyid` are ``` 0 Strong democrat 1 Not str democrat 2 Ind,near dem 3 Independent 4 Ind,near rep 5 Not str republican 6 Strong republican 7 Other party ``` The values for `polviews` are: ``` 1 Extremely liberal 2 Liberal 3 Slightly liberal 4 Moderate 5 Slightly conservative 6 Conservative 7 Extremely conservative ``` 1. Make a cross tabulation of `gss['partyid']` and `gss['polviews']` and normalize it to make a joint PMF. 2. Use `plot_heatmap` to display a heatmap of the joint distribution. What patterns do you notice? 3. Use `marginal` to compute the marginal distributions of `partyid` and `polviews`, and plot the results. 4. Use `conditional` to compute the conditional distribution of `partyid` for people who identify themselves as "Extremely conservative" (`polviews==7`). How many of them are "strong Republicans" (`partyid==6`)? 5. Use `conditional` to compute the conditional distribution of `polviews` for people who identify themselves as "Strong Democrat" (`partyid==0`). How many of them are "Extremely liberal" (`polviews==1`)? ``` # Solution xtab2 = pd.crosstab(gss['partyid'], gss['polviews']) joint2 = xtab2 / xtab2.to_numpy().sum() # Solution plot_heatmap(joint2) plt.xlabel('polviews') plt.title('Joint distribution of polviews and partyid'); # Solution marginal(joint2, 'polviews').plot.bar(color='C2') plt.ylabel('Probability') plt.title('Distribution of polviews'); # Solution marginal(joint2, 'polviews').plot.bar(color='C3') plt.ylabel('Probability') plt.title('Distribution of polviews'); # Solution cond1 = conditional(joint2, 'polviews', 7) cond1.plot.bar(label='Extremely conservative', color='C4') plt.ylabel('Probability') plt.title('Distribution of partyid') cond1[6] # Solution cond2 = conditional(joint2, 'partyid', 0) cond2.plot.bar(label='Strong democrat', color='C6') plt.ylabel('Probability') plt.title('Distribution of polviews') cond2[1] ``` ## Review In this notebook we started with cross tabulation, which we normalized to create a joint distribution, which describes the distribution of two (or more) variables and all of their conditional distributions. We used heatmaps to visualize cross tabulations and joint distributions. Then we defined `conditional` and `marginal` functions that take a joint distribution and compute conditional and marginal distributions for each variables. As an exercise, you had a chance to apply the same methods to explore the relationship between political alignment and party affiliation using data from the General Social Survey. You might have noticed that we did not use Bayes's Theorem in this notebook. [In the next notebook](https://colab.research.google.com/github/AllenDowney/BiteSizeBayes/blob/master/11_faceoff.ipynb) we'll take the ideas from this notebook and apply them Bayesian inference.
github_jupyter
# KNN Here we use K Nearest Neighbors algorithm to perform classification and regression ``` import numpy as np import matplotlib.pyplot as plt import sys import pandas as pd from sklearn.metrics import mean_squared_error from sklearn.model_selection import train_test_split from rdkit import Chem, DataStructs from sklearn.neighbors import KNeighborsRegressor, KNeighborsClassifier from tqdm.notebook import tqdm ``` ## Load Data ``` # training data: assays = pd.read_pickle('../processed_data/combined_dataset.pkl') assays = assays[assays.activity_target.isin(['Active', 'Inactive'])] # get rid of any 'Inconclusive' assays = assays.dropna(subset=['acvalue_scaled_to_tmprss2']) # only use data that could be scaled dcm = pd.read_pickle('../processed_data/DarkChemicalMatter_processed.pkl.gz') # testing data: screening_data = pd.read_pickle('../processed_data/screening_data_processed.pkl') ``` # Classification ## Load training data ``` # set up features (X) and labels (y) for knn X_assays = np.stack(assays.morgan_fingerprint) y_assays = assays.activity_target.values assays_hist = plt.hist(y_assays) X_dcm = np.stack(dcm.sample(frac=.1).morgan_fingerprint) y_dcm = ['Inactive'] * len(X_dcm) dcm_hist = plt.hist(y_dcm) ``` ### Validation ``` # make a validation set out of some of the assays and some of the dcm percent_test_assays = .3 # Make the val set a bit less skewed than the train set percent_test_dcm = .1 # random_state = 3 # for reproducibility of train/val split train_X_assays, val_X_assays, train_y_assays, test_y_assays = train_test_split(X_assays, y_assays, test_size=percent_test_assays, random_state=random_state) train_X_dcm, val_X_dcm, train_y_dcm, test_y_dcm = train_test_split(X_dcm, y_dcm, test_size=percent_test_dcm, random_state=random_state) plt.figure() plt.bar(['assays', 'dcm'], [len(train_X_assays), len(train_X_dcm)]) plt.title('training data') plt.figure() plt.bar(['assays', 'dcm'], [len(val_X_assays), len(val_X_dcm)]) plt.title('val data') train_X = np.concatenate([train_X_assays, train_X_dcm], axis=0) val_X = np.concatenate([val_X_assays, val_X_dcm], axis=0) train_y = np.concatenate([train_y_assays, train_y_dcm], axis=0) test_y = np.concatenate([test_y_assays, test_y_dcm], axis=0) ``` ## Optimize KNN Classifier using Validation Data ``` # optimize knn, test a couple ks ks = np.arange(1, 14, 2) accuracies = [] active_accuracies = [] inactive_accuracies = [] for k in tqdm(ks): nbrs = KNeighborsClassifier(n_neighbors=k, metric='jaccard', algorithm='ball_tree', n_jobs=32) nbrs.fit(train_X, train_y) pred = nbrs.predict(val_X) accuracies.append(np.count_nonzero(pred == test_y) / len(test_y)) if np.count_nonzero(test_y == 'Inactive') == 0: inactive_accuracies.append(1) # all inactive classified correctly: vacuously true else: inactive_accuracies.append(np.count_nonzero((pred == test_y) & (pred == 'Inactive')) / np.count_nonzero(test_y == 'Inactive')) if np.count_nonzero(test_y == 'Active') == 0: active_accuracies.append(1) else: active_accuracies.append(np.count_nonzero((pred == test_y) & (test_y == 'Active')) / np.count_nonzero(test_y == 'Active')) plt.figure() plt.plot(ks, accuracies, label='overall') plt.plot(ks, active_accuracies, label='active') plt.plot(ks, inactive_accuracies, label='inactive') plt.xlabel("k") plt.ylabel("accuracy") plt.title('Classification Accuracy') plt.legend() ``` From the above experiment, we can see that k=5 does the best on active compounds; we'll choose this. ## Test on the Screening Data ``` # set up train and test X_train = np.concatenate([X_assays, X_dcm]) y_train = np.concatenate([y_assays, y_dcm]) X_test = np.stack(screening_data.morgan_fingerprint) print("Training set size:", len(X_train)) print("Test set size:", len(X_test)) nbrs = KNeighborsClassifier(n_neighbors=3, metric='jaccard', algorithm='ball_tree', weights='distance', n_jobs=32) # turns out it gets much faster with many jobs (even 8x more jobs than my laptop's 4 physical cores). 64 is slower than 32 though, overhead catches up I guess. nbrs.fit(train_X, train_y) # chunk the test set in order to get some sense of progress pred_activity = [] for test_chunk in tqdm(np.array_split(X_test, 100)): pred_activity.append(nbrs.predict(test_chunk)) pred_activity = np.concatenate(pred_activity) fig, ax = plt.subplots(1, 2, figsize=(8, 3)) ax[0].hist(y_train) ax[0].set_title('training labels') ax[1].hist(pred_activity) ax[1].set_title('predicted labels') t = plt.suptitle('Label Distributions') ``` We can see the screening data mostly comes back as inactive. The distribution is similar to the training distribution, which could mean the model is biased by the training distribution, but this isn't necessarily true. Could use a test with different training data distribution to see. # Regression Now that we have identified active compounds out of the screening data, we can regress the activity of these compounds using our assay data. ## Validation ### Load Train Data Features are still morgan fingerprints, labels are log activity values. Where available, the activity values are scaled to tmprss2 based on correlation between target activities. Where correlation was unavailable, activity values are unscaled. ``` X_assays = np.stack(assays.morgan_fingerprint) y_assays = np.log10(assays.acvalue_scaled_to_tmprss2) assert y_assays.isna().sum() == 0 ``` ### Regression Cross-Validation ``` from sklearn.model_selection import cross_val_score ks = np.arange(1, 23, 2) RMSE = [] for k in tqdm(ks): knn_cv = KNeighborsRegressor(n_neighbors=k, metric='jaccard', weights='distance') RMSE.append(-cross_val_score(knn_cv, X_assays, y_assays, cv=10, scoring='neg_root_mean_squared_error')) plt.plot(ks, RMSE, '.') plt.plot(ks, np.median(RMSE, axis=1), label='median') plt.plot(ks, np.mean(RMSE, axis=1), label='mean') plt.xticks(ks) plt.legend() plt.ylabel('RMSE') plt.xlabel('k') plt.title('10-fold Cross Validation') ``` From the cross-validation, it seems k=7 is a reasonable choice. ``` from sklearn.metrics import mean_squared_error best_k_regr = 7 best_RMSE = np.median(RMSE, axis=1)[3] X_train, X_test, y_train, y_test = train_test_split(X_assays, y_assays, test_size=.25, random_state=1) nbrs = KNeighborsRegressor(n_neighbors=best_k_regr, metric='jaccard', weights='distance') nbrs.fit(X_train, y_train) y_pred = nbrs.predict(X_test) plt.plot(y_test, y_pred, '.') plt.xlabel('True Activity Values (log)') plt.ylabel('Predicted Activity Values (log)') bnds = [np.min([y_test, y_pred])*1.1, np.max([y_test, y_pred])*1.2] plt.axis('square') plt.xlim(bnds) plt.ylim(bnds) plt.plot(np.linspace(*bnds), np.linspace(*bnds), 'k--', label='y=x') plt.legend() plt.title('Sample Validation (3/4 train, 1/4 test)') print(f'RMSE={mean_squared_error(y_test, y_pred, squared=False)}') ``` Here you can see that the distribution as a whole looks good, but the accuracy in the low-end is poor. Since we care about the low end, this is concerning. ### Load Test Data The test data consists of all the screening molecules which were marked 'active' in classification above. ``` active_screening_data = screening_data[pred_activity=='Active'].copy() X_test_active = np.stack(active_screening_data.morgan_fingerprint) nbrs = KNeighborsRegressor(n_neighbors=best_k_regr, metric='jaccard', weights='distance') nbrs.fit(X_assays, y_assays) pred_acvalue = nbrs.predict(X_test_active) active_screening_data.insert(loc=2, column='predicted_acvalue(log10)', value=pred_acvalue) # a look at the predicted activity distributions by dataset source: from seaborn import violinplot violinplot(x='source', y='predicted_acvalue(log10)', data=active_screening_data) # and the top hits! active_screening_data.sort_values(by='predicted_acvalue(log10)', inplace=True) active_screening_data['name'] = active_screening_data.name.str.upper() active_screening_data.drop(columns=['morgan_fingerprint'], inplace=True) active_screening_data.drop_duplicates(subset=['name'], inplace=True) active_screening_data.head(20) ``` Nafamostat comes in on top, which is reassuring. The rest of the results... unclear. Not a ton of trust in the KNN, the large errors in the low-end on the regression test is concerning. ``` # store the results! active_screening_data['RMSE'] = best_RMSE active_screening_data.to_csv('../results/knn_results.csv') ```
github_jupyter
# Dispersion relations in a micropolar medium We are interested in computing the dispersion relations in a homogeneous micropolar solid. ## Wave propagation in micropolar solids The equations of motion for a micropolar solid are given by [[1, 2]](#References) \begin{align} &c_1^2 \nabla\nabla\cdot\mathbf{u}- c_2^2\nabla\times\nabla\times\mathbf{u} + K^2\nabla\times\boldsymbol{\theta} = -\omega^2 \mathbf{u} \, ,\\ &c_3^2 \nabla\nabla\cdot\boldsymbol{\theta} - c_4^2\nabla\times\nabla\times\boldsymbol{\theta} + Q^2\nabla\times\mathbf{u} - 2Q^2\boldsymbol{\theta} = -\omega^2 \boldsymbol{\theta} \, \end{align} where $\mathbf{u}$ is the displacement vector and $\boldsymbol{\theta}$ is the microrrotations vector, and where: $c_1$ represents the phase/group speed for the longitudinal wave ($P$) that is non-dispersive as in the classical case, $c_2$ represents the high-frequency limit phase/group speed for a transverse wave ($S$) that is dispersive unlike the classical counterpart, $c_3$ represents the high-frequency limit phase/group speed for a longitudinal-rotational wave ($LR$) with a corkscrew-like motion that is dispersive and does not have a classical counterpart, $c_4$ represents the high-frequency limit phase/group speed for a transverse-rotational wave ($TR$) that is dispersive and does not have a classical counterpart, $Q$ represents the cut-off frequency for rotational waves appearance, and $K$ quantifies the difference between the low-frequency and high-frequency phase/group speed for the S-wave. These parameters are defined by: \begin{align} c_1^2 = \frac{\lambda +2\mu}{\rho},\quad &c_3^2 =\frac{\beta + 2\eta}{J},\\ c_2^2 = \frac{\mu +\alpha}{\rho},\quad &c_4^2 =\frac{\eta + \varepsilon}{J},\\ Q^2= \frac{2\alpha}{J},\quad &K^2 =\frac{2\alpha}{\rho} \, , \end{align} ## Dispersion relations To identify types of propagating waves that can arise in the micropolar medium it is convenient to expand the displacement and rotation vectors in terms of scalar and vector potentials \begin{align} \mathbf{u} &= \nabla \phi + \nabla\times\boldsymbol{\Gamma}\, ,\\ \boldsymbol{\theta} &= \nabla \tau + \nabla\times\mathbf{E}\, , \end{align} subject to the conditions: \begin{align} &\nabla\cdot\boldsymbol{\Gamma} = 0\\ &\nabla\cdot\mathbf{E} = 0\, . \end{align} Using the above in the displacements equations of motion yields the following equations, after some manipulations \begin{align} c_1^2 \nabla^2 \phi &= \frac{\partial^2 \phi}{\partial t^2}\, ,\\ c_3^2 \nabla^2 \tau - 2Q^2\tau &= \frac{\partial^2 \tau}{\partial t^2}\, ,\\ \begin{bmatrix} c_2^2 \nabla^2 &K^2\nabla\times\, ,\\ Q^2\nabla\times &c_4^2\nabla^2 - 2Q^2 \end{bmatrix} \begin{Bmatrix} \boldsymbol{\Gamma}\\ \mathbf{E}\end{Bmatrix} &= \frac{\partial^2}{\partial t^2} \begin{Bmatrix} \boldsymbol{\Gamma}\\ \mathbf{E}\end{Bmatrix} \, , \end{align} where we can see that the equations for the scalar potentials are uncoupled, while the ones for the vector potentials are coupled. Writing the vector potentials as plane waves of amplitude $ \mathbf{A}$ and $ \mathbf{B}$, wave number $\kappa$ and circular frequency $\omega$ that propagate along the \(x\) axis, \begin{align} \boldsymbol{\Gamma} &= \mathbf{A}\exp(i\kappa x - i\omega t)\\ \mathbf{E} &= \mathbf{B}\exp(i\kappa x - i\omega t)\, . \end{align} We can do these calculations using some the functions available functions in the package. ``` from sympy import Matrix, diff, symbols, exp, I, sqrt from sympy import simplify, expand, solve, limit from sympy import init_printing, pprint, factor from continuum_mechanics.vector import lap_vec, curl, div init_printing() A1, A2, A3, B1, B2, B3 = symbols("A1 A2 A3 B1 B2 B3") kappa, omega, t, x = symbols("kappa omega t x") c1, c2, c3, c4, K, Q = symbols("c1 c2 c3 c4 K Q", positive=True) ``` We define the vector potentials $\boldsymbol{\Gamma}$ and $\mathbf{E}$. ``` Gamma = Matrix([A1, A2, A3]) * exp(I*kappa*x - I*omega*t) E = Matrix([B1, B2, B3]) * exp(I*kappa*x - I*omega*t) ``` And compute the equations using the vector operators. Namely, the Laplace ([`vector.lap_vec()`](https://continuum-mechanics.readthedocs.io/en/latest/modules.html#vector.lap_vec) and the curl ([`vector.curl()`](https://continuum-mechanics.readthedocs.io/en/latest/modules.html#vector.curl)) operators. ``` eq1 = c2**2 * lap_vec(Gamma) + K**2*curl(E) - Gamma.diff(t, 2) eq2 = Q**2 * curl(Gamma) + c4**2*lap_vec(E) - 2*Q**2*E - E.diff(t, 2) eq1 = simplify(eq1/exp(I*kappa*x - I*omega*t)) eq2 = simplify(eq2/exp(I*kappa*x - I*omega*t)) eq = eq1.col_join(eq2) ``` We can compute the matrix for the system using [`.jacobian()`](https://docs.sympy.org/1.5.1/modules/matrices/matrices.html#sympy.matrices.matrices.MatrixCalculus.jacobian) ``` M = eq.jacobian([A1, A2, A3, B1, B2, B3]) M ``` And, we are interested in the determinant of the matrix $M$. ``` factor(M.det()) ``` The roots for this polynomial (in $\omega^2$) represent the dispersion relations. ``` disps = solve(M.det(), omega**2) for disp in disps: display(disp) ``` ## References 1. Nowacki, W. (1986). Theory of asymmetric elasticity. Pergamon Press, Headington Hill Hall, Oxford OX 3 0 BW, UK, 1986. 2. Guarín-Zapata, N., Gomez, J., Valencia, C., Dargush, G. F., & Hadjesfandiari, A. R. (2020). Finite element modeling of micropolar-based phononic crystals. Wave Motion, 92, 102406.
github_jupyter
#### A multiclass classification problem by Aries P. Valeriano and Dave Emmanuel Q. Magno ## Executive Summary The goal of this project is to a build a prediction model that make use of stock chart pattern, in particular double top to predict the next movement of stock price if it will decrease further, increase, or stay still within the next 10 days. If successful, traders can use this prediction model to make a data driven decision on their next trade. To achieve this goal, we will create our own dataset first. This can be done by determining the minima and maxima of the time series dataset for every stock from various industry. Then, we will refer to it to detect the double top stock chart pattern. There are 5 points/prices that consists of maxima and minima that forms the pattern, these will become the descriptive features that we will use to predict the target feature which is the movement of stock price within the next 10 days. We also include the indexes of the start and end of the pattern, as well as the industry of the stocks where the pattern occurs. Now that we have the dataset. We will perform data exploration to visualize the double top pattern and verify the multicollinearity of the descriptive features because obviously they are correlated to each other since each are part of double top pattern. Moreover, we performed also feature engineer to get additional features that could help increase the predictive accuracy of the model. After data exploration, we proceed to predictive modelling. Note that the target feature consists of 3 levels. Thus, we will fit multiclass models to our dataset such as multiclass KNN, multinomial logistic regression, multiclass SVM etc.. Fortunately, this can be done simultaneously by using pycaret machine learning library, moreover it automatically split the dataset which we set to 80/20, and further perform data exploration such as normalization, in which we set it as minmax scaler, one hat encoding for nominal feature (industry). And as a result, the model the produces the highest F1 score is the gradient boosting classifier, a sequential ensemble approach with 0.5217 score. This imply that with 52.17% accuracy, we can predict the movement of stocks prices within 10 days after the double top stock chart pattern happen. ## Jupyter Display Settings ``` %%javascript IPython.OutputArea.prototype._should_scroll = function(lines) { return false; } from IPython.core.display import HTML HTML(""" <style> .output_png { display: table-cell; text-align: center; vertical-align: middle; } </style> """) ``` ## Prerequisites ``` from collections import Counter from typing import Union from itertools import combinations from pycaret.classification import * from sklearn.datasets import dump_svmlight_file from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import RepeatedKFold, train_test_split from sklearn.metrics import precision_score from imblearn.under_sampling import NearMiss import xgboost as xgb from xgboost import XGBClassifier import pandas as pd from dfply import * import plotly.express as px import matplotlib.pyplot as plt import seaborn as sns sns.set() %matplotlib inline from price_detection_tools import import_ ``` ## Tools ``` @dfpipe def extract_date(df_: pd.DataFrame) -> pd.DataFrame: df = df_.copy(deep=True) for i, col_name in zip(range(2), ['dateF', 'dateE']): df[col_name] = df.date.apply(lambda x: x[i]) return df @dfpipe def drop_(df_: pd.DataFrame) -> pd.DataFrame: to_drop = ['fw_ret_1', 'fw_ret_2', 'fw_ret_3'] return df_.drop([to_drop]) @dfpipe def get_average(df_: pd.DataFrame) -> pd.DataFrame: df = df_.copy(deep=True) f1_idx = df.columns.get_loc('f1') f5_idx = df.columns.get_loc('f5') averages = df.iloc[:, f1_idx:f5_idx + 1].mean(axis=1) averages.rename('averages', inplace=True) return pd.concat([df_, averages], axis=1) def lump_categories(data: Union[pd.DataFrame, pd.Series], percentage: float = 0.010): def set_threshold(df: pd.DataFrame, percentage: float = 0.010) -> float: """Sets threshold to be a percentage of the shape of dataframe.""" return df.shape[0] * percentage if isinstance(data, pd.DataFrame): pass if isinstance(data, pd.Series): data = data.to_frame() return data.apply(lambda x: x.mask( x.map(x.value_counts()) < set_threshold(df_copy), 'Others')) def encode_label(series: pd.Series): label_encoder = LabelEncoder() label_encoder.fit(series) return label_encoder.transform(series) def get_height(fA_: pd.Series, fB_: pd.Series) -> pd.DataFrame: return np.abs(fA_ - fB_) @dfpipe def add_height_features(df_: pd.DataFrame) -> pd.DataFrame: df = df_.copy(deep=True) heights = ['h{}'.format(i + 1) for i in range(10)] feats = ['f{}'.format(i + 1) for i in range(5)] for height, comb in zip(heights, combinations(feats, 2)): df[height] = get_height(df[comb[0]], df[comb[1]]) return df ``` ## Data Description It contains a target feature (label) that have 3 levels, decrease "1", neutral "2", increase "3" and 8 descriptive features in which 5 of it (f1, f2, f3, f4, f5) consist of minima and maxima that forms a double top stock chart pattern, 2 of it (dateF, dateE) are the indexes of the start and end of the pattern lastly, industry of the stock where the pattern occur. However, before arriving at this dataset, web scraping of stocks historical dataset for various industries at https://finance.yahoo.com/ are performed, see above table, then closing price from it was utilize. Moreover, minima and maxima of time series dataset for every stock were determined. Next, detection of double top stock chart pattern by setting threshold for the minima and maxima that forms the pattern, and lastly, determine its corresponding target feature by comparing the highest maxima or lowest minima within the pattern and the maximum or minimum prices within the next 10 days after the pattern is observed. Target is labeled increase "2" if the maximum price within the next 10 days is greater than the highest maxima within the pattern, decrease "0" if the minimum price within the next 10 days is lesser than the lowest minima within the pattern, neutral "0" if neither or both happens. ## Data Exploration and Preprocessing In here, we have done feature engineer. Created 3 additional descriptive features, which are the the absolute difference between f1 and f3 , also between f3 and f5, then we took the sum of the values from f1 to f5. These features were named d1, d2, and sum respectively. These additional features will help increase the predictive accuracy of the model built later on. ``` df = import_('trial.csv').drop(['increment', 'ema', 'window'], axis=1) df_copy = df.copy(deep=True) ``` #### Label encoding of 'industry' #### Lump categories ``` df_copy['industry_lumped'] = lump_categories(df_copy['industry']) df_copy = df_copy.drop('industry', axis=1) df_copy['industry_coded'] = encode_label(df_copy['industry_lumped']) df_copy = df_copy.drop('industry_lumped', axis=1) data = (df_copy >> extract_date >> drop(['date']) >> drop(['fw_ret_1', 'fw_ret_2', 'fw_ret_3']) >> add_height_features) ``` #### Get the size or width of the whole pattern ``` data['pattern_width'] = np.abs(data.dateF - data.dateE) data['w1'] = get_height(data.idx1, data.idx3) data['w2'] = get_height(data.idx3, data.idx5) data['w3'] = get_height(data.idx2, data.idx4) indices = ['idx1', 'idx2', 'idx3', 'idx4', 'idx5'] data = data.drop(indices, axis=1) ``` #### Data validation Drop values with 0 widths, invalid pattern. ``` data = data[data.w1 != 0] data = data[data.w2 != 0] data = data[data.w3 != 0] ``` #### Drop 'dateF' and 'dateE' after getting pattern width ``` data = data.drop(['dateF', 'dateE'], axis=1) Counter(data.label) undersample = NearMiss(version=3) def undersample_(X: pd.DataFrame, y: pd.Series, version: int = 1): undersample = NearMiss(version=version) return undersample.fit_resample(X, y) X, y = undersample_(data.drop('label', axis=1), data['label']) Counter(y) ``` #### Change the coding of the label ``` X, y = data.drop('label', axis=1), data['label'] mapping = {1: 0, 2: 1, 3: 2} y = y.replace(mapping) to_filter = ['f1', 'f2', 'f3', 'f4', 'f5', 'industry_coded', 'pattern_width', 'h1', 'h2', 'h4', 'h6', 'h9', 'w1', 'w2', 'w3'] X = X[to_filter] to_corr = ['w1', 'w2', 'w3', 'pattern_width', 'f1', 'h1', 'h2', 'h4', 'h6', 'h9'] fig=plt.figure(figsize=(12,10), dpi= 100) sns.heatmap(X[to_corr].corr(method='spearman'), annot=True) plt.show() ``` ## Model selection The dataset we have consists of quantitative features and a single categorical feature which is the target feature. The target feature contains multiple levels. Therefore, we will fit several models that are multiclass to our dataset, in particular multiclass KNN, multinomial logistic regression, multiclass SVM etc. to find the best predictive model of this project. Fortunately, we can fit these models to our dataset simultaneously using pycaret machine learning library. Moreover, pycaret also automatically normalized then splits dataset if specified, do one hat encoding for nominal features, perform cross validation, tuned hyperparameter for every model etc.. In our case, we specify the normalization method as minmax scaler then split it to 80% training set and 20% testing set, then let it perform 5 fold cross validation with 10 repetition. ``` data = pd.concat([X, y], axis=1) cv = RepeatedKFold(n_splits=5, n_repeats=10, random_state=13) exp_name = setup(data=data, target='label', normalize=True, normalize_method='minmax', train_size=0.8, data_split_stratify=True, fold_strategy=cv, remove_outliers=True, use_gpu=True, session_id=13, pca=True, pca_method='linear') best_model = compare_models() get_config('X') ``` Since this project aims to predict stock prices given double top stock chart pattern for trading purposes. Both false negative and false positive are crucial. That is, in the case of false negative, if we predict a decrease in price after the pattern then decided to sale the stocks because we won't get any more profit however, it actually increases, then we just lose the opportunity to earn more. On the other hand, in the case of false positive, if we predict an increase in price after the pattern then decided to buy stocks so we can sale it during the increase however, it actually decreases, then we just lose some money. Also, the target feature has imbalanced classes. Therefore, we will emphasize the F1 score over accuracy and any other performance metrics for this project to measure the predictive power of the model built. The above output shows the list of predictive performance for several models after we fit it to our data. Notice that the model that produces the highest F1 score is the Gradient descent classifier, a sequential ensemble approach, with 0.5217 score. This imply that the model we built can predict the target feature given f1, f2, f3, f4, f5, dateF, dateE, and industry with 52.17% accuracy. Moreover, we will further interpret other performance metrics but this is just for better understanding of the predictive model performance. After all, we already interpreted F1 score, the appropriate performance metric for this project. Now, notice that the model that produces the highest accuracy is still Gradient boosting classifier with value 0.5616, followed by Ada boost classifier with value 0.5579, both are sequential ensemble approach. These implies that the models we built can predict the target feature given f1, f2, f3, f4, f5, dateF, dateE, and industry with 56.16% and 55.79% accuracy respectively. Ada Boost Classifier also produces the highest Precision with value 0.5210. This suggest that for the number of predictions that the model made, 52.19% of it are correct. Whereas, Gradient boosting classifier produces the highest AUC and Recall (Sensitivity) with values 0.6750 and 0.4883 respectively. AUC value suggest that the model have 67.50% accuracy to predict the target feature that will or will not occur. And recall value imply that, for the target feature that should occur, we predicted 48.83% of it. ## Tuned hyperparameters ``` best_model plot_model(best_model, plot='confusion_matrix') plot_model(best_model) plot_model(best_model, plot='class_report') plot_model(best_model, plot='pr') plot_model(best_model, plot='boundary') plot_model(best_model, plot='learning') ``` ## Evaluate predictive accuracy of the model built ``` test_scores = predict_model(best_model) test_scores test_scores.Score.mean() ``` The predictive model built when use for test set, gives us a predictive accuracy of 62.40%. This suggest that we predicted the movement of stock prices given new quiries of double top stock chart pattern (test set) with 62.40% accuracy. ## Conclusion and Recommendation The dataset created consists of target feature with 3 levels (decrease/1, neutral/2, increase/3) and 7 descriptive features, in which 5 of them (f1, f2, f3, f4, f5) forms a double stock chart pattern and the other two are indexes of the start and end of the pattern. After we tried to fit several multiclass models on this dataset, we found out that its accuracy is less than 50%. Thus, we performed feature engineer by taking the absolute difference between f1 and f3, f3 and f5, and get the average from f1 to f5. These 3 additional descriptive features actually helped the predictive model we built to increase its accuracy from below 50% to a little bit higher than 50%. The predictive model that produces this result is the gradient boosting classifier, a sequential ensemble approach that gives an F1 score of 0.5217. This only imply that the predictive model built can predict the movement of the stock prices given double top stock chart pattern with 52.17% accuracy. Furthermore, when model performance was evaluated with the test set, it produces a 62.40% predictive accuracy. ## References * https://medium.com/analytics-vidhya/accuracy-vs-f1-score-6258237beca2 * https://pycaret.org/classification/ * https://finance.yahoo.com/
github_jupyter
# Classifying Fashion-MNIST Now it's your turn to build and train a neural network. You'll be using the [Fashion-MNIST dataset](https://github.com/zalandoresearch/fashion-mnist), a drop-in replacement for the MNIST dataset. MNIST is actually quite trivial with neural networks where you can easily achieve better than 97% accuracy. Fashion-MNIST is a set of 28x28 greyscale images of clothes. It's more complex than MNIST, so it's a better representation of the actual performance of your network, and a better representation of datasets you'll use in the real world. <img src='assets/fashion-mnist-sprite.png' width=500px> In this notebook, you'll build your own neural network. For the most part, you could just copy and paste the code from Part 3, but you wouldn't be learning. It's important for you to write the code yourself and get it to work. Feel free to consult the previous notebooks though as you work through this. First off, let's load the dataset through torchvision. ``` import torch from torchvision import datasets, transforms import helper # Define a transform to normalize the data transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 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 we can see one of the images. ``` image, label = next(iter(trainloader)) helper.imshow(image[0,:]); ``` ## Building the network Here you should define your network. As with MNIST, each image is 28x28 which is a total of 784 pixels, and there are 10 classes. You should include at least one hidden layer. We suggest you use ReLU activations for the layers and to return the logits or log-softmax from the forward pass. It's up to you how many layers you add and the size of those layers. ``` # TODO: Define your network architecture here from torch import nn from torch import optim model = nn.Sequential(nn.Linear(784,500), nn.ReLU(), nn.Linear(500,350), nn.ReLU(), nn.Linear(350,200), nn.ReLU(), nn.Linear(200,100), nn.ReLU(), nn.Linear(100,10), nn.LogSoftmax(dim = 1)) criterion = nn.NLLLoss() optimizer = optim.Adam(model.parameters(), lr = 0.003) ``` # Train the network Now you should create your network and train it. First you'll want to define [the criterion](http://pytorch.org/docs/master/nn.html#loss-functions) ( something like `nn.CrossEntropyLoss`) and [the optimizer](http://pytorch.org/docs/master/optim.html) (typically `optim.SGD` or `optim.Adam`). Then write the training code. Remember the training pass is a fairly straightforward process: * Make a forward pass through the network to get the logits * Use the logits to calculate the loss * Perform a backward pass through the network with `loss.backward()` to calculate the gradients * Take a step with the optimizer to update the weights By adjusting the hyperparameters (hidden units, learning rate, etc), you should be able to get the training loss below 0.4. ``` # TODO: Create the network, define the criterion and optimizer # TODO: Train the network here epoch = 5 for x in range(epoch): cumulative_loss = 0 for images, labels in trainloader: optimizer.zero_grad() images = images.view(images.shape[0],-1) output = model(images) loss = criterion(output, labels) cumulative_loss = cumulative_loss + loss loss.backward() optimizer.step() else: print(f"Training loss: {cumulative_loss/len(trainloader)}") %matplotlib inline %config InlineBackend.figure_format = 'retina' import helper # Test out your network! dataiter = iter(testloader) images, labels = dataiter.next() img = images[0] # Convert 2D image to 1D vector img = img.resize_(1, 784) # TODO: Calculate the class probabilities (softmax) for img with torch.no_grad(): logps = model(img) ps = torch.exp(logps) # Plot the image and probabilities helper.view_classify(img.resize_(1, 28, 28), ps, version='Fashion') ```
github_jupyter
``` %matplotlib inline from __future__ import print_function from __future__ import division import os import pandas as pd import numpy as np from tqdm import tqdm_notebook from matplotlib import pyplot as plt from matplotlib.colors import rgb2hex import seaborn as sns import statsmodels.api as sm # let's not pollute this blog post with warnings from warnings import filterwarnings filterwarnings('ignore') observations = pd.read_csv(os.path.join('data', 'training_set_observations.csv'), index_col=0) observations.head() observations.columns observations.describe() corr = observations.select_dtypes(include = ['float64', 'int64']).iloc[:, 1:].corr() plt.figure(figsize=(12, 12)) sns.heatmap(corr, vmax=1, square=True) print( "We have {} penguin observations from {} to {} at {} unique sites in the Antarctic!" \ .format(observations.shape[0], observations.season_starting.min(), observations.season_starting.max(), observations.site_id.nunique()) ) # How many observations do we have for each species? observations.common_name.value_counts() # How many differnet sites do we see each species at? (observations.groupby("common_name") .site_id .nunique()) # How many count types do we have for each species? (observations.groupby("common_name") .count_type .value_counts()) nest_counts = pd.read_csv( os.path.join('data', 'training_set_nest_counts.csv'), index_col=[0,1] ) # Let's look at the first 10 rows, and the last 10 columns nest_counts.iloc[:10, -10:] # get a sort order for the sites with the most observations sorted_idx = (pd.notnull(nest_counts) .sum(axis=1) .sort_values(ascending=False) .index) # get the top 25 most common sites and divide by the per-series mean to_plot = nest_counts.loc[sorted_idx].head(25) to_plot = to_plot.divide(to_plot.mean(axis=1), axis=0) # plot the data plt.gca().matshow(to_plot, cmap='viridis') plt.show() def preprocess_timeseries(timeseries, first_year, fillna_value=0): """ Takes one of the timeseries dataframes, removes columns before `first_year`, and fills NaN values with the preceeding value. Then backfills any remaining NaNs. As a courtesy, also turns year column name into integers for easy comparisons. """ # column type timeseries.columns = timeseries.columns.astype(int) # subset to just data after first_year timeseries = timeseries.loc[:, timeseries.columns >= first_year] # Forward fill count values. This is a strong assumption. timeseries.fillna(method="ffill", axis=1, inplace=True) timeseries.fillna(method="bfill", axis=1, inplace=True) # For sites with no observations, fill with fill_na_value timeseries.fillna(fillna_value, inplace=True) return timeseries nest_counts = preprocess_timeseries(nest_counts, 1980, fillna_value=0.0) nest_counts.head() # get the top 25 most common sites and divide by the per-series mean to_plot = nest_counts.loc[sorted_idx].head(25) to_plot = to_plot.divide(to_plot.mean(axis=1), axis=0) plt.gca().matshow(to_plot, cmap='viridis') plt.show() e_n_values = pd.read_csv( os.path.join('data', 'training_set_e_n.csv'), index_col=[0,1] ) # Process error data to match our nest_counts data e_n_values = preprocess_timeseries(e_n_values, 1980, fillna_value=0.05) e_n_values.head() def amape(y_true, y_pred, accuracies): """ Adjusted MAPE """ not_nan_mask = ~np.isnan(y_true) # calculate absolute error abs_error = (np.abs(y_true[not_nan_mask] - y_pred[not_nan_mask])) # calculate the percent error (replacing 0 with 1 # in order to avoid divide-by-zero errors). pct_error = abs_error / np.maximum(1, y_true[not_nan_mask]) # adjust error by count accuracies adj_error = pct_error / accuracies[not_nan_mask] # return the mean as a percentage return np.mean(adj_error) # Let's confirm the best possible score is 0! amape(nest_counts.values, nest_counts.values, e_n_values.values) from sklearn.linear_model import LinearRegression from sklearn.isotonic import IsotonicRegression from sklearn.tree import DecisionTreeRegressor def train_model_per_row(ts, acc, split_year=2010): # Split into train/test to tune our parameter train = ts.iloc[ts.index < split_year] test = ts.iloc[ts.index >= split_year] test_acc = acc.iloc[acc.index >= split_year] # Store best lag parameter best_mape = np.inf best_lag = None # Test linear regression models with the most recent # 2 points through using all of the points for lag in range(2, train.shape[0]): # fit the model temp_model = LinearRegression() #temp_model = DecisionTreeRegressor(max_depth=4) temp_model.fit( train.index[-lag:].values.reshape(-1, 1), train[-lag:] ) # make our predictions on the test set preds = temp_model.predict( test.index.values.reshape(-1, 1) ) # calculate the score using the custom metric mape = amape(test.values, preds, test_acc.values) # if it's the best score yet, hold on to the parameter if mape < best_mape: best_mape = mape best_lag = lag # return model re-trained on entire dataset final_model = LinearRegression() #final_model = DecisionTreeRegressor(max_depth=4) final_model.fit( ts.index[-best_lag:].values.reshape(-1, 1), ts[-best_lag:] ) return final_model, best_mape ,best_lag models = {} avg_Best_Mape = 0.0 avg_best_lag = 0.0 iteration = 0 for i, row in tqdm_notebook(nest_counts.iterrows(), total=nest_counts.shape[0]): acc = e_n_values.loc[i] models[i], best_mape, best_lag = train_model_per_row(row, acc) avg_Best_Mape = avg_Best_Mape + best_mape avg_best_lag = avg_best_lag + best_lag iteration = iteration + 1 avg_Best_Mape = avg_Best_Mape / iteration avg_best_lag = avg_best_lag / iteration print("Avg Best Mape : {0}".format(avg_Best_Mape)) print("Avg Best Lag : {0}".format(avg_best_lag)) submission_format = pd.read_csv( os.path.join('data','submission_format.csv'), index_col=[0, 1] ) print(submission_format.shape) submission_format.head() preds = [] # For every row in the submission file for i, row in tqdm_notebook(submission_format.iterrows(), total=submission_format.shape[0]): # get the model for this site + common_name model = models[i] # make predictions using the model row_predictions = model.predict( submission_format.columns.values.reshape(-1, 1) ) # keep our predictions, rounded to nearest whole number preds.append(np.round(row_predictions)) # Create a dataframe that we can write out to a CSV prediction_df = pd.DataFrame(preds, index=submission_format.index, columns=submission_format.columns) prediction_df.head() prediction_df.to_csv('predictions.csv') ```
github_jupyter
# UNSEEN-open In this project, the aim is to build an open, reproducible, and transferable workflow for UNSEEN. <!-- -- an increasingly popular method that exploits seasonal prediction systems to assess and anticipate climate extremes beyond the observed record. The approach uses pooled forecasts as plausible alternate realities. Instead of the 'single realization' of reality, pooled forecasts can be exploited to better assess the likelihood of infrequent events. --> The workflow consists of four steps, as illustrated below: ![title](../../graphs/Workflow.png) In this project, UNSEEN-open is applied to assess two extreme events in 2020: February 2020 UK precipitation and the 2020 Siberian heatwave. February average precipitation was the highest on record in the UK: with what frequency of occurrence can February extreme precipitation events such as the 2020 event be expected? The Siberian heatwave has broken the records as well. Could such an event be anticipation with UNSEEN? And to what extend can we expect changes in the frequency of occurrence and magnitude of these kind of events? ## Overview Here we provide an overview of the steps taken to apply UNSEEN-open. ### Download We want to download February precipitation over the UK and March-May average temperature over Siberia. We retrieve all SEAS5 seasonal forecasts that are forecasting the target months (i.e. February and MAM) and we retrieve ERA5 reanalysis for the same regions and variables for evaluation. ``` import os import sys sys.path.insert(0, os.path.abspath('../../')) os.chdir(os.path.abspath('../../')) import src.cdsretrieve as retrieve import src.preprocess as preprocess import numpy as np retrieve.retrieve_SEAS5(variables = ['2m_temperature','2m_dewpoint_temperature'], target_months = [3,4,5], area = [70, -11, 30, 120], years=np.arange(1981, 2021), folder = '../Siberia_example/SEAS5/') retrieve.retrieve_SEAS5(variables = 'total_precipitation', target_months = [2], area = [60, -11, 50, 2], folder = '../UK_example/SEAS5/') retrieve.retrieve_ERA5(variables = ['2m_temperature','2m_dewpoint_temperature'], target_months = [3,4,5], area = [70, -11, 30, 120], folder = '../Siberia_example/ERA5/') retrieve.retrieve_ERA5(variables = 'total_precipitation', target_months = [2], area = [60, -11, 50, 2], folder = '../UK_example/ERA5/') ``` ### Preprocess In the preprocessing step, we first merge all downloaded files into one netcdf file. Then the rest of the preprocessing depends on the definition of the extreme event. For example, for the UK case study, we want to extract the UK average precipitation while for the Siberian heatwave we will just used the defined area to spatially average over. For the MAM season, we still need to take the seasonal average, while for the UK we already have the average February precipitation. ``` SEAS5_Siberia = preprocess.merge_SEAS5(folder = '../Siberia_example/SEAS5/', target_months = [3,4,5]) SEAS5_Siberia SEAS5_Siberia.sel(latitude = 60, longitude = -10, time = '2000-03', number = 24, leadtime = 3).load() SEAS5_UK = preprocess.merge_SEAS5(folder = '../UK_example/SEAS5/', target_months = [2]) SEAS5_UK ``` ### Read more Jump into the respective sections for more detail: * **Download** * [1. Retrieve](1.Download/1.Retrieve.ipynb) * **Pre-process** * [2.1 Merge](2.Preprocess/2.1Merge.ipynb) * [2.2 Mask](2.Preprocess/2.2Mask.ipynb) * [2.3 Upscale](2.Preprocess/2.3Upscale.ipynb) * **Evaluate** * [3. Evaluate](3.Evaluate/3.Evaluate.ipynb) * **Illustrate**
github_jupyter