path
stringlengths
7
265
concatenated_notebook
stringlengths
46
17M
experiments/tw-on-uniform/8/tw_template.ipynb
###Markdown Imports ###Code #packages import numpy import tensorflow as tf from tensorflow.core.example import example_pb2 #utils import os import random import pickle import struct import time from generators import * #keras import keras from keras.preprocessing import text, sequence from keras.preprocessing.text import Tokenizer from keras.models import Model, Sequential from keras.models import load_model from keras.layers import Dense, Dropout, Activation, Concatenate, Dot, Embedding, LSTM, Conv1D, MaxPooling1D, Input, Lambda #callbacks from keras.callbacks import TensorBoard, ModelCheckpoint, Callback ###Output Using TensorFlow backend. ###Markdown Seeding ###Code sd = 8 from numpy.random import seed seed(sd) from tensorflow import set_random_seed set_random_seed(sd) ###Output _____no_output_____ ###Markdown CPU usage ###Code #os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" # see issue #152 #os.environ["CUDA_VISIBLE_DEVICES"] = "" ###Output _____no_output_____ ###Markdown Global parameters ###Code # Embedding max_features = 400000 maxlen_text = 400 maxlen_summ = 80 embedding_size = 100 #128 # Convolution kernel_size = 5 filters = 64 pool_size = 4 # LSTM lstm_output_size = 70 # Training batch_size = 32 epochs = 3 ###Output _____no_output_____ ###Markdown Load data ###Code data_dir = '/mnt/disks/500gb/experimental-data-mini/experimental-data-mini/pseudorandom-dist-1to1/1to1/' processing_dir = '/mnt/disks/500gb/stats-and-meta-data/400000/' with open(data_dir+'partition.pickle', 'rb') as handle: partition = pickle.load(handle) with open(data_dir+'labels.pickle', 'rb') as handle: labels = pickle.load(handle) with open(processing_dir+'tokenizer.pickle', 'rb') as handle: tokenizer = pickle.load(handle) embedding_matrix = numpy.load(processing_dir+'embedding_matrix.npy') #the p_n constant c = 80000 #stats maxi = numpy.load(processing_dir+'training-stats-all/maxi.npy') mini = numpy.load(processing_dir+'training-stats-all/mini.npy') sample_info = (numpy.random.uniform, mini,maxi) ###Output _____no_output_____ ###Markdown Model ###Code #2way input text_input = Input(shape=(maxlen_text,embedding_size), dtype='float32') summ_input = Input(shape=(maxlen_summ,embedding_size), dtype='float32') #2way dropout text_route = Dropout(0.25)(text_input) summ_route = Dropout(0.25)(summ_input) #2way conv text_route = Conv1D(filters, kernel_size, padding='valid', activation='relu', strides=1)(text_route) summ_route = Conv1D(filters, kernel_size, padding='valid', activation='relu', strides=1)(summ_route) #2way max pool text_route = MaxPooling1D(pool_size=pool_size)(text_route) summ_route = MaxPooling1D(pool_size=pool_size)(summ_route) #2way lstm text_route = LSTM(lstm_output_size)(text_route) summ_route = LSTM(lstm_output_size)(summ_route) #get dot of both routes merged = Dot(axes=1,normalize=True)([text_route, summ_route]) #negate results #merged = Lambda(lambda x: -1*x)(merged) #add p_n constant #merged = Lambda(lambda x: x + c)(merged) #output output = Dense(1, activation='sigmoid')(merged) #define model model = Model(inputs=[text_input, summ_input], outputs=[output]) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) ###Output _____no_output_____ ###Markdown Train model ###Code #callbacks class BatchHistory(keras.callbacks.Callback): def on_train_begin(self, logs={}): self.losses = [] self.accs = [] def on_batch_end(self, batch, logs={}): self.losses.append(logs.get('loss')) self.accs.append(logs.get('acc')) history = BatchHistory() tensorboard = TensorBoard(log_dir='./logs', histogram_freq=0, batch_size=batch_size, write_graph=True, write_grads=True) modelcheckpoint = ModelCheckpoint('best.h5', monitor='val_loss', verbose=0, save_best_only=True, mode='min', period=1) #batch generator parameters params = {'dim': [(maxlen_text,embedding_size),(maxlen_summ,embedding_size)], 'batch_size': batch_size, 'shuffle': True, 'tokenizer':tokenizer, 'embedding_matrix':embedding_matrix, 'maxlen_text':maxlen_text, 'maxlen_summ':maxlen_summ, 'data_dir':data_dir, 'sample_info':sample_info} #generators training_generator = TwoQuartGenerator(partition['train'], labels, **params) validation_generator = TwoQuartGenerator(partition['validation'], labels, **params) # Train model on dataset model.fit_generator(generator=training_generator, validation_data=validation_generator, use_multiprocessing=True, workers=5, epochs=epochs, callbacks=[tensorboard, modelcheckpoint, history]) with open('losses.pickle', 'wb') as handle: pickle.dump(history.losses, handle, protocol=pickle.HIGHEST_PROTOCOL) with open('accs.pickle', 'wb') as handle: pickle.dump(history.accs, handle, protocol=pickle.HIGHEST_PROTOCOL) ###Output _____no_output_____
Generative Deep Learning with TensorFlow/Week 4 GANs/Lab_2_First_DCGAN.ipynb
###Markdown Ungraded Lab: First DCGANIn this lab, you will see a demo of a Deep Convolutional GAN (DCGAN) trained on Fashion MNIST. You'll see architectural differences from the GAN in the first lab and also see the best practices when building this network. Imports ###Code import tensorflow as tf import tensorflow.keras as keras import numpy as np import matplotlib.pyplot as plt from IPython import display ###Output _____no_output_____ ###Markdown Utilities ###Code def plot_results(images, n_cols=None): '''visualizes fake images''' display.clear_output(wait=False) n_cols = n_cols or len(images) n_rows = (len(images) - 1) // n_cols + 1 if images.shape[-1] == 1: images = np.squeeze(images, axis=-1) plt.figure(figsize=(n_cols, n_rows)) for index, image in enumerate(images): plt.subplot(n_rows, n_cols, index + 1) plt.imshow(image, cmap="binary") plt.axis("off") ###Output _____no_output_____ ###Markdown Download and Prepare the DatasetYou will use the [Fashion MNIST](https://github.com/zalandoresearch/fashion-mnist) dataset for this exercise. As before, you will only need to create batches of the training images. The preprocessing steps are also shown below. ###Code # download the training images (X_train, _), _ = keras.datasets.fashion_mnist.load_data() # normalize pixel values X_train = X_train.astype(np.float32) / 255 # reshape and rescale X_train = X_train.reshape(-1, 28, 28, 1) * 2. - 1. BATCH_SIZE = 128 # create batches of tensors to be fed into the model dataset = tf.data.Dataset.from_tensor_slices(X_train) dataset = dataset.shuffle(1000) dataset = dataset.batch(BATCH_SIZE, drop_remainder=True).prefetch(1) ###Output Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/train-labels-idx1-ubyte.gz 32768/29515 [=================================] - 0s 0us/step Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/train-images-idx3-ubyte.gz 26427392/26421880 [==============================] - 0s 0us/step Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/t10k-labels-idx1-ubyte.gz 8192/5148 [===============================================] - 0s 0us/step Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/t10k-images-idx3-ubyte.gz 4423680/4422102 [==============================] - 0s 0us/step ###Markdown Build the Model In DCGANs, convolutional layers are predominantly used to build the generator and discriminator. You will see how the layers are stacked as well as the best practices shown below. GeneratorFor the generator, we take in random noise and eventually transform it to the shape of the Fashion MNIST images. The general steps are:* Feed the input noise to a dense layer.* Reshape the output to have three dimensions. This stands for the (length, width, number of filters).* Perform a deconvolution (with [Conv2DTranspose](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Conv2DTranspose)), reducing the number of filters by half and using a stride of `2`.* The final layer upsamples the features to the size of the training images. In this case 28 x 28 x 1.Notice that batch normalization is performed except for the final deconvolution layer. As best practice, `selu` is the activation used for the intermediate deconvolution while `tanh` is for the output. We printed the model summary so you can see the shapes at each layer. ###Code codings_size = 32 generator = keras.models.Sequential([ keras.layers.Dense(7 * 7 * 128, input_shape=[codings_size]), keras.layers.Reshape([7, 7, 128]), keras.layers.BatchNormalization(), keras.layers.Conv2DTranspose(64, kernel_size=5, strides=2, padding="SAME", activation="selu"), keras.layers.BatchNormalization(), keras.layers.Conv2DTranspose(1, kernel_size=5, strides=2, padding="SAME", activation="tanh"), ]) generator.summary() ###Output Model: "sequential" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= dense (Dense) (None, 6272) 206976 _________________________________________________________________ reshape (Reshape) (None, 7, 7, 128) 0 _________________________________________________________________ batch_normalization (BatchNo (None, 7, 7, 128) 512 _________________________________________________________________ conv2d_transpose (Conv2DTran (None, 14, 14, 64) 204864 _________________________________________________________________ batch_normalization_1 (Batch (None, 14, 14, 64) 256 _________________________________________________________________ conv2d_transpose_1 (Conv2DTr (None, 28, 28, 1) 1601 ================================================================= Total params: 414,209 Trainable params: 413,825 Non-trainable params: 384 _________________________________________________________________ ###Markdown As a sanity check, let's see the fake images generated by the untrained generator and see the dimensions of the output. ###Code # generate a batch of noise input (batch size = 16) test_noise = tf.random.normal([16, codings_size]) # feed the batch to the untrained generator test_image = generator(test_noise) # visualize sample output plot_results(test_image, n_cols=4) print(f'shape of the generated batch: {test_image.shape}') ###Output shape of the generated batch: (16, 28, 28, 1) ###Markdown DiscriminatorThe discriminator will use strided convolutions to reduce the dimensionality of the input images. As best practice, these are activated by [LeakyRELU](https://keras.io/api/layers/activation_layers/leaky_relu/). The output features will be flattened and fed to a 1-unit dense layer activated by `sigmoid`. ###Code discriminator = keras.models.Sequential([ keras.layers.Conv2D(64, kernel_size=5, strides=2, padding="SAME", activation=keras.layers.LeakyReLU(0.2), input_shape=[28, 28, 1]), keras.layers.Dropout(0.4), keras.layers.Conv2D(128, kernel_size=5, strides=2, padding="SAME", activation=keras.layers.LeakyReLU(0.2)), keras.layers.Dropout(0.4), keras.layers.Flatten(), keras.layers.Dense(1, activation="sigmoid") ]) discriminator.summary() ###Output Model: "sequential_1" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= conv2d (Conv2D) (None, 14, 14, 64) 1664 _________________________________________________________________ dropout (Dropout) (None, 14, 14, 64) 0 _________________________________________________________________ conv2d_1 (Conv2D) (None, 7, 7, 128) 204928 _________________________________________________________________ dropout_1 (Dropout) (None, 7, 7, 128) 0 _________________________________________________________________ flatten (Flatten) (None, 6272) 0 _________________________________________________________________ dense_1 (Dense) (None, 1) 6273 ================================================================= Total params: 212,865 Trainable params: 212,865 Non-trainable params: 0 _________________________________________________________________ ###Markdown As before, you will append these two subnetwork to build the complete GAN. ###Code gan = keras.models.Sequential([generator, discriminator]) ###Output _____no_output_____ ###Markdown Configure the Model for trainingThe discriminator and GAN will still be classifying fake and real images so you will use the same settings as before. ###Code discriminator.compile(loss="binary_crossentropy", optimizer="rmsprop") discriminator.trainable = False gan.compile(loss="binary_crossentropy", optimizer="rmsprop") ###Output _____no_output_____ ###Markdown Train the ModelThe training loop will also be identical to the previous one you built. Run the cells below and observe how the fake images become more convincing as the training progresses. ###Code def train_gan(gan, dataset, random_normal_dimensions, n_epochs=50): """ Defines the two-phase training loop of the GAN Args: gan -- the GAN model which has the generator and discriminator dataset -- the training set of real images random_normal_dimensions -- dimensionality of the input to the generator n_epochs -- number of epochs """ generator, discriminator = gan.layers for epoch in range(n_epochs): print("Epoch {}/{}".format(epoch + 1, n_epochs)) for real_images in dataset: # infer batch size from the training batch batch_size = real_images.shape[0] # Train the discriminator - PHASE 1 # create the noise noise = tf.random.normal(shape=[batch_size, random_normal_dimensions]) # use the noise to generate fake images fake_images = generator(noise) # create a list by concatenating the fake images with the real ones mixed_images = tf.concat([fake_images, real_images], axis=0) # Create the labels for the discriminator # 0 for the fake images # 1 for the real images discriminator_labels = tf.constant([[0.]] * batch_size + [[1.]] * batch_size) # ensure that the discriminator is trainable discriminator.trainable = True # use train_on_batch to train the discriminator with the mixed images and the discriminator labels discriminator.train_on_batch(mixed_images, discriminator_labels) # Train the generator - PHASE 2 # create a batch of noise input to feed to the GAN noise = tf.random.normal(shape=[batch_size, random_normal_dimensions]) # label all generated images to be "real" generator_labels = tf.constant([[1.]] * batch_size) # freeze the discriminator discriminator.trainable = False # train the GAN on the noise with the labels all set to be true gan.train_on_batch(noise, generator_labels) # plot the fake images used to train the discriminator plot_results(fake_images, 16) plt.show() train_gan(gan, dataset, codings_size, 100) ###Output _____no_output_____
Network_Analysis/network_analysis_notebook.ipynb
###Markdown 1. Load Dataset into Pandas DataFrameDescription: Analyze co-occurrence network of the characters in the Game of Thrones books. Characters are considered co-occur if their names appear in the vicinity of 15 words from one another in the books.Dataset constitutes a network and is given as a text file describing the edges between characters, with some attributes attached to each edge. Let's start by loading in the data for the first book A Game of Thrones and inspect it.![got_network.jpeg](attachment:got_network.jpeg)The resulting DataFrame book1 below has 5 columns: Source, Target, Type, weight, and book. Source and target are the two nodes that are linked by an edge. A network can have directed or undirected edges and in this network all the edges are undirected. The weight attribute of every edge tells us the number of interactions that the characters have had over the book, and the book column tells us the book number. ###Code # Importing modules import pandas as pd # Reading in datasets/book1.csv book1 = pd.read_csv('datasets/book1.csv') # Printing out the head of the dataset print(book1.head()) # Recall: DataFrame has 5 columns: Source, Target, Type, weight, and book. # Recall: Source and Target are the two nodes that are linked by an edge ###Output Source Target Type weight \ 0 Addam-Marbrand Jaime-Lannister Undirected 3 1 Addam-Marbrand Tywin-Lannister Undirected 6 2 Aegon-I-Targaryen Daenerys-Targaryen Undirected 5 3 Aegon-I-Targaryen Eddard-Stark Undirected 4 4 Aemon-Targaryen-(Maester-Aemon) Alliser-Thorne Undirected 4 book 0 1 1 1 2 1 3 1 4 1 ###Markdown 2. Create NetworkX GraphNetworkX is a Python package for the creation, manipulation, and study of the structure, dynamics, and functions of complex networks. ###Code # Importing modules import networkx as nx # Creating an empty graph object G_book1 = nx.Graph() ###Output _____no_output_____ ###Markdown 3. Populate the network with the DataFrame Currently, the graph object G_book1 is empty. Let us now populate network with the edges from book1. Load remaining dtatsets (books), folder datasets. ###Code # Iterating through the DataFrame to add edges for _, edge in book1.iterrows(): G_book1.add_edge(edge['Source'], edge['Target'], weight=edge['weight']) # Creating a list of networks for all the books books = [G_book1] book_fnames = ['datasets/book2.csv', 'datasets/book3.csv', 'datasets/book4.csv', 'datasets/book5.csv'] for book_fname in book_fnames: book = pd.read_csv(book_fname) G_book = nx.Graph() for _, edge in book.iterrows(): G_book.add_edge(edge['Source'], edge['Target'], weight=edge['weight']) books.append(G_book) ###Output _____no_output_____ ###Markdown 4. Measure Degree CentralityNetwork Science offers us many different metrics to measure the importance of a node in a network. No "correct" way of calculating the most important node in a network, every metric has a different meaning.First, measure the importance of a node in a network by looking at the number of neighbors it has, that is, the number of nodes it is connected to.Using 'number of neighbors' measure, extract top ten important characters from the first book (book[0]) and the fifth book (book[4]). ###Code # Calculating the degree centrality of book 1 deg_cen_book1 = nx.degree_centrality(books[0]) # Calculating the degree centrality of book 5 deg_cen_book5 = nx.degree_centrality(books[4]) # Sorting the dictionaries according to their degree centrality and storing the top 10 sorted_deg_cen_book1 = sorted(deg_cen_book1.items(), key=lambda x:x[1], reverse=True)[0:10] # Sorting the dictionaries according to their degree centrality and storing the top 10 sorted_deg_cen_book5 = sorted(deg_cen_book5.items(), key=lambda x:x[1], reverse=True)[0:10] # Printing out the top 10 of book1 and book5 print(sorted_deg_cen_book1) print() print(sorted_deg_cen_book5) ###Output [('Eddard-Stark', 0.3548387096774194), ('Robert-Baratheon', 0.2688172043010753), ('Tyrion-Lannister', 0.24731182795698928), ('Catelyn-Stark', 0.23118279569892475), ('Jon-Snow', 0.19892473118279572), ('Robb-Stark', 0.18817204301075272), ('Sansa-Stark', 0.18817204301075272), ('Bran-Stark', 0.17204301075268819), ('Cersei-Lannister', 0.16129032258064518), ('Joffrey-Baratheon', 0.16129032258064518)] [('Jon-Snow', 0.1962025316455696), ('Daenerys-Targaryen', 0.18354430379746836), ('Stannis-Baratheon', 0.14873417721518986), ('Tyrion-Lannister', 0.10443037974683544), ('Theon-Greyjoy', 0.10443037974683544), ('Cersei-Lannister', 0.08860759493670886), ('Barristan-Selmy', 0.07911392405063292), ('Hizdahr-zo-Loraq', 0.06962025316455696), ('Asha-Greyjoy', 0.056962025316455694), ('Melisandre', 0.05379746835443038)] ###Markdown 5. Evolution of Degree CentralityAccording to degree centrality, the most important character in the first book is Eddard Stark but he is not even in the top 10 of the fifth book. The importance of characters changes over the course of five books because, you know, stuff happens... ;)Let's look at the evolution of degree centrality of a couple of characters like Eddard Stark, Jon Snow, and Tyrion, which showed up in the top 10 of degree centrality in the first book. ###Code %matplotlib inline # Creating a list of degree centrality of all the books evol = [nx.degree_centrality(book) for book in books] # Creating a DataFrame from the list of degree centralities in all the books degree_evol_df = pd.DataFrame.from_records(evol) # Plotting the degree centrality evolution of Eddard-Stark, Tyrion-Lannister and Jon-Snow degree_evol_df[['Eddard-Stark', 'Tyrion-Lannister', 'Jon-Snow']].plot() ###Output _____no_output_____ ###Markdown 6. What's up with Stannis Baratheon?We can see that the importance of Eddard Stark dies off as the book series progresses. With Jon Snow, there is a drop in the fourth book but a sudden rise in the fifth book.Now let's look at various other measures like betweenness centrality and PageRank to find important characters in our Game of Thrones character co-occurrence network and see if we can uncover some more interesting facts about this network. Let's plot the evolution of betweenness centrality of this network over the five books. We will take the evolution of the top four characters of every book and plot it. ###Code # Creating a list of betweenness centrality of all the books just like we did for degree centrality evol = [nx.betweenness_centrality(book, weight='weight') for book in books] # Making a DataFrame from the list betweenness_evol_df = pd.DataFrame.from_records(evol).fillna(0) # Finding the top 4 characters in every book set_of_char = set() for i in range(5): set_of_char |= set(list(betweenness_evol_df.T[i].sort_values(ascending=False)[0:4].index)) list_of_char = list(set_of_char) # Plotting the evolution of the top characters betweenness_evol_df[list_of_char].plot(figsize=(13,7)) ###Output _____no_output_____ ###Markdown 7. PageRankWe see a peculiar rise in the importance of Stannis Baratheon over the books. In the fifth book, he is significantly more important than other characters in the network, even though he is the third most important character according to degree centrality.PageRank was the initial way Google ranked web pages. It evaluates the inlinks and outlinks of webpages in the world wide web, which is, essentially, a directed network. Let's look at the importance of characters in the Game of Thrones network according to PageRank. ###Code # Creating a list of pagerank of all the characters in all the books evol = [nx.pagerank(book, weight='weight') for book in books] # Making a DataFrame from the list pagerank_evol_df = pd.DataFrame.from_records(evol).fillna(0) # Finding the top 4 characters in every book set_of_char = set() for i in range(5): set_of_char |= set(list(pagerank_evol_df.T[i].sort_values(ascending=False)[0:4].index)) list_of_char = list(set_of_char) # Plotting the top characters pagerank_evol_df[list_of_char].plot(figsize=(13,7)) ###Output _____no_output_____ ###Markdown 8. Correlation between different measuresStannis, Jon Snow, and Daenerys are the most important characters in the fifth book according to PageRank. Eddard Stark follows a similar curve but for degree centrality and betweenness centrality: He is important in the first book but dies into oblivion over the book series.We have seen three different measures to calculate the importance of a node in a network, and all of them tells us something about the characters and their importance in the co-occurrence network. We see some names pop up in all three measures so maybe there is a strong correlation between them?Let's look at the correlation between PageRank, between centrality and degree centrality for the fifth book using Pearson correlation. ###Code # Creating a list of pagerank, betweenness centrality, degree centrality # of all the characters in the fifth book. measures = [nx.pagerank(books[4]), nx.betweenness_centrality(books[4], weight='weight'), nx.degree_centrality(books[4])] # Creating the correlation DataFrame cor = pd.DataFrame.from_records(measures).fillna(0) # Calculating the correlation cor.T.corr() ###Output _____no_output_____ ###Markdown 9. ConclusionWe see a high correlation between these three measures for our character co-occurrence network.So we've been looking at different ways to find the important characters in the Game of Thrones co-occurrence network. According to degree centrality, Eddard Stark is the most important character initially in the books.But by Fifth book, Jon Snow is most important character according to these three measures? ###Code # Finding the most important character in the fifth book,according to degree centrality, betweenness centrality and pagerank. p_rank, b_cent, d_cent = cor.idxmax(axis=1) # Printing out the top character accoding to the three measures print(p_rank, b_cent, d_cent) ###Output Jon-Snow Stannis-Baratheon Jon-Snow
Regression/regression_sec_us.ipynb
###Markdown P-greater-than-N scenarios- So far I have covered the problems were such that the number if features was far less than the number of samples availablle in training set.- However, for text or image data, aa new problem occurs which is that the number of features is much greater than the number of samples available.- Given below is an example of the one such regression problem. Let's dive in. Problem- __*Dateset*__: 10-K reports that companies filed with the **Securities and Exchange Comission(SEC)** in the United States.- __*Goal*__: To predict, based on this piece of public information, what the future volatility of the company's stock will be. Load Dataset--> *available in sklearn* ###Code ''' load dataset ''' from sklearn.datasets import load_svmlight_file data, target = load_svmlight_file('data/E2006.train') ###Output _____no_output_____
machine_learning_introduction.ipynb
###Markdown Approaches to machine learningSupervised Learning In supervised learning we take a set of data and a set of labels that map to the data, xi -> yi, the dataset is split to provide a training set and a test set, the model is trained on the data and labels, and tested on the test data, the aim is to reduce the error. Supervised learning is typically used for Classification or Regression problems.A Regression problem involves predicting a numerical label, an example of regression would be projections of new coronavirus cases based on historic data, or data from other countries such as provided by worldmeter (“United Kingdom Coronavirus cases,” n.d.).A Classification problem aims to identify a class label, an example of a classification problem would be the digit identification we looked at with the MNIST database (LeCunn et al., n.d.), which takes data and label pairs (x,y) x is data y is label, with the goal of learning a function to map x-> y.The MNIST dataset consists of 60000 labelled images of the digits 0-9. (LeCunn et al., n.d.) So a supervised model might take 40000 images and labels as the training set and run the model on these. Once the model is trained it is run with the test data.A good model will give similar test results to training results. A model that has been too closely training is said to have been overfitted to the training data which. This highlights the importance of splitting the data into at least training and test data (better still, training, verification and testing data) sets to prevent unseen correlations from swaying the model. TODO add rationale for use of SL >“Learning is a search through the space of possible hypotheses for one that will perform well, even on new examples beyond the training set. To measure the accuracy of a hypothesis we give it a test set of examples that are distinct from the training set.” (Norvig & Stuart, 2010).Unsupervised learning. Unsupervised learning does not require labelled data, and instead actively looks for correlations within the data to learn the underlying structure - "is this thing like another thing?"Unsupervised learning is typically used for clustering or density estimation problems.An example of a problem addressed by clustering is spam filtering, which can use K-Means clustering to at the email header and content and create groups, or clusters to identify problem emails.(“(28) Lecture 13.2 — Clustering | KMeans Algorithm — [ Machine Learning | Andrew Ng ] - YouTube,” n.d.) TODO add rationale for value of USL>“The most common unsupervised learning task is clustering detecting potentially useful clusters of input examples. For example, a taxi agent might gradually develop a concept of “good traffic days” and “bad traffic days” without ever being given labelled examples of each by a teacher.” (Norvig & Stuart, 2010). Reinforcement learning Reinforcement learning places the machine learning agent in an environment and lets it learn using feedback and success against a success criterion. It takes data as state action pairs and sets goals based on maximum future rewards over many time steps.>“Reinforcement learning is learning what to do — how to map situations to actions—so as to maximize a numerical reward signal. The learner is not told which actions to take, but instead must discover which actions yield the most reward by trying them.” (Sutton & Barto, 2018). An example of reinforcement learning would be the (very popular with Computer Science students) work on AI systems learning to play Video games (Shao, Tang, Zhu, Li, & Zhao, 2018). However the difficulty of configuring an effective Reinforcement Learning model is substantial, even for exteremely competent researcher like Andrew Karpathy. > karpathy on Hacker News Jan 30, 2017 | parent | favorite | on: Outrageously Large Neural Networks: The Sparsely-G...If it makes you feel any better, I've been doing this for a while and it took me last ~6 weeks to get a from-scratch policy gradients implementation to work 50% of the time on a bunch of RL problems. And I also have a GPU cluster available to me, and a number of friends I get lunch with every day who've been in the area for the last few years.Also, what we know about good CNN design from supervised learning land doesn't seem to apply to reinforcement learning land, because you're mostly bottlenecked by credit assignment / supervision bitrate, not by a lack of a powerful representation. Your ResNets, batchnorms, or very deep networks have no power here.SL wants to work. Even if you screw something up you'll usually get something non-random back. RL must be forced to work. If you screw something up or don't tune something well enough you're exceedingly likely to get a policy that is even worse than random. And even if it's all well tuned you'll get a bad policy 30% of the time, just because.Long story short your failure is more due to the difficulty of deep RL, and much less due to the difficulty of "designing neural networks".TODO add rationale for not using RLReinforecement Learning is hard because of the reward sparsity, and the need to incremental which can lead to deception. The models do not generalise at all well, and the sample efficiency is dreadful.[TODO add ref to Alex Irpan Deep reinforcement learning doesn't work yet"]For these reasons I will not be using deep reinforcement learning. Transfer LearningTransfer learning allows parts of a pre trained neural network to be re-used, saving time and money. The simplest route is to take a prexisting trained model. Freeze some of the layers to set their trained weights and add additional more specific layers. This reduces the overhead for basic feature extraction, re-using those convolutional layers close to the input, and concentrates on aspects particular to the use case training the fully connected layers. Neural Networks It's interesting to consider that the original work undertaken by McCulloch and Pitts (Mcculloch & Pitts, 1990) on neural brain structures as logic gates informed and inspired Von-Neumann's architecture (Ohta, 2015) and his view of the computer as a brain. The paradigm shifted and we began to view the brain as a type of computer, and as we came round to neural networks the analogy switched back once more (Cobb, 2020). Early work on Neural Networks was carried out by Frank Rosenblatt, who described the structure of the perceptron (Rosenblatt, 1958). Rosenblatt may have overhyped his findings, and fed a media circus instead of managing expectations (Boden, 2006). ![Rosenblatts Perceptron](https://raw.githubusercontent.com/re114/robotdraws/main/img/Rosenblatt-perceptron.png)Minksy at MIT published a damning mathematical analysis of Rosenblatt's work (Minsky, 1961) which many cite as precipitating the first AI winter (Boden, 2006) (Norvig & Stuart, 2010). The paper suggested that the perceptron was a dead end for AI as it could not internally represent the things it was learning (Cobb, 2020) and it was not until the adoption of backpropagation that the approach became ascendant again (Y. LeCun et al., 1989). The structure of Neural Networks Bengio quotes Hinton: "You have relatively simple processing elements that are very loosely models of neurons. They have connections coming in , each connection has a weight on it, and that weight can be changed through learning” (LeCunn, Bottou, & Haffner, 1998). Chollet outlines the processes in the operation of a Neural Network (François Chollet, 2019). • define • fit • predict • and evaluate • Initialise weights randomly - or by some insight into the relative importance of hyperparameters. • loop till convergence • compute gradient - (derivative) • update weights • return weights In practical terms the aim is to minimise the error. We can describe the error as the absolute difference between the prediction and the results. ```error = ((input * weight) - goal.pred) **2```The weight determines the significance of the input. This script trains a basic neural network on a set of labelled data to classify images as either cats or dogs. ###Code import tensorflow as tf mnist = tf.keras.datasets.mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train, x_test = x_train / 255.0, x_test / 255.0 model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(10) ]) predictions = model(x_train[:1]).numpy() predictions tf.nn.softmax(predictions).numpy() loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True) loss_fn(y_train[:1], predictions).numpy() model.compile(optimizer='adam', loss=loss_fn, metrics=['accuracy']) model.summary() model.fit(x_train, y_train, epochs=5) model.evaluate(x_test, y_test, verbose=2) probability_model = tf.keras.Sequential([ model, tf.keras.layers.Softmax() ]) probability_model(x_test[:5]) ###Output _____no_output_____ ###Markdown We can gauge how accurate our predictions are by comparing the prediction with a known result or label. In order to benefit from multiple layers, we need to add an activation function, without this the layers could practically be collapsed into a single layer (H. Li, Ouyang, & Wang, 2016). The activation function maps back to the neural structure of biological systems where synaptic inputs are expressed or repressed (Hawkins, 2005) to determine their activation.We can use a range of activation functions, such as RELU - rectified linear units which only activates if the input is above zero. BackpropagationWhilst backpropagation was discovered in the 1970s, it was neglected until a 1986 Nature paper co-authored by Geoffrey Hinton:>"At its essence backpropagation is just a clever application of the chain rule." (Rumelhart, Hinton, & Williams, 1986) >"The procedure repeatedly adjusts the weights of the connections in the network so as to minimize a measure of the difference between the actual output vector of the net and the desired output vector. As a result of the weight adjustments, internal ‘hidden’ units which are not part of the input or output come to represent important features of the task domain, and the regularities in the task are captured by the interactions of these units" Echoing our previous note on the parallel and complementary development of AI and cognitive neuroscience, Hinton has recently co-authored a paper "Backpropagation and the brain" (Lillicrap, Santoro, Marris, Akerman, & Hinton, 2020) which argues that "feedback connections may induce neural activities whose differences can be used to locally approximate these signals and hence drive effective learning in deep networks in the brain." Backpropagation is an expression for the partial derivative of the cost function with respect to any weight or bias in the network. The expression tells the network how quickly the cost changes when the weights and biases are changed (Nielsen, 2015). More pragmatically LeCunn describes backpropagation as: “a very popular neural network learning algorithm because it is conceptually simple, computationally efficient, and because it often works.” It is worth noting that LeCunn continues to identify the lack of precision in determining initial conditions at the heart of backpropagation, a theme that emerges again when deciding policies on dealing with missing data. >“However, getting it to work well, and sometimes to work at all, can seem more of an art than a science. Designing and training a network using backprop requires making many seemingly arbitrary choices such as the number and types of nodes, layers, learning rates, training and test sets, and so forth. These choices can be critical, yet there is no fool proof recipe for deciding them because they are largely problem and data dependent. However, there are heuristics and some underlying theory that can help guide a practitioner to make better choices.” (Y. A. LeCun, Bottou, Orr, & Müller, 2012). ###Code # code example here ###Output _____no_output_____ ###Markdown Recurrent Neural Nets>“A Recurrent Neural Network is a type of neural network that contains loops, allowing information to be stored within the network. In short, Recurrent Neural Networks use their reasoning from previous experiences to inform the upcoming events. Recurrent models are valuable in their ability to sequence vectors, which opens up the API to performing more complicated tasks.” (“Recurrent Neural Network Definition | DeepAI,” n.d.) Boucher quotes Trask: "I feel like a significant percentage of Deep Learning breakthroughs ask the question ‘how can I re-use weights in multiple places?’ - Recurrent (LTSM) layers for multiple timesteps - Convolutional layers reuse layers in multiple locations - capsules reuse across orientation" (Boucher, 2019) Long Term Short memory networks are a subclass of recurrent neural network (Hochreiter & Schmidhuber, 1997) identified by Hochreiter and Schmidhuber in 1997 which allow data to be passed across layers in a neural network improving performance (Sherstinsky, 2018). >“ A recurrent network whose inputs are not fixed but rather constitute an input sequence can be used to transform an input sequence into an output sequence while taking into account contextual information in a flexible way.” (Bengio, Simard, & Frasconi, 1994). Graves implementation of this was one of the spurs to this initial study:>“Unfortunately, the range of contextual information that standard RNNs can access is in practice quite limited. The problem is that the influence of a given input on the hidden layer, and therefore on the network output, either decays or blows up exponentially as it cycles around the network’s recurrent connections.This shortcoming ... referred to in the literature as the vanishing gradient problem ... Long Short-Term Memory (LSTM) is an RNN architecture specifically designed to address the vanishing gradient problem.” (Graves et al., 2009). Deep Learning Convolutional Neural NetworksAs highlighted by Boucher “Convolutional layers reuse layers in multiple locations” (Boucher, 2019). Yan LeCunn outlined the architecture of the Convolutional Neural Network in 1998 (Yann LeCun, Bottou, Bengio, & Haffner, 1998) and (Bottou, Bengio, & Le Cun, 1997). LeNet-5 consists of two sets of convolutional and average pooling layers, followed by a flattening convolutional layer, then two fully connected layers and finally a softmax classifier. TODO add Structure of LeNet5 source lecun.com The CNN applies a sliding window like a filter, and every targeted pixel is multiplied by the value by the filter. The structure of the window determines what aspects of the input layer are amplified.TODO add 2D convolution source Cambridge Coding Academy e.g.This is an example a convolution to emphasise vertical lines: -1 0 1 -2 0 2 -1 0 1 This is an example of a convolution to emphasise horizontal lines -1 -2 -1 0 0 0 1 2 1 Pooling is the process by which we compress data representation of the imagee.g.0 64 x x 48 192 x x xxxx xxxx To pool the top left quadrant we select the highest value:0 64 48 192 goes to 192 192 x x x ###Code # CNN example ###Output _____no_output_____
lesson05/Part2_planetsIn3D_lesson05.ipynb
###Markdown Day 5, Part 2 - Planets in 3D and plotting 3D things ###Code # usual things: import numpy as np import matplotlib.pyplot as plt #from mpl_toolkits.mplot3d import Axes3D %matplotlib inline #%matplotlib notebook ###Output _____no_output_____ ###Markdown There are a few different ways we can make some systems in 3D. The easiest is to take our original "by hand" systems and just add in a 3D component, and call our solver with the 3D tag. We can also simulate a kepler system in 3D as there is a 3D component to most if not all planetary systems. We'll try each of these. 1. By-Hand Planetary systems in 3d We'll start by taking our original Hermite solving datasets and inputting things in 3D: ###Code star_mass = 1.0 # stellar mass in Msun planet_masses = np.array( [1.0, 0.5] ) # planet masses in Mjupiter # [x,y,z] coords for each planet in AU # NOTE: no z-coords! These will be set to zero later on # if you make them non-zero planet_initial_position = np.array([ [1.0, 0.0, 1.0], [1.0, 0.0, 0.0]]) # planet's velocity at each position in km/s # NOTE: no z-velocities! These will be set to zero later on # if you make them non-zero planet_initial_velocity = np.array([ [0.0, 35, 0.0], [0.0, 15.0, 15.0]]) # note: this assumes that the star is at (0, 0, 0) and has zero # initial velocity ###Output _____no_output_____ ###Markdown We then call the Hermite solver as follows: ###Code from hermite_library import do_hermite r_h, v_h, t_h, E_h = do_hermite(star_mass, planet_masses, planet_initial_position, planet_initial_velocity, tfinal=1e7, Nsteps=8800, threeDee=True) # so sneaky, here the whole time! # let's plot! fig, ax = plt.subplots(1, 2, figsize = (10*2, 10)) fig.suptitle('Coordinates Plot') ax[0].set_xlabel('x in AU') ax[0].set_ylabel('y in AU') # recall: # r_h[NUMBER OF PARTICLES, NUMBER COORDINATES (X,Y,Z), NUMBER OF TIMESTEPS] for i in range(len(planet_masses)): ax[0].plot(r_h[i,0,:], r_h[i,1,:], lw=3) ax[1].set_xlabel('Time in years') ax[1].set_ylabel('Energy') # re-norm energy ax[1].plot(t_h, E_h) plt.show() ###Output _____no_output_____ ###Markdown Ok, but wait. This is only plotting x vs. y. How can we show all coordinates? We'll get more into 3D plots next week, but for now, we can plot all combinations by having more than one coordinates plot: ###Code # now make 4 plots instead of 2, and make it 4x wide as tall fig, ax = plt.subplots(1, 4, figsize = (10*4, 10)) fig.suptitle('Coordinates Plot') # X vs Y means 0th vs 1st coordinate axes # recall: # r_h[NUMBER OF PARTICLES, NUMBER COORDINATES (X,Y,Z), NUMBER OF TIMESTEPS] ax[0].set_xlabel('x in AU') ax[0].set_ylabel('y in AU') for i in range(len(planet_masses)): ax[0].plot(r_h[i,0,:], r_h[i,1,:], lw=3) # make *last* plot energy ax[3].set_xlabel('Time in years') ax[3].set_ylabel('Energy') # re-norm energy ax[3].plot(t_h, E_h) plt.show() ###Output _____no_output_____ ###Markdown Now we'll fill in the other axis combinations: ###Code # now make 4 plots instead of 2, and make it 4x wide as tall fig, ax = plt.subplots(1, 4, figsize = (10*4, 10)) fig.suptitle('Coordinates Plot') # X vs Y means 0th vs 1st coordinate axes # ax[0] means first plot # recall: # r_h[NUMBER OF PARTICLES, NUMBER COORDINATES (X,Y,Z), NUMBER OF TIMESTEPS] ax[0].set_xlabel('x in AU') ax[0].set_ylabel('y in AU') for i in range(len(planet_masses)): ax[0].plot(r_h[i,0,:], r_h[i,1,:], lw=3) # X vs Z means 0th vs 2nd coordinate axes # ax[1] means 2nd plot ax[1].set_xlabel('x in AU') ax[1].set_ylabel('z in AU') for i in range(len(planet_masses)): ax[1].plot(r_h[i,0,:], r_h[i,2,:], lw=3) # Y vs Z means 1th vs 2nd coordinate axes # ax[2] means 3rd plot ax[2].set_xlabel('y in AU') ax[2].set_ylabel('z in AU') for i in range(len(planet_masses)): ax[2].plot(r_h[i,1,:], r_h[i,2,:], lw=3) # make *last* plot energy ax[3].set_xlabel('Time in years') ax[3].set_ylabel('Energy') # re-norm energy ax[3].plot(t_h, E_h) plt.show() ###Output _____no_output_____ ###Markdown So this gives us additional information. It is still hard to see exactly what is going on, but we are getting a little bit more information. Next week we'll do some 3D movies and see what we can gain from them, but for now, we'll stay with these. We can also do the kepler system orbits in 3D, again with a few assumptions folded in. To do this we'll use the inclination of the orbit as well:![](http://astronomy.swin.edu.au/cms/cpg15x/albums/userpics/orbitalelements.2.jpg) First we'll read in the kepler data before from one of our systems. We have to make sure we have the `convert_kepler_data.py` file in our `.ipynb` directory. ###Code from convert_kepler_data import read_kepler_data kepler_data = read_kepler_data('kepler101data.txt') from convert_kepler_data import convert_kepler_data star_mass, \ planet_masses, \ planet_initial_position, \ planet_initial_velocity, ecc = convert_kepler_data(kepler_data, use_inclination_3d=True) ###Output _____no_output_____ ###Markdown Let's quickly remind ourselves what this system looks like: ###Code star_mass planet_masses planet_initial_position, planet_initial_velocity ###Output _____no_output_____ ###Markdown Ok, this is a 2 planet system with a central star of 1.17$M_\odot$ masses (i.e. 1.17 times the mass of the Sun). Let's do a sim! ###Code # solve # h is for hermite! r_h, v_h, t_h, E_h = do_hermite(star_mass, planet_masses, planet_initial_position, planet_initial_velocity, tfinal=1e4*5000, Nsteps=5000, threeDee=True) ###Output _____no_output_____ ###Markdown We can then use the exact same plotting routine we used before to plot this: ###Code # now make 4 plots instead of 2, and make it 4x wide as tall fig, ax = plt.subplots(1, 4, figsize = (10*4, 10)) fig.suptitle('Coordinates Plot') # X vs Y means 0th vs 1st coordinate axes # ax[0] means first plot # recall: # r_h[NUMBER OF PARTICLES, NUMBER COORDINATES (X,Y,Z), NUMBER OF TIMESTEPS] ax[0].set_xlabel('x in AU') ax[0].set_ylabel('y in AU') for i in range(len(planet_masses)): ax[0].plot(r_h[i,0,:], r_h[i,1,:], lw=3) # X vs Z means 0th vs 2nd coordinate axes # ax[1] means 2nd plot ax[1].set_xlabel('x in AU') ax[1].set_ylabel('z in AU') for i in range(len(planet_masses)): ax[1].plot(r_h[i,0,:], r_h[i,2,:], lw=3) # Y vs Z means 1th vs 2nd coordinate axes # ax[2] means 3rd plot ax[2].set_xlabel('y in AU') ax[2].set_ylabel('z in AU') for i in range(len(planet_masses)): ax[2].plot(r_h[i,1,:], r_h[i,2,:], lw=3) # make *last* plot energy ax[3].set_xlabel('Time in years') ax[3].set_ylabel('Energy') # re-norm energy ax[3].plot(t_h, E_h) plt.show() ###Output _____no_output_____ ###Markdown Don't forget, if I like this simulation, I can save it! ###Code from hermite_library import save_hermite_solution_to_file save_hermite_solution_to_file("MyPlanetarySystem2.txt", t_h, E_h, r_h, v_h) ###Output _____no_output_____
web-search-engine/final/notebooks/nearest_neighbour_explore.ipynb
###Markdown Clustering the images using k-means ###Code filename = 'result-wse_flickr.jsonl' filepath = '../tasks/03.image-crawl' import os filename = os.path.join(filepath, filename) print filename print os.path.exists(filename) # load the data # only get the data for query='bench' lines = open(filename).readlines() import json items = [json.loads(line) for line in lines] items = filter(lambda item: item.get('embeds') and item.get('query') == 'bird', items) print len(items) print items[0].keys() urls = [item['url'] for item in items] features = [item['embeds'] for item in items] print len(urls) print len(features) import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from sklearn.cluster import KMeans from sklearn import datasets np.random.seed(5) from time import time import numpy as np import matplotlib.pyplot as plt from sklearn import metrics from sklearn.cluster import KMeans from sklearn.datasets import load_digits from sklearn.decomposition import PCA from sklearn.preprocessing import scale # convert data to nparray data = scale(np.array(features)) print data.shape n_samples, n_features = data.shape k = 3 k_means = KMeans(init='k-means++', n_clusters=k, n_init=10) k_means.fit(data) clustered_urls = [[], [], []] print clustered_urls it = np.nditer(k_means.labels_, flags=['f_index']) while not it.finished: #print it.index, it[0], urls[it.index] clustered_urls[it[0]].append(urls[it.index]) #print clustered_urls it.iternext() for idx in range(k): print 'count for %d: %d' % (idx, len(clustered_urls[idx])) print clustered_urls[0][:10] print print clustered_urls[1][:10] # plow multiple images """ plot image matrix """ # plot 3x3 picture matrix %matplotlib inline import numpy as np import matplotlib.pyplot as plt import requests import StringIO from matplotlib.pyplot import figure, show, axes, sci from PIL import Image def thumbnail(img): """ generate 250x250 square thumbnail """ THUMB_SIZE = 250, 250 width, height = img.size if width > height: delta = width - height left = int(delta/2) upper = 0 right = height + left lower = height else: delta = height - width left = 0 upper = int(delta/2) right = width lower = width + upper img = img.crop((left, upper, right, lower)) img.thumbnail(THUMB_SIZE, Image.ANTIALIAS) return img def plot_3x3(images, title = ''): """ given 9 images, plot them in 3x3 matrix """ plt.figure(figsize=(10,10)) Nr = 3 Nc = 3 i = 0 for image in images: i += 1 img_io = requests.get(image) plt.subplot(Nr, Nc, i) image = Image.open(StringIO.StringIO(img_io.content)) image = thumbnail(image) #img = io.imread(StringIO.StringIO(img_io.content)) plt.imshow(image) plt.show() # show the top 9 images for each cluster import skimage.io as io %matplotlib inline for cat in range(3): img_urls = clustered_urls[cat][:9] plot_3x3(img_urls, title = '9 samples for cluster %d' % cat) print '---------------------' # get the nearest neighbour pictures import numpy from scipy.spatial import distance def sim_search_k_images(images_features, search_feature): """ images_features is an array of the features search_feature is the feature to be searched for nearest neighbour use distance measure to get the k nearest neighbours and return the indices of the samples """ idx = 0 results = [] for feature in images_features: if numpy.array_equal(feature, search_feature): idx += 1 continue dst = distance.euclidean(search_feature, feature) results.append((idx, dst)) idx += 1 top_results = sorted(results, key=lambda x: x[1])[:9] top_ids = [image[0] for image in top_results] return top_ids ids = sim_search_k_images(data, data[56]) print ids img_urls = [urls[id] for id in ids] print img_urls plot_3x3(img_urls) ###Output _____no_output_____
Python/MNISTandOnlineNewsPopularity/.ipynb_checkpoints/MNISTandOnlineNewsPopularity-checkpoint.ipynb
###Markdown Data Analysis and Vis, HW 5*Adapted from COMP 5360 / MATH 4100, University of Utah, http://datasciencecourse.net/*Due: July 11In this homework, you will use classification methods to classify handwritten digits (Part 1) and predict the popularity of online news (Part 2). We hope these exercises will give you an idea of the broad usage of classificaiton methods. ###Code # imports and setup import pandas as pd import numpy as np import statistics from sklearn import tree, svm, metrics from sklearn.neighbors import KNeighborsClassifier from sklearn.model_selection import train_test_split, cross_val_predict, cross_val_score, KFold from sklearn.datasets import load_digits from sklearn.preprocessing import scale import matplotlib.pyplot as plt %matplotlib inline plt.rcParams['figure.figsize'] = (10, 6) plt.style.use('ggplot') ###Output _____no_output_____ ###Markdown Part1: MNIST handwritten digitsTHE MNIST handwritten digit dataset consists of images of handwritten digits, together with labels indicating which digit is in each image. You will see that images are just matrices with scalar values, and that we can use all the classifcation algorithms we studied on them. We saw these in class when we looked at clustering methods.Becaue both the features and the labels are present in this dataset (and labels for large datasets are generally difficult/expensive to obtain), this dataset is frequently used as a benchmark to compare various classification methods. For example, [this webpage](http://yann.lecun.com/exdb/mnist/) gives a comparison of a variety of different classification methods on MNIST (Note that the tests on this website are for higher resolution images than we'll use.) In this problem, we'll use scikit-learn to compare classification methods on the MNIST dataset. There are several versions of the MNIST dataset. We'll use the one that is built-into scikit-learn, described [here](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html). * Classes: 10 (one for each digit)* Samples total: 1797* Samples per class: $\approx$180* Dimensionality: 64 (8 pixels by 8 pixels)* Features: integers 0-16 (grayscale value; 0 is white, 16 is black)Here are some examples of the images. Note that the digits have been size-normalized and centered in a fixed-size ($8\times8$ pixels) image. Note that we will scale the data before running them through our algorithms, which will also alter their appearance when we plot them. You can read details about scaling and why it's important [here](http://scikit-learn.org/stable/modules/preprocessing.htmlstandardization-or-mean-removal-and-variance-scaling). ###Code digits = load_digits() X = scale(digits.data) y = digits.target print(type(X)) n_samples, n_features = X.shape n_digits = len(np.unique(digits.target)) print("n_digits: %d, n_samples %d, n_features %d" % (n_digits, n_samples, n_features)) # this is what one digit (a zero) looks like print("===\nThe raw data") print(digits.images[0]) print("===\nThe scaled data") print(X[0]) print("===\nThe digit") print(digits.target[0]) plt.figure(figsize= (10, 10)) for ii in np.arange(25): plt.subplot(5, 5, ii+1) plt.imshow(np.reshape(X[ii,:],(8,8)), cmap='Greys',interpolation='nearest') plt.axis('off') plt.show() ###Output _____no_output_____ ###Markdown You might find [this webpage](http://scikit-learn.org/stable/tutorial/basic/tutorial.html) helpful. Task 1.1: Classification with Support Vector Machines (SVM)1. Split the data into a training and test set using the command ```train_test_split(X, y, random_state=1, test_size=0.8)```+ Use SVM with an `rbf` kernel and parameter `C=100` to build a classifier using the *training dataset*.+ Using the *test dataset*, evaluate the accuracy of the model. Again using the *test dataset*, compute the confusion matrix. What is the most common mistake that the classifier makes? + Print all of these misclassified digits as images. + Using the 'cross_val_score' function, evaluate the accuracy of the SVM for 100 different values of the parameter C between 1 and 500. What is the best value? + Try to train and test the algorithm on the raw (non-scaled) data. What's your accuracy score? ###Code # build train/test and use svm.SVC with a radial basis function as the kernel X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1, test_size=0.8) rbfModel = svm.SVC(kernel='rbf', C=100) #fit the data using test dataset rbfModel.fit(X_train,y_train) print(rbfModel) rbfModel.get_params() #predicting y from the test data y_pred = rbfModel.predict(X_test) #compute the confusion matrix in order to see where the classifier is going wrong print(metrics.confusion_matrix(y_true = y_test, y_pred = y_pred)) print('Accuracy = ', metrics.accuracy_score(y_true = y_test, y_pred = y_pred)) misClassified = [x for x in range(len(y_pred)) if y_test[x] != y_pred[x]] print(misClassified) plt.figure(figsize=(15,15)) for i, val in enumerate(misClassified): plt.subplot(np.ceil(len(misClassified)/10), 10, i+1) plt.imshow(np.reshape(X_test[val,:], (8,8)), cmap='Greys', interpolation='nearest') plt.axis('off') plt.show() #This seems to suggest that the testing went well, but this seems odd. I'd think we should be far less accurate for i in range (1, 500, 5): model = svm.SVC(kernel='rbf', C=i).fit(X_test,y_test) y_predi = model.predict(X_test) # score = cross_val_score(estimator = model, X = X_test, y = y_test, cv=5, scoring='accuracy') # print(metrics.confusion_matrix(y_true = y, y_pred=y_predi)) print('Accuracy = ', cross_val_score(estimator = model, X = X_test, y = y_test, cv=5, scoring='accuracy'), 'C = ', i) #6 unscaled data Xu = digits.data yu = digits.target X_train_u, X_test_u, y_train_u, y_test_u = train_test_split(Xu, yu, random_state=1, test_size=0.8) for i in range (1, 500, 5): model_u = svm.SVC(kernel='rbf', C=i).fit(X_test_u,y_test_u) y_pred_u = model.predict(Xu) # score = cross_val_score(estimator = model, X = X_test, y = y_test, cv=5, scoring='accuracy') # print(metrics.confusion_matrix(y_true = y, y_pred=y_predi)) print('Accuracy = ', cross_val_score(estimator = model_u, X = X_test_u, y = y_test_u, cv=5, scoring='accuracy'), 'C = ', i) ###Output Accuracy = [ 0.42123288 0.49484536 0.42307692 0.41052632 0.39084507] C = 1 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 6 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 11 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 16 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 21 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 26 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 31 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 36 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 41 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 46 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 51 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 56 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 61 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 66 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 71 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 76 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 81 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 86 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 91 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 96 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 101 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 106 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 111 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 116 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 121 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 126 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 131 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 136 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 141 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 146 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 151 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 156 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 161 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 166 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 171 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 176 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 181 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 186 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 191 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 196 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 201 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 206 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 211 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 216 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 221 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 226 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 231 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 236 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 241 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 246 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 251 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 256 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 261 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 266 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 271 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 276 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 281 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 286 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 291 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 296 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 301 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 306 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 311 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 316 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 321 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 326 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 331 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 336 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 341 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 346 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 351 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 356 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 361 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 366 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 371 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 376 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 381 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 386 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 391 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 396 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 401 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 406 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 411 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 416 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 421 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 426 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 431 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 436 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 441 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 446 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 451 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 456 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 461 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 466 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 471 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 476 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 481 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 486 Accuracy = [ 0.48287671 0.53608247 0.47552448 0.44210526 0.44014085] C = 491 ###Markdown **Your Interpretation**: The best value for Accuracy was .962159154457986. This was the case for all values for C from 2 - 500. The worst value was for C = 1. This suggests that no matter the value of C, the result is the same. Task 1.2: Prediction with k-nearest neighborsRepeat task 1.1 using k-nearest neighbors (k-NN). In part 1, use k=10. In part 3, find the best value of k. ###Code # your solution goes here knnModel = KNeighborsClassifier(n_neighbors=10).fit(X_train,y_train) y_pre = knnModel.predict(X_test) print(metrics.confusion_matrix(y_true = y_test, y_pred = y_pre)) print('Accuracy = ', metrics.accuracy_score(y_true = y_test, y_pred = y_pre)) misClassifiedK = [x for x in range(len(y_pre)) if y_test[x] != y_pre[x]] print(misClassified) plt.figure(figsize=(15,15)) for i, val in enumerate(misClassifiedK): plt.subplot(np.ceil(len(misClassifiedK)/10), 10, i+1) plt.imshow(np.reshape(X_test[val,:], (8,8)), cmap='Greys', interpolation='nearest') plt.axis('off') plt.show() Cs = np.linspace(1, 100, 50) Accuracies = np.zeros(Cs.shape[0]) for i,k in enumerate(Cs): mod = KNeighborsClassifier(n_neighbors=int(k)) # print(metrics.confusion_matrix(y_true = y_train, y_pred=y_prediction)) scores = cross_val_score(estimator = mod, X = X, y = y, cv=5, scoring='accuracy') Accuracies[i] = scores.mean() plt.plot(Cs,Accuracies) plt.xticks(np.arange(0, 100, 5)) best = Cs[np.argmax(Accuracies)] print('Best = ', best) plt.show() # Xu = digits.data # yu = digits.target # X_train_u, X_test_u, y_train_u, y_test_u = train_test_split(Xu, yu, random_state=1, test_size=0.8) kuCs = np.linspace(1, 100, 50) kuAccuracies = np.zeros(kuCs.shape[0]) for i,k in enumerate(kuCs): mod_ku = KNeighborsClassifier(n_neighbors=int(k)) # print(metrics.confusion_matrix(y_true = y_train, y_pred=y_prediction)) scores = cross_val_score(estimator = mod_ku, X = Xu, y = yu, cv=5, scoring='accuracy') kuAccuracies[i] = scores.mean() plt.plot(kuCs,kuAccuracies) plt.xticks(np.arange(0, 100, 5)) kubest = kuCs[np.argmax(kuAccuracies)] print('Best = ', kubest) plt.show() ###Output Best = 3.02040816327 ###Markdown **Your Interpretation**: Looks like the best K for this dataset was around 3. Part 2: Popularity of online newsFor this problem, you will use classification tools to predict the popularity of online news based on attributes such as the length of the article, the number of images, the day of the week that the article was published, and some variables related to the content of the article. You can learn details about the datasetat the[UCI Machine Learning Repository](https://archive.ics.uci.edu/ml/datasets/Online+News+Popularity). This dataset was first used in the following conference paper: K. Fernandes, P. Vinagre and P. Cortez. A Proactive Intelligent Decision Support System for Predicting the Popularity of Online News. *Proceedings of the 17th EPIA 2015 - Portuguese Conference on Artificial Intelligence* (2015).The dataset contains variables describing 39,644 articles published between January 7, 2013 and Januyary 7, 2015 on the news website, [Mashable](http://mashable.com/). There are 61 variables associated with each article. Of these, 58 are *predictor* variables, 2 are variables that we will not use (url and timedelta), and finally the number of shares of each article. The number of shares is what we will use to define whether or not the article was *popular*, which is what we will try to predict. You should read about the predictor variables in the file *OnlineNewsPopularity.names*. Further details about the collection and processing of the articles can be found in the conference paper. Task 2.1 Import the data * Use the pandas.read_csv() function to import the dataset.* To us[scikit-learn](http://scikit-learn.org), we'll need to save the data as a numpy array. Use the *DataFrame.as_matrix()* command to export the predictor variables as a numpy array called *X* this array should not include our target variable (the number of shares). We don't need the url and timedelta, so let's drop these columns. * Export the number of shares as a separate numpy array, called *shares*. We'll define an article to be popular if it received more shares than the median number of shares. Create a binary numpy array, *y*, which indicates whether or not each article is popular. ###Code # Your code here. Note the data and description are in the OnlineNewsPopularity directory dirtyCsv = pd.read_csv("/Users/znickle/znickle/DataAnalysesAndVisualization/Homework/Homework5/OnlineNewsPopularity/OnlineNewsPopularity.csv") list(dirtyCsv) #the following are the instructions above (create np array called shares, delete url and timedelta then create the remaining colums as an np array) del dirtyCsv['url'] del dirtyCsv[' timedelta'] shares = dirtyCsv[' shares'] shares = shares.as_matrix() del dirtyCsv[' shares'] SX = dirtyCsv.as_matrix() shares.dtype #Create a binary numpy array, y, which indicates whether or not each article is popular def isPopular(x, popValue): if x >= popValue: return 1 else: return 0 print(shares) originalShares = shares.copy() print(originalShares) popularThreshold = statistics.median(shares) print('Popular Threshold: ', popularThreshold) for i in range(0, len(shares)): shares[i] = isPopular(shares[i], popularThreshold) print(shares) print(originalShares) ###Output [ 593 711 1500 ..., 1900 1100 1300] [ 593 711 1500 ..., 1900 1100 1300] Popular Threshold: 1400.0 [0 0 1 ..., 1 0 0] [ 593 711 1500 ..., 1900 1100 1300] ###Markdown Task 2.2 Exploratory data analysis First check to see if the values are reasonable. What are the min, median, and maximum number of shares? ###Code minimum = originalShares.min() median = statistics.median(originalShares) maximum = originalShares.max() print('Minimum: ', minimum) print('Maximum: ', maximum) print('Median: ', median) print(shares) ###Output [0 0 1 ..., 1 0 0] ###Markdown Task 2.3 Classification using k-NNDevelop a k-NN classification model for the data. Use cross validation to choose the best value of k. What is the best accuracy you can obtain on the test data? ###Code SX = scale(SX) sy = shares print(type(SX)) sn_samples, sn_features = SX.shape sn_digits = len(np.unique(sy)) print("sn_digits: %d, sn_samples %d, sn_features %d" % (sn_digits, sn_samples, sn_features)) X_train_s, X_test_s, y_train_s, y_test_s = train_test_split(SX, sy, random_state=1, test_size=0.8) sModel = KNeighborsClassifier(n_neighbors=10).fit(X_train_s,y_train_s) y_s_pre = sModel.predict(X_test_s) print(metrics.confusion_matrix(y_true = y_test_s, y_pred = y_s_pre)) print('Accuracy = ', metrics.accuracy_score(y_true = y_test_s, y_pred = y_s_pre)) xCopy = SX[0:5000] yCopy = sy[0:5000] kss = np.linspace(1, 100, 50) sAccuracies = np.zeros(kss.shape[0]) for i,k in enumerate(kss): s_mod = KNeighborsClassifier(n_neighbors=int(k)) # print(metrics.confusion_matrix(y_true = y_train, y_pred=y_prediction)) scores_s = cross_val_score(estimator = s_mod, X = xCopy, y = yCopy, cv=5, scoring='accuracy') sAccuracies[i] = scores_s.mean() plt.plot(kss,sAccuracies) plt.xticks(np.arange(0, 100, 5)) sBest = kss[np.argmax(sAccuracies)] print('Best = ', sBest) plt.show() ###Output Best = 100.0 ###Markdown **Interpretation:** Best accuracy score for knn is 93.9387755102 Task 2.4 Classification using SVMDevelop a support vector machine classification model for the data. * SVM is computationally expensive, so start by using only a fraction of the data, say 5,000 articles. * Experimt with different Cs. Which is the best value for C?Note that it takes multiple minutes per value of C to run on the whole dataset! ###Code #use xCopy and yCopy in order to only use 5,000 articles /X_train_s, X_test_s, y_train_s, y_test_s for test/train # for i in range (1, 500, 5): # s_model = svm.SVC(kernel='rbf', C=i).fit(X_test_s,y_test_s) # y_predi = s_model.predict(X_test_s) # # score = cross_val_score(estimator = model, X = X_test, y = y_test, cv=5, scoring='accuracy') # # print(metrics.confusion_matrix(y_true = y, y_pred=y_predi)) # print('Accuracy = ', cross_val_score(estimator = model, X = X_test_s, y = y_test_s, cv=5, scoring='accuracy'), 'C = ', i) svm_s = np.linspace(.1, 2.0,20) sv_Accuracies = np.zeros(svm_s.shape[0]) for i,C in enumerate(svm_s): sv_model = svm.SVC(kernel='rbf', C=C) # print(metrics.confusion_matrix(y_true = y_train, y_pred=y_prediction)) sv_scores = cross_val_score(estimator = sv_model, X = xCopy, y = yCopy, cv=5, scoring='accuracy') sv_Accuracies[i] = sv_scores.mean() print(i) plt.plot(svm_s,sv_Accuracies) plt.xticks(np.arange(0, 20, 1)) sv_best = svm_s[np.argmax(sv_Accuracies)] print('Best = ', sv_best) plt.show() ###Output 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 Best = 0.3 ###Markdown *Best value for C is .1* Task 2.5 Classification using decision treesDevelop a decision tree classification model for the data. Use cross validation to choose good values of the max tree depth (*max_depth*) and minimum samples split (*min_samples_split*). ###Code # Your code here X_train_d, X_test_d, y_train_d, y_test_d = train_test_split(SX, sy, random_state=1, test_size=0.8) decisionTree = tree.DecisionTreeClassifier() decisionTree = decisionTree.fit(X_train_d, y_train_d) y_predict_train = decisionTree.predict(X_train_d) print('Accuracy on training data= ', metrics.accuracy_score(y_true = y_train_d, y_pred = y_predict_train)) y_predict_d = decisionTree.predict(X_test_d) print('Accuracy on test data= ', metrics.accuracy_score(y_true = y_test_d, y_pred = y_predict_d)) md = [1, 3, 5, 7, 9] mss = [15, 30, 50, 75, 100] bestSD = [0,0] bestScoreSoFar = 0 for x in md: for y in mss: decisionTree = tree.DecisionTreeClassifier(max_depth=x, min_samples_split=y) # decisionTree = decisionTree.fit(X_train_d, y_train_d) scores_d = cross_val_score(estimator = decisionTree, X = X_train_d, y = y_train_d, cv = 5, scoring='accuracy') meanScore_d = scores_d.mean() if meanScore_d > bestScoreSoFar: bestScoreSoFar = meanScore_d bestSD = [x, y] print(bestScoreSoFar) print('Max Depth ', bestSD[0]) print('Min Sample Split ', bestSD[1]) ###Output 0.629541314597 Max Depth 7 Min Sample Split 100
MLCourse/Tensorflow.ipynb
###Markdown Introducing TensorflowBe sure to "conda install tensorflow" or "conda install tensorflow-gpu" first! The world's simplest Tensorflow applicationLet's begin by writing a really simple program to illustrate Tensorflow's main concepts. We'll set up two Variables, named "a" and "b", which each contain a tensor which contains a single value - the number 1, and the number 2.We then create a graph "f" that adds these two tensors together. But "f = a + b" just creates the graph; it doesn't actually perform the addition yet.Next we need to initialize any global variables before we run the graph.And finally, we create a Tensorflow Session object, run our variable initializer, and execute the graph with eval(). This returns the sum of 1 + 2 in a rather complex, yet highly scalable manner :) ###Code import tensorflow as tf a = tf.Variable(1, name="a") b = tf.Variable(2, name="b") f = a + b tf.print("The sum of a and b is", f) ###Output The sum of a and b is 3 ###Markdown And now for something more interesting: Handwriting recognitionThe standard example for machine learning these days is the MNIST data set, a collection of 70,000 handwriting samples of the numbers 0-9. Our challenge - to predict which number each handwritten image represents.Although we'll talk about neural networks that are specifically well suited for image recognition later, we actually don't need to go there for this relatively simple task. We can achieve decent results without a whole lot of code.Each image is 28x28 grayscale pixels, so we can treat each image as just a 1D array, or tensor, of 784 numbers. As long as we're consistent in how we flatten each image into an array, it'll still work. Yes, it would be even better if we could preserve the 2D structure of the data while training - but we'll get there later.Let's start by importing the data set, which conveniently is part of tensorflow itself. We will reshape the images into the 1D arrays of 784 pixels that we expect, and the label data into one-hot-encoded categorical format (which we will convert during our loss function defination), which we'll talk about in a second: ###Code # Prepare MNIST data. import numpy as np import tensorflow as tf from tensorflow.keras.datasets import mnist # MNIST dataset parameters num_classes = 10 # total classes (0-9 digits) num_features = 784 # data features (img shape: 28*28) (x_train, y_train), (x_test, y_test) = mnist.load_data() # Convert to float32 x_train, x_test = np.array(x_train, np.float32), np.array(x_test, np.float32) # Flatten images to 1-D vector of 784 features (28*28) x_train, x_test = x_train.reshape([-1, num_features]), x_test.reshape([-1, num_features]) # Normalize images value from [0, 255] to [0, 1] x_train, x_test = x_train / 255., x_test / 255. ###Output _____no_output_____ ###Markdown MNIST provides 60,000 samples in a training data set, and 10,000 samples in a test data set.If you're new to the concept of train/test - it's important to evaluate the performance of our neural network using data it's never seen before. Otherwise it's kinda like giving students a math test for problems they already have the answers for. So, we use a completely different set of images to train our neural network from the images used for testing its accuracy.The training images are therefore a tensor of shape [60,000, 784] - 60,000 instances of 784 numbers that represent each image. The training labels are a one-dimensional tensor of 60,000 labels that range from 0 to 9.Let's define a little function to let us visualize what the input data looks like, and pick some random training image to see what it is we're up against: ###Code %matplotlib inline import matplotlib.pyplot as plt def display_sample(num): #Print this sample's label label = y_train[num] #Reshape the 784 values to a 28x28 image image = x_train[num].reshape([28,28]) plt.title('Sample: %d Label: %d' % (num, label)) plt.imshow(image, cmap=plt.get_cmap('gray_r')) plt.show() display_sample(1000) ###Output _____no_output_____ ###Markdown So, you can see the training label for image 1000, as well as what this particular sample looks like. You can tell that some of the training data would even be challenging for a human to classify!Go ahead and try different input images to get a feel of the data we're given. Any value between 0 and 60,000 will work.As a reminder, we're flattening each image to a 1D array of 784 (28 x 28) numerical values. Each one of those values will be an input node into our deep neural network. Let's visualize how the data is being fed into it just to drive that point home: ###Code images = x_train[0].reshape([1,784]) for i in range(1, 500): images = np.concatenate((images, x_train[i].reshape([1,784]))) plt.imshow(images, cmap=plt.get_cmap('gray_r')) plt.show() ###Output _____no_output_____ ###Markdown This is showing the first 500 training samples, one on each row. Imagine each pixel on each row getting fed into the bottom layer of a neural network 768 neurons (or "units") wide as we train our neural network.We will now define few training parameters (or "hyperparameters") and use tf.data API to shuffle our data and divide it into batches. Think of these as parameters - we build up our neural network model without knowledge of the actual data that will be fed into it; we just need to construct it in such a way that our data will fit in.We'll use a Dataset within Tensorflow to wrap our traning features and labels, and use functions of the Dataset to randomly shuffle it and batch it up into smaller chunks for each iteration of training. ###Code # Training parameters. learning_rate = 0.001 training_steps = 3000 batch_size = 250 display_step = 100 # Network parameters. n_hidden = 512 # Number of neurons. # Use tf.data API to shuffle and batch data. train_data = tf.data.Dataset.from_tensor_slices((x_train, y_train)) train_data = train_data.repeat().shuffle(60000).batch(batch_size).prefetch(1) ###Output _____no_output_____ ###Markdown So let's start setting up that artificial neural network. We'll start by creating variables to store and keep track of weights and biases of different layers.We'll need an input layer with one node per input pixel per image, or 784 nodes. That will feed into a hidden layer of some arbitrary size - let's pick 512, given by n_hidden. That hidden layer will output 10 values, given by num_classes, corresonding to scores for each classification to be fed into softmax. ###Code # Store layers weight & bias # A random value generator to initialize weights initially random_normal = tf.initializers.RandomNormal() weights = { 'h': tf.Variable(random_normal([num_features, n_hidden])), 'out': tf.Variable(random_normal([n_hidden, num_classes])) } biases = { 'b': tf.Variable(tf.zeros([n_hidden])), 'out': tf.Variable(tf.zeros([num_classes])) } ###Output _____no_output_____ ###Markdown Now let's set up the neural network itself. We'll feed our input data into the first layer of our neural network. All this layer does is multiply these inputs by our weight "h" tensor which will be learned over time.Then we'll feed that into our hidden layer, which applies the sigmoid activation function to the weighted inputs with our learned biases added in as well.Finally our output layer, called out_layer, multiplies in the learned weights of the hidden layer and adds in the hidden layer's bias term. ###Code # Create model. def neural_net(inputData): # Hidden fully connected layer with 512 neurons. hidden_layer = tf.add(tf.matmul(inputData, weights['h']), biases['b']) # Apply sigmoid to hidden_layer output for non-linearity. hidden_layer = tf.nn.sigmoid(hidden_layer) # Output fully connected layer with a neuron for each class. out_layer = tf.matmul(hidden_layer, weights['out']) + biases['out'] # Apply softmax to normalize the logits to a probability distribution. return tf.nn.softmax(out_layer) ###Output _____no_output_____ ###Markdown Make sure you noodle on the above block. This sets up a deep neural network like the one we talked about in our slides.output layerhidden layerinput layerNext we will define our loss function for use in measuring our progress in gradient descent: cross-entropy, which applies a logarithmic scale to penalize incorrect classifications much more than ones that are close. In this function, y_pred is the output of our final layer, and we're comparing that against the target labels used for training in y_true.To compare our known "true" labels of 0-9 to the output of our neural network, we need to convert the labels to "one-hot" encoding. Our output layer has a neuron for each possible label of 0-9, not a single neuron with an integer in it. For example, let's say a known "true" label for an image is 1. We would represent that in one-hot format as [0, 1, 0, 0, 0, 0, 0, 0, 0, 0] (remember we start counting at 0.) This makes it easier to compare the known label to the output neurons. ###Code def cross_entropy(y_pred, y_true): # Encode label to a one hot vector. y_true = tf.one_hot(y_true, depth=num_classes) # Clip prediction values to avoid log(0) error. y_pred = tf.clip_by_value(y_pred, 1e-9, 1.) # Compute cross-entropy. return tf.reduce_mean(-tf.reduce_sum(y_true * tf.math.log(y_pred))) ###Output _____no_output_____ ###Markdown Now we will set up our stocastic gradient descent optimizer, based on our previously defined hyperparameters and our loss function defined above.That learning rate is an example of a hyperparameter that may be worth experimenting with and tuning.We will be using Tensorflow 2.0 new feature of Gradient Tape (to know futher why we use this, follow this amazing answer given on stackoverflow, https://stackoverflow.com/a/53995313/8804853) It's the new way of setting up neural nets from scratch in Tensorflow 2. ###Code optimizer = tf.keras.optimizers.SGD(learning_rate) def run_optimization(x, y): # Wrap computation inside a GradientTape for automatic differentiation. with tf.GradientTape() as g: pred = neural_net(x) loss = cross_entropy(pred, y) # Variables to update, i.e. trainable variables. trainable_variables = list(weights.values()) + list(biases.values()) # Compute gradients. gradients = g.gradient(loss, trainable_variables) # Update W and b following gradients. optimizer.apply_gradients(zip(gradients, trainable_variables)) ###Output _____no_output_____ ###Markdown Next we'll want to train our neural network and measure its accuracy. First let's define some methods for measuring the accuracy of our trained model. correct_prediction will look at the output of our neural network (in digit_weights) and choose the label with the highest value, and see if that agrees with the target label given. During testing, digit_weights will be our prediction based on the test data we give the network, and target_labels is a placeholder that we will assign to our test labels. Ultimately this gives us a 1 for every correct classification, and a 0 for every incorrect classification."accuracy" then takes the average of all the classifications to produce an overall score for our model's accuracy. ###Code # Accuracy metric. def accuracy(y_pred, y_true): # Predicted class is the index of highest score in prediction vector (i.e. argmax). correct_prediction = tf.equal(tf.argmax(y_pred, 1), tf.cast(y_true, tf.int64)) return tf.reduce_mean(tf.cast(correct_prediction, tf.float32), axis=-1) ###Output _____no_output_____ ###Markdown Let's train this thing and see how it works! Tensorflow 2 removed the need to set up a session object an explicitly initialize your varaibles. So we can jump right into training our network in 3000 steps (or "epochs", given by training_steps) with batches of 250 samples set up earlier in our training data. At each step, we assign run our optimization function on the current batch of images and labels from the training data.At every 100 epochs (given by display_step), we print out the current values of the loss function and our accuracy metric, by comparing our predicted labels against the known "true" labels. To do this we run our neural network using our trained weights and biases at each point on the current batch of training images, and compute cross entropy and accuracy of the resulting predictions ("pred") to the known correct labels ("batch_y"). ###Code # Run training for the given number of steps. for step, (batch_x, batch_y) in enumerate(train_data.take(training_steps), 1): # Run the optimization to update W and b values. run_optimization(batch_x, batch_y) if step % display_step == 0: pred = neural_net(batch_x) loss = cross_entropy(pred, batch_y) acc = accuracy(pred, batch_y) print("Training epoch: %i, Loss: %f, Accuracy: %f" % (step, loss, acc)) # Test model on validation set. pred = neural_net(x_test) print("Test Accuracy: %f" % accuracy(pred, y_test)) ###Output Test Accuracy: 0.931700 ###Markdown You should have about 93% accuracy. Not bad! But hey, we're just starting.Let's take a look at some of the misclassified images and see just how good or bad our model is, compared to what your own brain can do. We'll go through the first 200 test images and look at the ones that are misclassified: ###Code n_images = 200 test_images = x_test[:n_images] test_labels = y_test[:n_images] predictions = neural_net(test_images) for i in range(n_images): model_prediction = np.argmax(predictions.numpy()[i]) if (model_prediction != test_labels[i]): plt.imshow(np.reshape(test_images[i], [28, 28]), cmap='gray_r') plt.show() print("Original Labels: %i" % test_labels[i]) print("Model prediction: %i" % model_prediction) ###Output _____no_output_____
nlp-tutorial-part-ii/sentiment_with_spark_nlp.ipynb
###Markdown Sentiment Analysis with [Spark NLP](https://nlp.johnsnowlabs.com/?gclid=CjwKCAjwr7X4BRA4EiwAUXjbt8SXPLqhOytb-o6ZpGC67FuhfJkiaI3GR2EvdTItYmQXEK2gIRfmlBoCzt8QAvD_BwE)** In this second part of our tutorial, we will use Spark NLP, an industry level open source NLP library. After implementing the preprocessing steps as we did last time with NLTK, we will use the pretrained sentiment_analyzer from Spark NLP to see an example of how to use a pretrained model for sentiment analysis. Our goal is to introduce you to one of the most robust NLP tools and libraries that you can continue learning more about as you keep experimenting with NLP techniques. *Please note, in order to have a full grasp of Spark NLP, as well as any other NLP library or tool, you will first need to get familiarized with their documentation and concepts. To learn more about Spark NLP visit the [documentation](https://nlp.johnsnowlabs.com/docs/en/concepts)* + We will first setup the necessary colab environment. + Run this block only if you are inside Google Colab. ###Code import os # Install java ! apt-get install -y openjdk-8-jdk-headless -qq > /dev/null os.environ["JAVA_HOME"] = "/usr/lib/jvm/java-8-openjdk-amd64" os.environ["PATH"] = os.environ["JAVA_HOME"] + "/bin:" + os.environ["PATH"] ! java -version # Install pyspark ! pip install --ignore-installed pyspark==2.4.4 # Install Spark NLP ! pip install --ignore-installed spark-nlp==2.5.0 ###Output _____no_output_____ ###Markdown + Next, we will mount Google colab by running the cell below and clicking on the URL to get the authorization code. + If you are coding along, copy and paste your authorization code from the url that appears after you run the cell below to the provided box. If you are using Jupyter Notebook, you don't need to do this step. ###Code from google.colab import drive drive.mount("content") ###Output _____no_output_____ ###Markdown + We have now set up our environment on Google colab and can continue with the next steps, using Spark NLP to do sentiment analysis. 1. Sentiment Analysis Using the pretrained PipelineUsing a pretrained pipeline with spark dataframes we can also use the pipeline through a spark dataframe. We just need to create first a spark dataframe with a column named “text” that will work as the input for the pipeline and then use the `.transform()` method to run the pipeline over that dataframe and store the outputs of the different components in a spark dataframe.In this example, we are not doing any training or using a model that we created, but we simply use Spark NLP, out of the box, to tell us what the sentiment of a text that we give to it is. ###Code import sys import sparknlp from pyspark.sql import SparkSession from pyspark.ml import Pipeline from pyspark.sql.functions import array_contains from pyspark.ml import Pipeline, PipelineModel from sparknlp.annotator import * from sparknlp.pretrained import PretrainedPipeline ###Output _____no_output_____ ###Markdown + We will now start a spark nlp session, as well as check for versions of both Apache spark and spark NLP. Running this cell without an error means we have installed the necessary packages correctly. ###Code spark = sparknlp.start() print("Spark NLP version: ", sparknlp.version()) print("Apache Spark version: ", spark.version) ###Output _____no_output_____ ###Markdown + Load the predefined pipeline provided in Spark NLP containing all the annotators we need to run a sentiment analysis on a piece of raw text.+ + The next step in the process is to initialize the pretrained model from Spark NLP. For sentiment analysis, we will use the named `analyze_sentiment` for the English language. + In this example, we can simply use a text that could be provided by a user, a client, or any piece of text that you would like to get the sentiment associated to it. ###Code pipeline = ... ###Output _____no_output_____ ###Markdown + Create random list of sentences that you would like the model to analyze. ###Code dataset = ["Since there is No Vaccine for COVID-19 I have no choice but to wear my mask to protect, my family, myself and others. fact is many people have died from COVID-19 are you willing to take that risk, and possibly even put your family in harms way?", "Their is NO Vaccine so wear the MASK!"] # Alternatively, you can put this tiny data into a spark dataframe # data = spark.createDataFrame([["Since there is No Vaccine for COVID-19 I have no choice but to wear my mask to protect, my family, myself and others. fact is many people have died from COVID-19 are you willing to take that risk, and possibly even put your family in harms way?", "Their is NO Vaccine so wear the MASK!"]]).toDF('text') # Annotate our tiny dataset result = ... [(r['sentence'], r['sentiment']) for r in result] # We can also view each stage in the pipeline by simply printing it. result ###Output _____no_output_____ ###Markdown 2. Sentiment Analysis Using A Pretrained Model, SentimentDL ###Code import time import sys import os import pandas as pd from pyspark.ml import Pipeline, PipelineModel from pyspark.sql import SparkSession from pyspark.sql.functions import * from sparknlp.annotator import * from sparknlp.base import DocumentAssembler, Finisher pd.set_option('display.max_columns', None) pd.set_option('display.max_rows', None) ###Output _____no_output_____ ###Markdown + Let's pull in our twitter dataset that we used last time. ###Code df = pd.read_csv('/content/content/My Drive/Colab Notebooks/nlp-tutorial-part-ii/data/covid19_tweets.csv') df.head() ###Output _____no_output_____ ###Markdown + Pick only the relevant columns for the sentiment analysis task to reduce data size. + pretrained pipelines expect the input column to be named “text”. ###Code df = df[['tweet', 'sentiment']] df = ... df.head() ###Output _____no_output_____ ###Markdown + Split the dataset into train and test sets, save these subsets into two different csv files, using pandas and numpy + This can also be done with `scikit-learn` library as we did last time. This is simply another way of splitting our data if you are trying to reduce the overhead of your code. ###Code import numpy as np # Randomly select %80 of the dataset and use it for training. mask = np.random.rand(len(df)) < 0.8 trainDataset = ... # Take the complement of the training set we have split above (i.e %20 of the data for testing). testDataset = ... #save these subsets (train & test) into csv trainDataset.to_csv('/content/content/My Drive/Colab Notebooks/nlp-tutorial-part-ii/data/trainDataset.csv', index=False) testDataset.to_csv('/content/content/My Drive/Colab Notebooks/nlp-tutorial-part-ii/data/testDataset.csv', index=False) ###Output _____no_output_____ ###Markdown + See how many rows of data we have in training and testing sets ###Code trainDataset.shape testDataset. ... trainDataset.head() ###Output _____no_output_____ ###Markdown + Convert the data into a pyspark dataframe to make it compatible with Spark NLP ###Code spark_train = ... spark_test = ... spark_train.show(n=10, truncate=True) ###Output _____no_output_____ ###Markdown + Setup the Pipeline for the model + With any new tool or library libray, there is often some specific terminology that you need to learn. In this case, the term we need to pay attention to is "pipeline," + *In Machine Learning, a pipeline is often defined as a sequence of algorithms to process and learn from data. It is a sequence of stages, and in Spark NLP, each stage is either a Transformer or an Estimator. These stages are run in order, and the input DataFrame is transformed as it passes through each stage. That is, the data are passed through the fitted pipeline in order. For more details on Spark Pipelines that Spark NLP uses, please visit [here](http://spark.apache.org/docs/latest/ml-pipeline.html).* ###Code from pyspark.ml import Pipeline from sparknlp.annotator import * from sparknlp.common import * from sparknlp.base import * document = DocumentAssembler()\ .setInputCol("text")\ .setOutputCol("document") use = UniversalSentenceEncoder.pretrained() \ .setInputCols(["document"])\ .setOutputCol("sentence_embeddings") # the classes/labels/categories are in sentiment column sentimentdl = SentimentDLApproach()\ .setInputCols(["sentence_embeddings"])\ .setOutputCol("class")\ .setLabelColumn("sentiment")\ .setMaxEpochs(3)\ .setEnableOutputLogs(True) pipeline = Pipeline( stages = [ document, use, sentimentdl ]) ###Output _____no_output_____ ###Markdown + Train the model on our training dataset ###Code pipelineModel = ... ###Output _____no_output_____ ###Markdown Save and load pre-trained SentimentDL model ###Code pipelineModel.stages[-1].write().overwrite().save('./tmp_sentimentdl_model') ###Output _____no_output_____ ###Markdown + Use our pre-trained SentimentDLModel in a pipeline ###Code # In a new pipeline we can load it for prediction document = DocumentAssembler()\ .setInputCol("text")\ .setOutputCol("document") use = UniversalSentenceEncoder.pretrained() \ .setInputCols(["document"])\ .setOutputCol("sentence_embeddings") sentimentdl = SentimentDLModel.load("./tmp_sentimentdl_model") \ .setInputCols(["sentence_embeddings"])\ .setOutputCol("class") pipeline = Pipeline( stages = [ document, use, sentimentdl ]) from pyspark.sql.types import StringType dfTest = spark.createDataFrame([ "I am glad I read this book on the latest trends in Natural Language Processing.", "This movie is ridiculous. I wish I hadn't come to watch it." ], StringType()).toDF("text") prediction = ... prediction.select("class.result").show() prediction.select("class.metadata").show(truncate=False) ###Output _____no_output_____ ###Markdown Evaluation Similar to other NLP libraries, we can use the evaluation metrics for NLP, evaluating our Spark NLP sentimentdl model. For this, we will first run the model on our test set. We leave it to you for practice to experiment with evaluations metrics in `scikit-learn` library. (Hint: Revisit Part I notebook) ###Code predictions = ... predictions.select(...) ###Output _____no_output_____ ###Markdown + SentimentDL has the ability to accept a threshold to set a label on any result that is less than that number. By default the threshold is set on 0.6 and everything below that will be assigned as neutral. You can change this label with `setThresholdLabel` attribute.+ We need to filter neutral results since we don't have any in the original test dataset to compare with. ###Code predictions_df = predictions.select('sentiment','text',"class.result").toPandas() predictions_df = predictions_df[predictions_df['result'] != 'neutral'] predictions_df.head() from sklearn.metrics import accuracy_score #alternatively from sklearn.metrics import classification_report # Your code here ###Output _____no_output_____
workflow/RGI02.ipynb
###Markdown RGI02 (Western Canada and USA)F. Maussion ###Code import pandas as pd import geopandas as gpd import subprocess import matplotlib.pyplot as plt import matplotlib.patches as mpatches import seaborn as sns import numpy as np from utils import mkdir, submission_summary, needs_size_filter, size_filter, plot_map, plot_date_hist import os ###Output _____no_output_____ ###Markdown Files and storage paths ###Code # Region of interest reg = 2 # go down from rgi7_scripts/workflow data_dir = '../../rgi7_data/' # Level 2 GLIMS files l2_dir = os.path.join(data_dir, 'l2_sel_reg_tars') # Output directories output_dir = mkdir(os.path.join(data_dir, 'l3_rgi7a')) output_dir_tar = mkdir(os.path.join(data_dir, 'l3_rgi7a_tar')) # RGI v6 file for comparison later rgi6_reg_file = os.path.join(data_dir, 'l0_RGIv6', '02_rgi60_WesternCanadaUS.zip') # Specific to this region: boxes where data has to be selected differently support_dir = os.path.join(data_dir, 'l0_support_data') ###Output _____no_output_____ ###Markdown Load the input data ###Code # Read L2 files shp = gpd.read_file('tar://' + l2_dir + f'/RGI{reg:02d}.tar.gz/RGI{reg:02d}/RGI{reg:02d}.shp') ###Output _____no_output_____ ###Markdown List of submissions ###Code sdf, df_classes = submission_summary(shp) sdf ###Output _____no_output_____ ###Markdown Notes based on inidivual submission evaluations: - 635 is for all glaciers above 60°N (was used in RGI6)- 624 is a lonely glacier on the close to Region 01 border, it was misplaced in RGI6 and is already available in 623!- 623 is for the rest of the glaciers in Canada not covered by 635. The version in GLIMS has several issues ([GH issue](https://github.com/GLIMS-RGI/glims_issue_tracker/issues/8))- 619: not clear what this is. the 5 outlines are already available in 614- 618: an intermediate inventory for the colorado range- 617: a further intermediate inventory for the colorado range- 616: used by RGI for Colorado to replace 614 in this region (make a shape to select them)- 744: all the rest of USA- 721, 722: update of two outlines by Bruce which we need to use ###Code # # Optional: write out selection in intermediate shape files for manual GIS review # tmp_output_dir = mkdir(os.path.join(data_dir, 'l0_tmp_data', f'rgi{reg:02d}_inventories')) # tmp_output_dir_tar = mkdir(os.path.join(data_dir, 'l0_tmp_data')) # for subid in shp.subm_id.unique(): # s_loc = shp.loc[shp.subm_id == subid] # s_loc.to_file(tmp_output_dir + f'/subm_{int(subid):03d}.shp') # print('Taring...') # print(subprocess.run(['tar', '-zcvf', f'{tmp_output_dir_tar}/rgi{reg:02d}_inventories.tar.gz', '-C', # os.path.join(data_dir, 'l0_tmp_data'), f'rgi{reg:02d}_inventories'])) ###Output _____no_output_____ ###Markdown Remove the useless inventories now: ###Code shp = shp.loc[shp['subm_id'].isin([744, 616, 623, 635, 721, 722])].copy() ###Output _____no_output_____ ###Markdown Read in the geometry data for sub-inventory selection ###Code # Read L2 files shp_loc = gpd.read_file('tar://' + support_dir + f'/sub_inventory_sel_RGI02.tar.gz/sub_inventory_sel_RGI02.shp') shp_loc.plot(edgecolor='k'); shp_loc # Test the polygons I drew - each subregion should be equivalent as the sel by id for sub_id in [635, 623, 616]: sel = shp.loc[shp['subm_id'] == sub_id].copy() rp = sel.representative_point().to_frame('geometry') rp['orig_index'] = sel.index intersect = gpd.overlay(rp, shp_loc.loc[shp_loc['subm_id'] == sub_id], how='intersection') odf = sel.loc[intersect['orig_index']] assert len(sel) == len(odf) # Also even without preselection rp = shp.representative_point().to_frame('geometry') rp['orig_index'] = shp.index for sub_id in [635, 623]: sel = shp.loc[shp['subm_id'] == sub_id].copy() intersect = gpd.overlay(rp, shp_loc.loc[shp_loc['subm_id'] == sub_id], how='intersection') odf = shp.loc[intersect['orig_index']] delta = 0 if sub_id == 623: delta = 2 # Those two glaciers assert len(sel) + delta == len(odf) # for 614, 616 we mix and mingle but I trust what we have done below ###Output _____no_output_____ ###Markdown Apply selection criteria to create the RGI7 data subset ###Code # for northern Canada we use 'subm_id' 635 by analyst 'Berthier, Etienne' RGI_ss_NCan = shp.loc[shp['subm_id'] == 635].copy() needs_size_filter(RGI_ss_NCan) # for southern Canada we use 'subm_id' 623 by analyst 'Bolch, Tobias' (with 721, 722 which are corrections) RGI_ss_SCan = shp.loc[shp['subm_id'].isin([623, 721, 722])].copy() print(len(RGI_ss_SCan)) RGI_ss_SCan = size_filter(RGI_ss_SCan) len(RGI_ss_SCan) # For CONUS we use 'subm_id' 744 by analyst 'Fountain, Andrew G.' except for colorado RGI_ss_CONUS = shp.loc[shp['subm_id'] == 744].copy() # Remove colorado print(len(RGI_ss_CONUS)) rp = RGI_ss_CONUS.representative_point().to_frame('geometry') rp['orig_index'] = RGI_ss_CONUS.index intersect = gpd.overlay(rp, shp_loc.loc[shp_loc['subm_id'] == 744], how='intersection') RGI_ss_CONUS = RGI_ss_CONUS.loc[intersect['orig_index'].values].copy() print(len(RGI_ss_CONUS)) RGI_ss_CONUS = size_filter(RGI_ss_CONUS) len(RGI_ss_CONUS) # For Colorado we use 'subm_id' 616 by analyst 'Fountain, Andrew G.' RGI_ss_Colo = shp.loc[shp['subm_id'] == 616].copy() print(len(RGI_ss_Colo)) RGI_ss_Colo = size_filter(RGI_ss_Colo) len(RGI_ss_Colo) # combine the geodataframes rgi7 = pd.concat([RGI_ss_NCan, RGI_ss_SCan, RGI_ss_CONUS, RGI_ss_Colo]) ###Output _____no_output_____ ###Markdown Some sanity checks ###Code sdf, df_class = submission_summary(rgi7) df_class # Nothing should change here rgi7['is_rgi6'] = True # Check the orphaned rock outcrops orphan_f = os.path.join(data_dir, 'l1_orphan_interiors', f'RGI{reg:02d}', f'RGI{reg:02d}.shp') if os.path.exists(orphan_f): orphan_f = gpd.read_file(orphan_f) check = np.isin(rgi7.subm_id.unique(), orphan_f.subm_id.unique()) if np.any(check): print(f'Orphan rock outcrops detected in subm_id {rgi7.subm_id.unique()[check]}') orphan_f['area'] = orphan_f.to_crs({'proj':'cea'}).area orphan_f = orphan_f.loc[orphan_f.subm_id == 623] orphan_f['area'].sum() * 1e-6 ###Output _____no_output_____ ###Markdown Ok, more details in the checks below. Plots ###Code plot_map(rgi7, reg) plot_map(rgi7, reg, is_rgi6=True) plot_date_hist(rgi7, reg=reg, figsize=(20, 5)) plot_date_hist(RGI_ss_CONUS, title='744 - CONUS Fountain', figsize=(20, 5), savefig=False) ###Output _____no_output_____ ###Markdown Text for github ###Code fgh = sdf.T fgh print(fgh.to_markdown(headers=np.append(['subm_id'], fgh.columns))) ###Output | subm_id | 635 | 623 | 721 | 722 | 744 | 616 | |:--------------|:-----------------------------------------------------------------------|:--------------------|:--------------------|:--------------------|:-----------------|:------------------| | N | 1235 | 12463 | 1 | 1 | 5126 | 33 | | A | 656.5 | 13054.8 | 136.9 | 10.2 | 671.4 | 1.1 | | analysts | Berthier, Bolch, Cogley, Kienholz | Bolch | Bolch | Bolch | Fountain | Fountain, Hoffman | | submitters | Cogley | Bolch | Bolch | Bolch | Fountain | Hoffman | | release_date | 2015 | 2009 | 2009 | 2009 | 2016 | 2016 | | geog_area | Randolph Glacier Inventory; Umbrella RC for merging the RGI into GLIMS | Northern Cordillera | Northern Cordillera | Northern Cordillera | Conterminous USA | Conterminous USA | | src_date_mode | 1985 | 2006 | 2006 | 2006 | 1966 | 2001 | | src_date_min | 1968 | 2004 | 2006 | 2006 | 1943 | 2001 | | src_date_max | 1999 | 2006 | 2006 | 2006 | 1987 | 2001 | ###Markdown Write out and tar ###Code dd = mkdir(f'{output_dir}/RGI{reg:02d}/', reset=True) print('Writing...') rgi7.to_file(dd + f'RGI{reg:02d}.shp') print('Taring...') print(subprocess.run(['tar', '-zcvf', f'{output_dir_tar}/RGI{reg:02d}.tar.gz', '-C', output_dir, f'RGI{reg:02d}'])) ###Output Writing... Taring... CompletedProcess(args=['tar', '-zcvf', '../../rgi7_data/l3_rgi7a_tar/RGI02.tar.gz', '-C', '../../rgi7_data/l3_rgi7a', 'RGI02'], returncode=0) ###Markdown New RGI-file created - Check result! load reference data (here RGI6) to enable comparison ###Code # load reference data from utils import open_zip_shapefile ref_odf = open_zip_shapefile(rgi6_reg_file) ###Output _____no_output_____ ###Markdown Compare new RGI7-file to RGI6 Number of elements (differences depict problems) ###Code print('Number of glaciers in new RGI:', len(rgi7)) print('Number of glaciers in RGI6:', len(ref_odf)) print('Difference:', len(rgi7)-len(ref_odf)) ###Output Number of glaciers in new RGI: 18859 Number of glaciers in RGI6: 18855 Difference: 4 ###Markdown How many nominal glaciers were there in RGI06? ###Code len(ref_odf.loc[ref_odf.Status == 2]) ###Output _____no_output_____ ###Markdown Total area ###Code # add an area field to RGI_ss and reference data rgi7['area'] = rgi7.to_crs({'proj':'cea'}).area ref_odf['area'] = ref_odf.to_crs({'proj':'cea'}).area # print and compare area values Area_RGI = rgi7['area'].sum() * 1e-6 print('Area RGI7 [km²]:', Area_RGI) Area_ref = ref_odf['area'].sum() * 1e-6 print('Area RGI6 [km²]:', Area_ref) d = (Area_RGI - Area_ref) print('Area difference [km²]:', d) ###Output Area RGI7 [km²]: 14530.886140315337 Area RGI6 [km²]: 14524.240019596462 Area difference [km²]: 6.646120718874954 ###Markdown Northern Canada (635, Berthier, no problem there): ###Code rp = ref_odf.representative_point().to_frame('geometry') rp['orig_index'] = ref_odf.index intersect = gpd.overlay(rp, shp_loc.loc[shp_loc['subm_id'] == 635], how='intersection') ref_odf_NCan = ref_odf.loc[intersect['orig_index']].copy() print('Number of glaciers in RGI7 subset:', len(RGI_ss_NCan)) print('Number of glaciers in reference data (RGI6):', len(ref_odf_NCan)) print('Difference:', len(RGI_ss_NCan)-len(ref_odf_NCan)) # print and compare area values Area_7 = RGI_ss_NCan['area'].sum() * 1e-6 print('Area RGI7 [km²]:', Area_7) Area_6 = ref_odf_NCan['area'].sum() * 1e-6 print('Area RGI6 [km²]:', Area_6) d = (Area_7 - Area_6) print('Area difference [km²]:', d) ###Output Area RGI7 [km²]: 656.5317836977715 Area RGI6 [km²]: 656.5319107844741 Area difference [km²]: -0.0001270867026050837 ###Markdown This is brilliant! No issue there. Southern Canada (623, Bolch, some problems): ###Code rp = ref_odf.representative_point().to_frame('geometry') rp['orig_index'] = ref_odf.index intersect = gpd.overlay(rp, shp_loc.loc[shp_loc['subm_id'] == 623], how='intersection') ref_odf_SCan = ref_odf.loc[intersect['orig_index']].copy() print('Number of glaciers in RGI7 subset:', len(RGI_ss_SCan)) print('Number of glaciers in reference data (RGI6):', len(ref_odf_SCan)) print('Difference:', len(RGI_ss_SCan)-len(ref_odf_SCan)) # print and compare area values Area_7 = RGI_ss_SCan['area'].sum() * 1e-6 print('Area RGI7 [km²]:', Area_7) Area_6 = ref_odf_SCan['area'].sum() * 1e-6 print('Area RGI6 [km²]:', Area_6) d = (Area_7 - Area_6) print('Area difference [km²]:', d) ###Output Area RGI7 [km²]: 13201.819607709593 Area RGI6 [km²]: 13195.162964834108 Area difference [km²]: 6.656642875484977 ###Markdown We have one more glacier in GLIMS (this is expected from the glacier that was on the wrong side of the region border in RGI6) ###Code RGI_ss_SCan.loc[RGI_ss_SCan.anlys_id == 380747]['area'].sum() * 1e-6 ###Output _____no_output_____ ###Markdown Arg, we still have 6 km2 more in GLIMS than RGI6. Quick check on GIS reveals that some polygons in polygons are in GLIMS but not RGI, and some rock outcrops are in RGI but not GLIMS (see [example](https://github.com/GLIMS-RGI/glims_issue_tracker/issues/8issuecomment-981134080) in GH issue). We'll ignore this for now.Also, orphaned rock outcrops: ###Code # for i in range(len(orphan_f)): # f, ax = plt.subplots(figsize=(2, 2)) # orphan_f.iloc[[i]].plot(ax=ax); ###Output _____no_output_____ ###Markdown CONUS (744, Fountain, OK): ###Code rp = ref_odf.representative_point().to_frame('geometry') rp['orig_index'] = ref_odf.index intersect = gpd.overlay(rp, shp_loc.loc[shp_loc['subm_id'] == 744], how='intersection') ref_odf_CONUS = ref_odf.loc[intersect['orig_index']].copy() print('Number of glaciers in RGI7 subset:', len(RGI_ss_CONUS)) print('Number of glaciers in reference data (RGI6):', len(ref_odf_CONUS)) print('Difference:', len(RGI_ss_CONUS)-len(ref_odf_CONUS)) # print and compare area values Area_7 = RGI_ss_CONUS['area'].sum() * 1e-6 print('Area RGI7 [km²]:', Area_7) Area_6 = ref_odf_CONUS['area'].sum() * 1e-6 print('Area RGI6 [km²]:', Area_6) d = (Area_7 - Area_6) print('Area difference [km²]:', d) ###Output Area RGI7 [km²]: 671.4228538861278 Area RGI6 [km²]: 671.433249726907 Area difference [km²]: -0.01039584077921063 ###Markdown I don't know about the N glacier difference (not a big deal), and the missing area is small enough! Colorado (616, Fountain, OK): ###Code rp = ref_odf.representative_point().to_frame('geometry') rp['orig_index'] = ref_odf.index intersect = gpd.overlay(rp, shp_loc.loc[shp_loc['subm_id'] == 616], how='intersection') ref_odf_Colo = ref_odf.loc[intersect['orig_index']].copy() print('Number of glaciers in RGI7 subset:', len(RGI_ss_Colo)) print('Number of glaciers in reference data (RGI6):', len(ref_odf_Colo)) print('Difference:', len(RGI_ss_Colo)-len(ref_odf_Colo)) # print and compare area values Area_7 = RGI_ss_Colo['area'].sum() * 1e-6 print('Area RGI7 [km²]:', Area_7) Area_6 = ref_odf_Colo['area'].sum() * 1e-6 print('Area RGI6 [km²]:', Area_6) d = (Area_7 - Area_6) print('Area difference [km²]:', d) ###Output Area RGI7 [km²]: 1.111895021844131 Area RGI6 [km²]: 1.111894250971996 Area difference [km²]: 7.708721350141445e-07
notebooks/SignDetectorAndClassifier/notebooks/1.0.ClassifierResearch.ipynb
###Markdown датасет должен быть или скачен или сделан с помощью ноутбука RTSD-R_MERGEDОбъединенный датасет доступен по [ссылке](https://drive.google.com/drive/folders/1jmxG2zfi-Fs3m2KrMGmjD347aYiT8YFM?usp=sharing).Положить в папку data содержимое так, чтобы были следующие пути: * \$(ROOT_DIR)/data/merged-rtsd/...* \$(ROOT_DIR)/data/gt.csv> *gt_Set_NaN.csv - содержит тот же датасет, но значения колонки Set обнулено*gt - датафрейм содержащий: * имена файлов - поле filename* класс знака - поле sign_class* флаг присутствия знака при работе с датасетом - IsPresent. Предполагается, что вместо удаления записи, будет устанавливатся этот флаг, включающий/не влючающий знак в выборку* в какой набор включен знак - поле Set $\in$ $\{train, valid, test\}$ ###Code import matplotlib.pyplot as plt import numpy as np import random import torch from torch import nn import seaborn as sns import pandas as pd import os import pathlib import shutil import cv2 import PIL import cv2 from datetime import datetime %cd adas_system/notebooks IN_COLAB = False USE_COLAB_GPU = False try: import google.colab IN_COLAB = True USE_COLAB_GPU = True from google.colab import drive drive.mount('/content/drive') if not os.path.isfile('1_ClassifierResearch.ipynb'): !git clone --branch 9_SignDetector https://github.com/lsd-maddrive/adas_system.git !gdown --id 1-K3ee1NbMmx_0T5uwMesStmKnZO_6mWi %cd adas_system/notebooks !mkdir ../data/R_MERGED !unzip -q -o /content/R_MERGED.zip -d ./../data/ except: if IN_COLAB: print('[!]YOU ARE IN COLAB, BUT DIDNT MOUND A DRIVE. Model wont be synced[!]') if not os.path.isfile('1_ClassifierResearch.ipynb'): !git clone --branch 9_SignDetector https://github.com/lsd-maddrive/adas_system.git !gdown --id 1-K3ee1NbMmx_0T5uwMesStmKnZO_6mWi %cd adas_system/notebooks !mkdir ../data/R_MERGED !unzip -q -o /content/R_MERGED.zip -d ./../data/ IN_COLAB = False else: pass ### import nt_helper from nt_helper.helper_utils import * ### TEXT_COLOR = 'black' # Зафиксируем состояние случайных чисел RANDOM_STATE = 42 np.random.seed(RANDOM_STATE) torch.manual_seed(RANDOM_STATE) random.seed(RANDOM_STATE) %matplotlib inline plt.rcParams["figure.figsize"] = (17,10) device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') device ###Output _____no_output_____ ###Markdown Init dirs, init main vars ###Code if not IN_COLAB: PROJECT_ROOT = pathlib.Path(os.path.join(os.curdir, os.pardir)) else: PROJECT_ROOT = pathlib.Path('..') DATA_DIR = PROJECT_ROOT / 'data' NOTEBOOKS_DIR = PROJECT_ROOT / 'notebooks' gt = pd.read_csv(DATA_DIR / 'RTDS_DATASET.csv') SIGN_TO_NUMBER = pd.read_csv(DATA_DIR / 'sign_to_number.csv', index_col=0).T.to_dict('records')[0] NUMBER_TO_SIGN = pd.read_csv(DATA_DIR / 'number_to_sign.csv', index_col=0).T.to_dict('records')[0] gt['filepath'] = gt['filepath'].apply(lambda x: DATA_DIR / x) GT_SRC_LEN = len(gt.index) display(gt) _, ax = plt.subplots(nrows=3, ncols=1, figsize=(21, 8)) LABELS = ['train', 'valid', 'test'] for i in range(len(LABELS)): g = sns.countplot(x='SIGN', data=gt[gt['SET']==LABELS[i]], ax=ax[i], order=sorted(gt['SIGN'].value_counts().index.tolist()) ) ax[i].tick_params(labelrotation=90) ax[i].set_title(LABELS[i]) plt.tight_layout() ###Output _____no_output_____ ###Markdown Тестим обучалку: возьмем из трейна по N представителей каждого класса ###Code N = 1 gt_ = gt[gt["SET"]=='train'].copy() SIGN_SET = set(gt['SIGN']) from sklearn import preprocessing LE_LOCATION = DATA_DIR / 'le.npy' le = preprocessing.LabelEncoder() if os.path.isfile(LE_LOCATION): le.classes_ = np.load(LE_LOCATION) else: le.fit_transform(gt_['SIGN']) np.save(LE_LOCATION, le.classes_) gt['ENCODED_LABELS'] = le.transform(gt['SIGN']) gt_['ENCODED_LABELS'] = le.transform(gt_['SIGN']) nrows, ncols = 7, 6 fig = plt.figure(figsize = (16,16)) new_mini_df = pd.DataFrame(columns=gt_.columns) for idx, sign_class in enumerate(SIGN_SET): instances = gt_[gt_['SIGN'] == sign_class].sample(N) # print(instances) new_mini_df = new_mini_df.append(instances) # new_mini_df.loc[len(new_mini_df)] = instance.iloc[0] path = str(instances['filepath'].sample(1).values[0]) # print(path) sign = instances['SIGN'].sample(1).values[0] img = cv2.imread(path) ax = fig.add_subplot(nrows, ncols, idx+1) ax.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB), aspect=1) ax.set_title('ENCODED: ' + str(le.transform([sign_class])[0]) + '\nDECODED: ' + str(sign_class) + '\nSIGN: ' + str(NUMBER_TO_SIGN[sign_class])) plt.tight_layout() ###Output _____no_output_____ ###Markdown new_mini_df хранит только по единственному представителю знаков.Создадим загрузчик ###Code class SignDataset(torch.utils.data.Dataset): def __init__(self, df, set_label, img_size=64, transform=None, le=None): if isinstance(img_size, int): img_size = (img_size, img_size) self.img_size = img_size self.df = df[df['SET']==set_label] def __len__(self): return len(self.df.index) def __getitem__(self, index): label = int(self.df.iloc[index]['ENCODED_LABELS']) path = str(self.df.iloc[index]['filepath']) img = cv2.imread(path) img = cv2.resize(img, self.img_size, interpolation=cv2.INTER_LANCZOS4) img_tnsr = torch.Tensor.permute(torch.Tensor(img), [2, 0, 1]).div(255) return img_tnsr, label from sklearn.metrics import accuracy_score from tqdm.notebook import tqdm def train_epoch(model, loader, loss_op, optim, device): model.train() model.to(device) losses = 0 rights = 0 pbar = tqdm(enumerate(loader), total=len(loader), position=0, leave=False) for idx, (data, target) in pbar: data = data.to(device) target = target.to(device) optim.zero_grad() pred = model(data) iter_right_count = get_rights_count(pred, target).cpu().numpy() rights += iter_right_count loss = loss_op(pred, target) losses += loss.item() # Gradient descent loss.backward() optim.step() pbar.set_description("TRAIN: INSTANT LOSS %f INSTANT ACCUR: %.4f" % (round(loss.item(), 3), iter_right_count / len(target)) ) return losses def get_rights_count(y_pred, y_true): y_pred_softmax = torch.log_softmax(y_pred, dim = 1) _, y_pred_tags = torch.max(y_pred_softmax, dim = 1) correct_pred = (y_pred_tags == y_true).float() acc = correct_pred.sum() return acc def valid_epoch(model, loader, device): model.eval() model.to(device) rights = 0 pbar = tqdm(enumerate(loader), total=len(loader), position=0, leave=False) for idx, (data, target) in pbar: data = data.to(device) target = target.to(device) pred = model(data) iter_right_count = get_rights_count(pred, target).cpu().numpy() rights += iter_right_count pbar.set_description("VALIDATION: INSTANT ACCUR: %.4f" % (iter_right_count / len(target))) return rights / len(loader.dataset) SHOULD_I_TRAIN = False config = { 'lr': 0.1, 'epochs': 5, } DEFAULT_MODEL_LOCATION = DATA_DIR / 'CLASSIFIER' from torchvision import models model = models.resnet18(pretrained=True) MODEL_CLASSES = len(set(gt['SIGN'])) model.fc = nn.Sequential( nn.Linear(512, MODEL_CLASSES), nn.Softmax(dim=1) ) if os.path.isfile(DEFAULT_MODEL_LOCATION): model.load_state_dict(torch.load(DEFAULT_MODEL_LOCATION)) print('[+] Model restored from', DEFAULT_MODEL_LOCATION) model.eval() loss_op = nn.CrossEntropyLoss().cuda() optim = torch.optim.Adadelta(model.parameters(), lr=config['lr']) model.to(device) img_size = 64 train_dataset = SignDataset(gt, 'train', img_size) valid_dataset = SignDataset(gt, 'valid', img_size) num_workers=0 if IN_COLAB or USE_COLAB_GPU: num_workers=4 batch_size = 260 if IN_COLAB or USE_COLAB_GPU: batch_size = 2500 train_loader = torch.utils.data.DataLoader( train_dataset, batch_size=batch_size, num_workers=num_workers, pin_memory=True, shuffle=False) valid_loader = torch.utils.data.DataLoader( valid_dataset, batch_size=batch_size, num_workers=num_workers, pin_memory=True, shuffle=False) if SHOULD_I_TRAIN: pbar = tqdm(range(config['epochs']), total=config['epochs'], position=0, leave=True, desc='WAITING FOR FIRST EPOCH END...') for epoch in pbar: train_loss = train_epoch(model, train_loader, loss_op, optim, device) mean_train_acc = valid_epoch(model, train_loader, device) mean_valid_acc = valid_epoch(model, valid_loader, device) torch.save(model.state_dict(), DEFAULT_MODEL_LOCATION) model_save_name = 'CLASSIFIER_{}_TRAIN_ACC{:.4f}_VALID_ACC{:.4f}'.format(datetime.now().strftime("%m.%d_%H.%M"), mean_train_acc, mean_valid_acc) torch.save(model.state_dict(), DATA_DIR / model_save_name) if IN_COLAB: shutil.copy2(DATA_DIR / model_save_name, '/content/drive/MyDrive/') # torch.save(model.state_dict(), DEFAULT_MODEL_LOCATION) # if IN_COLAB: # shutil.copy2(DEFAULT_MODEL_LOCATION, '/content/drive/MyDrive/') pbar.set_description("PER EPOCH: TRAIN LOSS: %4f; TRAIN ACCUR %.4f; VALID ACCUR: %.4f" % (train_loss, mean_train_acc, mean_valid_acc) ) print("END TRAIN ACCUR: %.4f; VALID ACCUR %.4f" % (mean_train_acc, mean_valid_acc)) else: print('SHOULD I TRAIN == FALSE, SKIP TRAINING') ###Output _____no_output_____ ###Markdown DataSet sample ###Code def getNSamplesFromDataSet(ds, N): random_index = random.sample(range(0, len(ds)), N) ret = [] for index in random_index: ret.append(ds[index]) return ret def checkModelOutAndCompareToTargetLabel(pred, target): ''' ret is prediction right flag, predicted sign, target sign, confidence ''' isPredictionRight = False # transform prediction to sign argmax = np.argmax(pred) model_pred_decoded = le.inverse_transform([argmax])[0] model_pred_sign = NUMBER_TO_SIGN[model_pred_decoded] # transform target to sign decoded_label = le.inverse_transform([target])[0] target_sign = NUMBER_TO_SIGN[decoded_label] if model_pred_decoded == decoded_label: isPredictionRight = True confidence = pred[0][argmax] return isPredictionRight, model_pred_sign, target_sign, confidence nrows, ncols = 70, 6 fig = plt.figure(figsize = (16,200)) model.to(device) wrongs = 0 test_dataset = SignDataset(gt, 'test', img_size=64) test_samples = getNSamplesFromDataSet(test_dataset, 300) for idx, (img, encoded_label) in enumerate(test_samples): pred = model(img[None, ...].to(device)).cpu().detach().numpy() # make img from tensor img = torch.Tensor.permute(img, [1, 2, 0]).numpy() isPredictionRight, model_pred_sign, target_sign, confidence = checkModelOutAndCompareToTargetLabel(pred, encoded_label ) ax = fig.add_subplot(nrows, ncols, idx+1) ax.patch.set_linewidth('20') if isPredictionRight and confidence > 0.9: ax.patch.set_edgecolor('green') elif isPredictionRight and confidence > 0.7: print('low conf for', [(idx+1) // ncols , (idx+1) % ncols]) ax.patch.set_edgecolor('yellow') else: if confidence > 0.7: print('mismatch with high conf for', [(idx+1) // ncols , (idx+1) % ncols]) ax.patch.set_edgecolor('black') else: print('mismatch for', [(idx+1) // ncols , (idx+1) % ncols]) ax.patch.set_edgecolor('red') wrongs += 1 ax.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB), aspect=1) FACT_SIGN = 'FACT: ' + str(target_sign) PRED_SIGN = '\nPRED: ' + str(model_pred_sign) CONF = '(%.3f)' % confidence title = FACT_SIGN + PRED_SIGN + CONF title = ax.set_title(title, fontsize=15) print('Accuracy:', 1 - wrongs / len(test_samples)) plt.tight_layout() ###Output _____no_output_____
Tradeoffs with Privacy.ipynb
###Markdown Code to generate Figures 3, 5(a), 6 ###Code import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn import preprocessing from utils.svm import LinearSupportVectorMachine_noOffset from utils.RandFourier import RandomFourier from utils.functions import * from IPython.display import display, clear_output import matplotlib import matplotlib.pyplot as plt figwidth = 8 figheight = 4 ###Output _____no_output_____ ###Markdown Load and preprocess the data ###Code # Load Dataset X, Y, labels = load_wdbc() # Creat Train and Test sets X_train, X_test, ytrain, ytest = train_test_split(X, Y, test_size=0.3, random_state=1) y_train = np.asarray(ytrain) y_test = np.asarray(ytest) # Preprocess scaler = preprocessing.StandardScaler() scaler.fit(X_train) X_train_scaled = scaler.transform(X_train) X_test_scaled = scaler.transform(X_test) ###Output _____no_output_____ ###Markdown Set parameters ###Code n = X_train_scaled.shape[0] # number of training data points C = np.sqrt(n) # SVM parameter should scale as such (consistent classifier) print("C:",C) # number of features (should be an even number) F = int(2*50) ###Output C: 19.949937343260004 ###Markdown Find a prototype for each class ###Code # prototype[0]: class 1 # prototype[1]: class -1 prototype = [np.mean(X_train_scaled[y_train == 1], axis=0), np.mean(X_train_scaled[y_train == -1], axis=0)] ###Output _____no_output_____ ###Markdown Fix probability p and vary noise power and average over many realizations ###Code gran = 10 # the number of betas to generate rep = 10 # sample size for averaging noise (choose high to get smoother curves) # probablity for the probabilistic constraint proba = 0.9 # beta beta_v = np.linspace(0.1, 50, num=gran, endpoint=True) # noise scale: lambda lambda_v = 4*C*np.sqrt(F)/(beta_v*n) accuracy = np.zeros((rep)) distance_to_proto = np.zeros((rep)) accuracy_private = np.zeros((rep,gran)) explainability = np.zeros((rep,gran)) explainability_private = np.zeros((rep,gran)) explainability_robust = np.zeros((rep,gran)) explainability_private_strength = np.zeros((rep,gran)) explainability_robust_strength = np.zeros((rep,gran)) # Approximation of kernel FM_transform = RandomFourier(n_components=F,random_state=1).fit(X_train_scaled) X_train_FM = FM_transform.transform(X_train_scaled) X_test_FM = FM_transform.transform(X_test_scaled) # Train classifier SVM = LinearSupportVectorMachine_noOffset(C=C) SVM.fit(X_train_FM, y_train) # without noise # ------------- ## accuracy accuracy = sum(np.sign(SVM.predict(X_test_FM).flatten()) == y_test)/len(y_test) # Iteration: noise and approximation sample for rep_idx in range(rep): np.random.seed(seed=rep_idx) # selected instance to explain idx_selected = np.random.randint(0,len(X_test)) instance = X_test_scaled[idx_selected] instance_transformed = FM_transform.transform(instance.reshape(1, -1)) prediction_instance = np.sign(SVM.predict(instance_transformed).flatten()) selected_prototype = prototype[np.where(prediction_instance != [1,-1])[0][0]] ## explainability without noise explanation, plot_convergence = bisection_chance(instance, prediction_instance, selected_prototype, SVM, FM_transform) explainability[rep_idx] = np.linalg.norm(explanation-instance) distance_to_proto[rep_idx] = np.linalg.norm(selected_prototype-instance) # Iteration: noise scale for lambda_idx in range(gran): # with noise # ---------- mu = np.random.laplace(loc=0.0, scale=lambda_v[lambda_idx], size=(1,F)) ## accuracy accuracy_private[rep_idx,lambda_idx] = sum(np.sign(SVM.predict(X_test_FM, mu).flatten()) == y_test)/len(y_test) ## explainability non-robust explanation_private, plot_convergence = bisection_chance(instance, prediction_instance, selected_prototype, SVM, FM_transform, mu) explainability_private[rep_idx,lambda_idx] = np.linalg.norm(explanation_private-instance) explainability_private_strength[rep_idx,lambda_idx] = prediction_instance*SVM.predict(FM_transform.transform(explanation_private.reshape(1, -1)), noise=0).flatten() ## explainability robust explanation_robust, plot_convergence = bisection_chance(instance, prediction_instance, selected_prototype, SVM, FM_transform, mu, lambda_v[lambda_idx], p=proba) explainability_robust[rep_idx,lambda_idx] = np.linalg.norm(explanation_robust-instance) explainability_robust_strength[rep_idx,lambda_idx] = prediction_instance*SVM.predict(FM_transform.transform(explanation_robust.reshape(1, -1)), noise=0).flatten() clear_output(wait=True) display("Iteration for averaging: "+str(rep_idx+1)+ '/' +str(rep) +" -- Iteration on Beta: "+ str(lambda_idx+1)+ '/' +str(gran)) ###Output _____no_output_____ ###Markdown Plot Accuracy - Privacy Tradeoff ###Code fig, ax = plt.subplots(figsize=[figwidth, figheight], dpi=100) ax.plot(beta_v,np.mean(accuracy_private, axis=0), c="tab:red", label='private SVM') ax.axhline(y=accuracy, c="k", ls="--", label='non-private SVM') ax.set(xlabel=r'$\beta$', ylabel="classification accuracy", title='') ax.legend(loc='right') ax.set_xlim((0,50)) ax.set_ylim((.45,1)) ax.grid() plt.show() ###Output _____no_output_____ ###Markdown Plot Explainability - Privacy Tradeoff ###Code fig, ax = plt.subplots(figsize=[figwidth, figheight], dpi=100) ax.axhline(y=np.mean(distance_to_proto), c='tab:green', ls='--', marker='s', label='prototype') ax.plot(beta_v,np.mean(explainability_robust, axis=0), c="tab:red", ls='-', label='robust explanations for private SVM') ax.plot(beta_v,np.mean(explainability_private, axis=0), c="tab:blue", ls='-', marker='.', label='non-robust explanations for private SVM') ax.axhline(y=np.mean(explainability), c='k', ls='--', label='explanations for non-private SVM') ax.set(xlabel=r'$\beta$', ylabel="average distance to $x'$", title='') ax.legend() ax.grid() plt.show() ###Output _____no_output_____ ###Markdown Distribution of opposite class constraint ###Code epsilon = 0 fig, ax = plt.subplots(figsize=[figwidth, figheight], dpi=100) ax.plot(beta_v,np.percentile(explainability_private_strength, q=99, axis=0), c="tab:blue", ls=":", lw=1) ax.plot(beta_v,np.percentile(explainability_private_strength, q=95, axis=0), c="tab:blue", ls="-.", lw=1) ax.plot(beta_v,np.percentile(explainability_private_strength, q=90, axis=0), c="tab:blue", ls="--", lw=1.5) ax.plot(beta_v,np.percentile(explainability_private_strength, q=50, axis=0), c="tab:blue", ls="-", lw=2) ax.set(xlabel=r"$\beta$", ylabel=r"$y' f_{\phi}(x^{ex},\tilde{w})$", title='') ax.legend(['99th-percentile','95th-percentile','90th-percentile','50th-percentile'],loc='lower right') ax.grid() plt.show() fig, ax = plt.subplots(figsize=[figwidth, figheight], dpi=100) ax.plot(beta_v,np.percentile(explainability_robust_strength, q=99, axis=0), c="tab:red", ls=":", lw=1) ax.plot(beta_v,np.percentile(explainability_robust_strength, q=95, axis=0), c="tab:red", ls="-.", lw=1) ax.plot(beta_v,np.percentile(explainability_robust_strength, q=90, axis=0), c="tab:red", ls="--", lw=1.5) ax.plot(beta_v,np.percentile(explainability_robust_strength, q=50, axis=0), c="tab:red", ls="-", lw=2) ax.set(xlabel=r"$\beta$", ylabel=r"$y' f_{\phi}(x^{ro-ex},\tilde{w})$", title='') ax.legend(['99th-percentile','95th-percentile','90th-percentile','50th-percentile'],fontsize=8,loc='upper right') ax.grid() plt.show() ###Output _____no_output_____
to_send1.ipynb
###Markdown $$P_{(dx, dy)}=\|P(i, j)\|_{256 \times 256}$$ \begin{equation}P(i, j)=\sum_{x=1}^{N} \sum_{y=1}^{M}\left\{\begin{array}{ll}1, & \text { якщо } I(x, y)=i \text { та } I(x+d x, y + d y)=j ; \\0, & \text { в інших випадках }\end{array}\right.\end{equation} ###Code def p(i,j, matr, d): n_rows, n_cols = matr.shape dx, dy = d res = 0 for x in range(n_rows): for y in range(n_cols): # check for being in image's bounds props1 = [x + dx < n_rows, y + dy < n_cols] if all(props1): if matr[x][y] == i and matr[x + dx][y + dy] == j: res += 1 return res def coincidence_matr(image, d): """ d -- (dx, dy) vector image -- N x M matrix (built by image) """ res_matr = np.zeros((256, 256)) vmin, vmax = image.min(), image.max() # it actually makes sense to look only at # rectangle (vmnin x vmax) and make the least # equals zero for i in range(vmin, vmax): for j in range(vmin, vmax): res_matr[i, j] = p(i, j, image, d) return res_matr ###Output _____no_output_____ ###Markdown \begin{aligned}\hat{P}=\frac{1}{8}\left(P_{(0, dy)}+P_{(0,-dy)}\right.&+P_{(-dx, dy)}+P_{(dx,-dy)}+\\&\left.+P_{(-dx, 0)}+P_{(dx, 0)}+P_{(-dx,-dy)}+P_{(dx, dy)}\right)\end{aligned} ###Code def mean_coincidence_matr(image, d): """ image is given matrix d is (dx, dy) 2-dim vector """ dx, dy = d D = [(0, dy), (0, -dy), (-dx, dy), (dx, -dy), (-dx,0), (dx, 0), (-dx, -dy), (dx, dy)] res_matr = np.zeros((256, 256)) if d != (0, 0): for d_i in D: res_matr += coincidence_matr(ex1, d_i) return 1 / 8 * (res_matr) else: return coincidence_matr(ex1, d) matrices = [] for i in range(6): matrices.append([]) with open(fr"D:\Documents\Курсова файли\needed_files\404\1_{i+1}_Gray.txt") as f: lines = f.readlines() for line in lines: t = [float(x) for x in line.split()] matrices[i].append(t) ex1 = np.array(matrices[0][:-1], dtype=int) plt.imshow(ex1, cmap='gray') plt.imshow(ex1, cmap='gray_r') %%time d = (0, 1) ex1_res_ = coincidence_matr(ex1, d) plt.figure(dpi=100) plt.imshow(ex1_res_, cmap='gray_r') %%time ex1_res_mean = mean_coincidence_matr(ex1, d) plt.figure(dpi=100) plt.imshow(ex1_res_mean, cmap='gray_r') ###Output _____no_output_____
Video/Video_emotion_Recognition.ipynb
###Markdown In classifier model I have removed the Sotftmax Layer and added a Dense layer to give embedding of length 128. ###Code from google.colab import drive drive.mount('/content/drive') def classifierModel(X_input): ''' Layer 1 ''' X = TimeDistributed(Conv2D(64,(7,7),strides=(2,2),name = 'conv2',activation='relu'))(X_input) X = TimeDistributed(MaxPool2D((3,3),strides=(2,2),name='max_pool2'))(X) X = TimeDistributed(BatchNormalization())(X) ''' Layer 2 ''' X1 = TimeDistributed(Conv2D(96,(1,1),name='conv4',activation='relu'))(X) X2 = TimeDistributed(MaxPool2D((3,3),strides=(1,1),name='max_pool3'))(X) X3 = TimeDistributed(Conv2D(208,(3,3),name='conv5',activation='relu'))(X1) X4 = TimeDistributed(Conv2D(64,(1,1),name='conv6',activation='relu'))(X2) print(X1.shape,X2.shape) chunk_1 = keras.layers.concatenate([X3,X4],axis=-1) ''' Layer 3 ''' X5 = TimeDistributed(Conv2D(96,(1,1),name='conv7',activation='relu'))(chunk_1) X6 = TimeDistributed(MaxPool2D((3,3),strides=(1,1),name='max_pool4'))(chunk_1) X7 = TimeDistributed(Conv2D(208, (3,3),name='conv8',activation='relu'))(X5) X8 = TimeDistributed(Conv2D(64,(1,1),name='conv9',activation='relu'))(X6) chunk_2 = keras.layers.concatenate([X7,X8],axis=-1) ''' Layer 4 ''' out = TimeDistributed(Flatten())(chunk_2) out = TimeDistributed(Dropout(0.5))(out) out = TimeDistributed(Dense(128,activation = 'linear'))(out) return out ###Output _____no_output_____ ###Markdown 1. Clip size will be fixed i.e. the number of images during transition of emotion.2. s0 and c0 are the initial hidden state and cell state for LSTM3. Outputs will be an array storing the output of each LSTM cell 4. Then we will take the last output of LSTM cell as our final output ###Code def LSTM_model(input_shape): X_input = Input(shape = input_shape) X = classifierModel(X_input) X = LSTM(128)(X) X = Dense(8,activation='softmax')(X) model = Model(inputs = X_input,outputs = X) return model ###Output _____no_output_____ ###Markdown Clip size yet to be decided and it will be same as hidden_state_size because there will be equal number of LSTM units as number of images in a clip. ###Code model1 = LSTM_model((12,48,48,1)) model1.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) model1.summary() emotion_model = keras.models.load_model('/content/drive/My Drive/data/training3.h5') emotion_model.layers.pop() emotion_model.layers.pop() emotion_model.layers.pop() emotion_model.outputs = [emotion_model.layers[-1].output] def fine_tune(input_shape): input = Input(shape=input_shape, name='seq_input') x = TimeDistributed(keras.layers.Lambda(lambda x: emotion_model(x)))(input) x = TimeDistributed(Flatten())(x) x = TimeDistributed(Dense(128))(x) x = LSTM(128)(x) out = Dense(8,activation='softmax')(x) model = Model(inputs = input,outputs = out) return model fine_tuned_model = fine_tune((12,48,48,1)) fine_tuned_model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) ###Output _____no_output_____ ###Markdown Downloading BAUM 2 Dataset from the official website and extracting it to videos folder Getting cascades to find face and eye Extracting frames from the video file to use our model on that. ###Code !wget --continue https://github.com/spazewalker/FER_Doggomaniacs/raw/master/Video/ds.zip https://github.com/spazewalker/FER_Doggomaniacs/raw/master/main1.csv && unzip ds.zip ds = pd.read_csv("main1.csv") ds.head() x = np.array(ds['frames']) y = pd.get_dummies(ds['emotion']).to_numpy() import cv2 import numpy as np count = len(x) data = np.empty((1,1,1)) print("data loading. ") for j in range(len(x)): for i in range(12): arr = cv2.imread(x[j]+str(i)+'.jpg',cv2.IMREAD_GRAYSCALE) data = np.append(data,arr) print('\r{}%'.format(j/len(x)*100),end='') # print(arr.shape) # break data = np.delete(data,0) data = data.reshape(count,12,48,48,1) print('\r100%\nFinal Shape: ',data.shape) from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(data, y, test_size=0.1, random_state=42) ###Output _____no_output_____ ###Markdown Input_frames are of shape (m,clip_size,input_size)where input_size for eg. for FER2013 is (48,48,1) ###Code print('X_train: ',X_train.shape,'\nX_test: ',X_test.shape,'\ny_train: ',y_train.shape,'\ny_test: ',y_test.shape) fine_tuned_model.fit(X_train,y_train,epochs=8,batch_size = 32,validation_data=(X_test,y_test)) kf = KFold(n_splits=10) kf.get_n_splits(x) print(kf) fine_tuned_model2 = fine_tune((12,48,48,1)) fine_tuned_model2.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) for train_index,test_index in kf.split(X_train,y_train): X_train_sub, X_test_sub = X_train[train_index], X_train[test_index] y_train_sub, y_test_sub = y_train[train_index], y_train[test_index] X_train_sub = X_train_sub.reshape(X_train_sub.shape[0],12,48, 48, 1) X_test_sub = X_test_sub.reshape(X_test_sub.shape[0],12,48, 48, 1) fine_tuned_model2.fit(X_train_sub,y_train_sub,epochs=5,batch_size=32,validation_data=(X_test_sub,y_test_sub)) from keras.layers import Conv3D,MaxPool3D def c3d_model(input_shape): input = Input(shape = input_shape) X = Conv3D(64,(1,3,3),activation = 'relu')(input) X = MaxPool3D((1,2,2),strides=(1,2,2))(X) X = Conv3D(128,(1,3,3),activation='relu')(X) X = MaxPool3D((1,2,2),strides=(2,2,2))(X) X = Conv3D(128,(1,1,1),activation='relu')(X) X = Conv3D(256,(1,1,1),activation = 'relu')(X) X = MaxPool3D((2,2,2),strides=(2,2,2))(X) X = Conv3D(256,(1,1,1),activation='relu')(X) X = Conv3D(512,(1,1,1),activation='relu')(X) X = MaxPool3D((2,2,2),strides=(2,2,2))(X) X = Conv3D(512,(1,1,1),activation='relu')(X) X = Conv3D(512,(1,1,1),activation='relu')(X) X = MaxPool3D((1,1,1),strides=(2,2,2))(X) X = Flatten()(X) X = Dense(4096)(X) X = Dropout(0.5)(X) X = Dense(4096)(X) X = Dropout(0.5)(X) out = Dense(8,activation='softmax')(X) model = Model(inputs = input,outputs = out) return model c3d = c3d_model((12,48,48,1)) c3d.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) c3d.fit(X_train,y_train,epochs=5,batch_size=32,validation_data=(X_test,y_test)) kf = KFold(n_splits=10) kf.get_n_splits(x) print(kf) c3d = c3d_model((12,48,48,1)) c3d.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) for train_index,test_index in kf.split(X_train,y_train): X_train_sub, X_test_sub = X_train[train_index], X_train[test_index] y_train_sub, y_test_sub = y_train[train_index], y_train[test_index] X_train_sub = X_train_sub.reshape(X_train_sub.shape[0],12,48, 48, 1) X_test_sub = X_test_sub.reshape(X_test_sub.shape[0],12,48, 48, 1) c3d.fit(X_train_sub,y_train_sub,epochs=10,batch_size=32,validation_data=(X_test_sub,y_test_sub)) class_names = ['Neutral', 'Anger', 'Contempt', 'Disgust', 'Fear', 'Happy', 'Sad','Suprise'] def plot_confusion_matrix( cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues): if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] print("Normalized confusion matrix") else: print('Confusion matrix, without normalization') print(cm) plt.figure(figsize=(10,10)) plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title, fontsize=12) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45,color = 'black') plt.yticks(tick_marks, classes,color = 'black') fmt = '.2f' if normalize else 'd' thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, format(cm[i, j], fmt), horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") plt.ylabel('True label', fontsize=12,color='black') plt.xlabel('Predicted label', fontsize=12,color='black') plt.tight_layout() plt.savefig('confusion_matrix.png') ans = np.argmax(fine_tuned_model2.predict(X_test),axis=-1) y_test_fine = np.argmax(y_test,axis=1) matrix = confusion_matrix(y_test_fine,ans) plot_confusion_matrix( matrix, classes=class_names, normalize=True, title='Confusion Matrix') ans = np.argmax(c3d.predict(X_test),axis=-1) y_test_c3d = np.argmax(y_test,axis=1) matrix = confusion_matrix(y_test_c3d,ans) plot_confusion_matrix( matrix, classes=class_names, normalize=True, title='Confusion Matrix') plt.figure() plt.plot(c3d.history.history['val_accuracy']) plt.plot(c3d.history.history['accuracy']) ###Output _____no_output_____
notebooks/360_chapter7_table7.SM.5.ipynb
###Markdown Convert Mark Zelinka's json data into table formTheme Song: CrammArtist: Three Trapped TigersAlbum: Route One or DieReleased: 2011 ###Code import json import pandas as pd with open('../data_input/Zelinka_et_al_2020/cmip56_feedbacks_AR6.json') as file: z20 = json.load(file) df5 = pd.DataFrame(z20['cmip5']) df5['mip'] = 'CMIP5' df5 df6 = pd.DataFrame(z20['cmip6']) df6['mip'] = 'CMIP6' df6 df = pd.concat([df5, df6]) df df = df[['mip', 'models', 'NET_fbk', 'PL_fbk', 'WVLR_fbk', 'ALB_fbk', 'CLD_fbk', 'resid_fbk']] df df.to_csv('../data_output/7sm/feedbacks_supplement.csv', index=False) df6.mean() ###Output _____no_output_____
nbs/multiloss.ipynb
###Markdown MultiLoss> A loss wrapper and callback to calculate and log individual losses as fastxtend metrics. ###Code #|exporti def init_loss(l, **kwargs): "Initiatize loss class or partial loss function" return partialler(l, reduction='none') if isinstance(l, FunctionType) else l(reduction='none', **kwargs) #|export class MultiLoss(Module): """ Combine multiple `loss_funcs` on one prediction & target via `reduction`, with optional weighting. Log `loss_funcs` as metrics via `MultiLossCallback`, optionally using `loss_names`. """ def __init__(self, loss_funcs:listy[Callable[...,nn.Module]|FunctionType], # Uninitialized loss functions or classes. Must support PyTorch `reduction` string. weights:listified[Number]|None=None, # Weight per loss. Defaults to uniform weighting. loss_kwargs:listy[dict[str,Any]]|None=None, # kwargs to pass to each loss function. Defaults to None. loss_names:listy[str]|None=None, # Loss names to log using `MultiLossCallback`. Defaults to loss `__name__`. reduction:str|None='mean' # PyTorch loss reduction ): store_attr(but='loss_names') assert is_listy(loss_funcs), "`loss_funcs` must be list-like" if weights is None or len(weights)==0: self.weights = [1]*len(loss_funcs) else: assert len(loss_funcs) == len(weights), "Must provide same number of `weights` as `loss_funcs`" self.weights = weights if loss_kwargs is None or len(loss_kwargs)==0: loss_kwargs = [{}]*len(loss_funcs) else: assert len(loss_funcs) == len(loss_kwargs), "Must provide same number of `loss_kwargs` as `loss_funcs`" if loss_names is None or len(loss_names)==0: loss_names = [l.__name__ for l in loss_funcs] else: assert len(loss_funcs) == len(loss_names), "Must provide same number of `loss_names` as `loss_funcs`" self.loss_funcs = [init_loss(l, **k) for l, k in zip(loss_funcs, loss_kwargs)] self.loss_names = L(loss_names) self._reduction,self._loss = reduction,{} def forward(self, pred, targ): for i, loss_func in enumerate(self.loss_funcs): l = TensorBase(self.weights[i]*loss_func(pred, targ)) if i == 0: loss = TensorBase(torch.zeros_like(targ)).float() loss += l self._loss[i] = l return loss.mean() if self._reduction=='mean' else loss.sum() if self._reduction=='sum' else loss @property def losses(self): return self._loss @property def reduction(self): return self._reduction @reduction.setter def reduction(self, r): self._reduction = r @delegates(Module.to) def to(self, *args, **kwargs): device, dtype, non_blocking, convert_to_format = torch._C._nn._parse_to(*args, **kwargs) if is_listish(self.weights) or not isinstance(self.weights, torch.Tensor): self.weights = torch.Tensor(self.weights) if self.weights.device != device: self.weights = self.weights.to(device=device) super().to(*args, **kwargs) def activation(self, pred): "Returns first `loss_funcs` `activation`" return getattr(self.loss_funcs[0], 'activation', noop)(pred) def decodes(self, pred): "Returns first `loss_funcs` `decodes`" return getattr(self.loss_funcs[0], 'decodes', noop)(pred) ###Output _____no_output_____ ###Markdown `MultiLoss` is a simple multiple loss wrapper which allows logging each individual loss automatically using the `MultiLossCallback`.Pass uninitialized loss functions to `loss_funcs`, optional per loss weighting via `weights`, any loss arguments via a list of dictionaries in `loss_kwargs`, and optional names for each individual loss via `loss_names`.If passed, `weights`, `loss_kwargs`, & `loss_names` must be an iterable of the same length as `loss_funcs`.Output from each loss function must be the same shape. ###Code #|hide losses = [nn.MSELoss, nn.L1Loss] multiloss = MultiLoss(loss_funcs=losses) output = torch.sigmoid(torch.randn(32, 5, 10)) target = torch.randint(0,2,(32, 5, 10)) with torch.no_grad(): ml = multiloss(output, target) for i, l in enumerate(losses): test_close(l()(output, target), multiloss.losses[i].mean()) #|hide from fastai.losses import FocalLoss losses = [nn.CrossEntropyLoss, FocalLoss] multiloss = MultiLoss(loss_funcs=losses) output = torch.randn(32, 5, 128, 128) target = torch.randint(0, 5, (32, 128, 128)) with torch.no_grad(): ml = multiloss(output, target) for i, l in enumerate(losses): test_close(l()(output, target), multiloss.losses[i].mean()) ###Output _____no_output_____ ###Markdown MultiTargetLoss - ###Code #|export class MultiTargetLoss(MultiLoss): """ Combine `loss_funcs` from multiple predictions & targets via `reduction`, with optional weighting. Log `loss_funcs` as metrics via `MultiLossCallback`, optionally using `loss_names`. """ def __init__(self, loss_funcs:listy[Callable[...,nn.Module]|FunctionType], # Uninitialized loss functions or classes. One per prediction and target. Must support PyTorch `reduction` string. weights:listified[Number]|None=None, # Weight per loss. Defaults to uniform weighting. loss_kwargs:listy[dict[str,Any]]|None=None, # kwargs to pass to each loss function. Defaults to None. loss_names:listy[str]|None=None, # Loss names to log using `MultiLossCallback`. Defaults to loss `__name__`. reduction:str|None='mean' # PyTorch loss reduction ): super().__init__(loss_funcs, weights, loss_kwargs, loss_names, reduction) def forward(self, preds, targs): for i, (loss_func, pred, targ) in enumerate(zip(self.loss_funcs, preds, targs)): l = TensorBase(self.weights[i]*loss_func(pred, targ)) if i == 0: loss = TensorBase(torch.zeros_like(targ)).float() loss += l self._loss[i] = l return loss.mean() if self._reduction=='mean' else loss.sum() if self._reduction=='sum' else loss def activation(self, preds): "Returns list of `activation`" return [getattr(self.loss_funcs[i], 'activation', noop)(pred) for i, pred in enumerate(preds)] def decodes(self, preds): "Returns list of `decodes`" return [getattr(self.loss_funcs[i], 'decodes', noop)(pred) for i, pred in enumerate(preds)] ###Output _____no_output_____ ###Markdown `MultiTargetLoss` a single loss per multiple target version of `Multiloss`. It is a simple multiple loss wrapper which allows logging each individual loss automatically using the `MultiLossCallback`.Pass uninitialized loss functions to `loss_funcs`, optional per loss weighting via `weights`, any loss arguments via a list of dictionaries in `loss_kwargs`, and optional names for each individual loss via `loss_names`.If passed, `weights`, `loss_kwargs`, & `loss_names` must be an iterable of the same length as `loss_funcs`.Output from each loss function must be the same shape. ###Code #|hide losses = [nn.MSELoss, nn.L1Loss] multitargloss = MultiTargetLoss(loss_funcs=losses) outputs = [torch.sigmoid(torch.randn(32, 5, 10)),torch.sigmoid(torch.randn(32, 5, 10))] targets = [torch.randint(0,2,(32, 5, 10)),torch.randint(0,2,(32, 5, 10))] with torch.no_grad(): ml = multitargloss(outputs, targets) for i, (l, out, targ) in enumerate(zip(losses, outputs, targets)): test_close(l()(out, targ), multitargloss.losses[i].mean()) #|hide from fastai.losses import FocalLoss losses = [nn.CrossEntropyLoss, FocalLoss] multitargloss = MultiTargetLoss(loss_funcs=losses) outputs = [torch.randn(32, 5, 128, 128), torch.randn(32, 5, 128, 128)] targets = [torch.randint(0, 5, (32, 128, 128)), torch.randint(0, 5, (32, 128, 128))] with torch.no_grad(): ml = multitargloss(outputs, targets) for i, (l, out, targ) in enumerate(zip(losses, outputs, targets)): test_close(l()(out, targ), multitargloss.losses[i].mean()) ###Output _____no_output_____ ###Markdown Multiloss Metrics - ###Code #|exporti class MultiAvgLoss(AvgLossX): "Average the MultiLoss losses taking into account potential different batch sizes" def __init__(self, i, # `Multiloss` loss function location name, # Loss function name reduction:str|None='mean' # Override loss reduction for logging ): store_attr(but='name') self._name = name def accumulate(self, learn): bs = find_bs(learn.yb) loss = learn.loss_func.losses[self.i] loss = loss.mean() if self.reduction=='mean' else loss.sum() if self.reduction=='sum' else loss self.total += learn.to_detach(loss)*bs self.count += bs #|exporti class MultiAvgSmoothLoss(AvgSmoothLossX): "Smooth average of the MultiLoss losses (exponentially weighted with `beta`)" def __init__(self, i, # `Multiloss` loss function location name, # Loss function name beta:float=0.98, # Smoothing beta reduction:str|None='mean' # Override loss reduction for logging ): super().__init__() store_attr(but='name') self._name = name def accumulate(self, learn): self.count += 1 loss = learn.loss_func.losses[self.i] loss = loss.mean() if self.reduction=='mean' else loss.sum() if self.reduction=='sum' else loss self.val = torch.lerp(to_detach(loss, gather=False), self.val, self.beta) ###Output _____no_output_____ ###Markdown MultiLossCallback - ###Code #|export class MultiLossCallback(Callback): "Callback to automatically log and name `MultiLoss` losses as fastxtend metrics" run_valid,order = False,Recorder.order-1 def __init__(self, beta:float=0.98, # Smoothing beta reduction:str|None='mean' # Override loss reduction for logging ): store_attr() def before_fit(self): if not isinstance(self.loss_func, MultiLoss): raise ValueError("`MultiLossCallback` requires loss to be `MultiLoss` class") mets= L() reduction = self.loss_func.reduction if self.reduction is None else self.reduction for i in range(len(self.loss_func.loss_funcs)): mets += MultiAvgSmoothLoss(i, self.loss_func.loss_names[i], self.beta, reduction) mets += MultiAvgLoss(i, self.loss_func.loss_names[i], reduction) self.learn.metrics = mets + self.learn.metrics ###Output _____no_output_____ ###Markdown Example ###Code #|hide #|slow from fastai.learner import Learner from fastai.optimizer import SGD from fastxtend.metrics import RMSE @delegates(Learner.__init__) def synth_learner(n_trn=10, n_val=2, cuda=False, lr=1e-3, data=None, model=None, **kwargs): if data is None: data=synth_dbunch(n_train=n_trn,n_valid=n_val, cuda=cuda) if model is None: model=RegModel() return Learner(data, model, lr=lr, opt_func=partial(SGD, mom=0.9), **kwargs) #|slow with no_random(): mloss = MultiLoss(loss_funcs=[nn.MSELoss, nn.L1Loss], weights=[1, 3.5], loss_names=['mse_loss', 'l1_loss']) learn = synth_learner(n_trn=5, loss_func=mloss, metrics=RMSE(), cbs=MultiLossCallback) learn.fit(5) ###Output _____no_output_____
Big-Data-Clusters/CU2/Public/content/log-analyzers/tsg076-get-elastic-search-logs.ipynb
###Markdown TSG076 - Elastic Search logs============================Steps----- Parameters ###Code import re tail_lines = 2000 pod = None # All container = "elasticsearch" log_files = [ "/var/log/supervisor/log/elasticsearch*.log" ] expressions_to_analyze = [ re.compile(".{26}[WARN ]"), re.compile(".{26}[ERROR]") ] ###Output _____no_output_____ ###Markdown Instantiate Kubernetes client ###Code # 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: try: config.load_kube_config() except: display(Markdown(f'HINT: Use [TSG112 - App-Deploy Proxy Nginx Logs](../log-analyzers/tsg112-get-approxy-nginx-logs.ipynb) to resolve this issue.')) raise 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 ###Output _____no_output_____ ###Markdown Get the namespace for the big data clusterGet the namespace of the Big Data Cluster from the Kuberenetes API.**NOTE:**If there is more than one Big Data Cluster in the target Kubernetescluster, then either:- set \[0\] to the correct value for the big data cluster.- set the environment variable AZDATA\_NAMESPACE, before starting Azure Data Studio. ###Code # Place Kubernetes namespace name for BDC into 'namespace' variable if "AZDATA_NAMESPACE" in os.environ: namespace = os.environ["AZDATA_NAMESPACE"] else: 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) ###Output _____no_output_____ ###Markdown Get tail for log ###Code # Display the last 'tail_lines' of files in 'log_files' list pods = api.list_namespaced_pod(namespace) entries_for_analysis = [] for p in pods.items: if pod is None or p.metadata.name == pod: for c in p.spec.containers: if container is None or c.name == container: for log_file in log_files: print (f"- LOGS: '{log_file}' for CONTAINER: '{c.name}' in POD: '{p.metadata.name}'") try: output = stream(api.connect_get_namespaced_pod_exec, p.metadata.name, namespace, command=['/bin/sh', '-c', f'tail -n {tail_lines} {log_file}'], container=c.name, stderr=True, stdout=True) except Exception: print (f"FAILED to get LOGS for CONTAINER: {c.name} in POD: {p.metadata.name}") else: for line in output.split('\n'): for expression in expressions_to_analyze: if expression.match(line): entries_for_analysis.append(line) print(line) print("") print(f"{len(entries_for_analysis)} log entries found for further analysis.") ###Output _____no_output_____ ###Markdown Analyze log entries and suggest relevant Troubleshooting Guides ###Code # Analyze log entries and suggest further relevant troubleshooting guides from IPython.display import Markdown import os import json import requests import ipykernel import datetime from urllib.parse import urljoin from notebook import notebookapp def get_notebook_name(): """Return the full path of the jupyter notebook. Some runtimes (e.g. ADS) have the kernel_id in the filename of the connection file. If so, the notebook name at runtime can be determined using `list_running_servers`. Other runtimes (e.g. azdata) do not have the kernel_id in the filename of the connection file, therefore we are unable to establish the filename """ connection_file = os.path.basename(ipykernel.get_connection_file()) # If the runtime has the kernel_id in the connection filename, use it to # get the real notebook name at runtime, otherwise, use the notebook # filename from build time. try: kernel_id = connection_file.split('-', 1)[1].split('.')[0] except: pass else: for servers in list(notebookapp.list_running_servers()): try: response = requests.get(urljoin(servers['url'], 'api/sessions'), params={'token': servers.get('token', '')}, timeout=.01) except: pass else: for nn in json.loads(response.text): if nn['kernel']['id'] == kernel_id: return nn['path'] def load_json(filename): with open(filename, encoding="utf8") as json_file: return json.load(json_file) def get_notebook_rules(): """Load the notebook rules from the metadata of this notebook (in the .ipynb file)""" file_name = get_notebook_name() if file_name == None: return None else: j = load_json(file_name) if "azdata" not in j["metadata"] or \ "expert" not in j["metadata"]["azdata"] or \ "log_analyzer_rules" not in j["metadata"]["azdata"]["expert"]: return [] else: return j["metadata"]["azdata"]["expert"]["log_analyzer_rules"] rules = get_notebook_rules() if rules == None: print("") print(f"Log Analysis only available when run in Azure Data Studio. Not available when run in azdata.") else: hints = 0 if len(rules) > 0: for entry in entries_for_analysis: for rule in rules: if entry.find(rule[0]) != -1: print (entry) display(Markdown(f'HINT: Use [{rule[2]}]({rule[3]}) to resolve this issue.')) hints = hints + 1 print("") print(f"{len(entries_for_analysis)} log entries analyzed (using {len(rules)} rules). {hints} further troubleshooting hints made inline.") print('Notebook execution complete.') ###Output _____no_output_____
Quiz/m4_multifactor_models/m4l3/sector_neutral_solution.ipynb
###Markdown Sector Neutral (Solution) Install packages ###Code import sys !{sys.executable} -m pip install -r requirements.txt import cvxpy as cvx import numpy as np import pandas as pd import time import os import quiz_helper import matplotlib.pyplot as plt %matplotlib inline plt.style.use('ggplot') plt.rcParams['figure.figsize'] = (14, 8) ###Output _____no_output_____ ###Markdown following zipline bundle documentationhttp://www.zipline.io/bundles.htmlingesting-data-from-csv-files data bundle ###Code import os import quiz_helper from zipline.data import bundles os.environ['ZIPLINE_ROOT'] = os.path.join(os.getcwd(), '..', '..','data','module_4_quizzes_eod') ingest_func = bundles.csvdir.csvdir_equities(['daily'], quiz_helper.EOD_BUNDLE_NAME) bundles.register(quiz_helper.EOD_BUNDLE_NAME, ingest_func) print('Data Registered') ###Output _____no_output_____ ###Markdown Build pipeline engine ###Code from zipline.pipeline import Pipeline from zipline.pipeline.factors import AverageDollarVolume from zipline.utils.calendars import get_calendar universe = AverageDollarVolume(window_length=120).top(500) trading_calendar = get_calendar('NYSE') bundle_data = bundles.load(quiz_helper.EOD_BUNDLE_NAME) engine = quiz_helper.build_pipeline_engine(bundle_data, trading_calendar) ###Output _____no_output_____ ###Markdown View Data¶With the pipeline engine built, let's get the stocks at the end of the period in the universe we're using. We'll use these tickers to generate the returns data for the our risk model. ###Code universe_end_date = pd.Timestamp('2016-01-05', tz='UTC') universe_tickers = engine\ .run_pipeline( Pipeline(screen=universe), universe_end_date, universe_end_date)\ .index.get_level_values(1)\ .values.tolist() universe_tickers ###Output _____no_output_____ ###Markdown Get Returns data ###Code from zipline.data.data_portal import DataPortal data_portal = DataPortal( bundle_data.asset_finder, trading_calendar=trading_calendar, first_trading_day=bundle_data.equity_daily_bar_reader.first_trading_day, equity_minute_reader=None, equity_daily_reader=bundle_data.equity_daily_bar_reader, adjustment_reader=bundle_data.adjustment_reader) ###Output _____no_output_____ ###Markdown Get pricing data helper function ###Code def get_pricing(data_portal, trading_calendar, assets, start_date, end_date, field='close'): end_dt = pd.Timestamp(end_date.strftime('%Y-%m-%d'), tz='UTC', offset='C') start_dt = pd.Timestamp(start_date.strftime('%Y-%m-%d'), tz='UTC', offset='C') end_loc = trading_calendar.closes.index.get_loc(end_dt) start_loc = trading_calendar.closes.index.get_loc(start_dt) return data_portal.get_history_window( assets=assets, end_dt=end_dt, bar_count=end_loc - start_loc, frequency='1d', field=field, data_frequency='daily') ###Output _____no_output_____ ###Markdown get pricing data into a dataframe ###Code returns_df = \ get_pricing( data_portal, trading_calendar, universe_tickers, universe_end_date - pd.DateOffset(years=5), universe_end_date)\ .pct_change()[1:].fillna(0) #convert prices into returns returns_df ###Output _____no_output_____ ###Markdown Sector data helper functionWe'll create an object for you, which defines a sector for each stock. The sectors are represented by integers. We inherit from the Classifier class. [Documentation for Classifier](https://www.quantopian.com/posts/pipeline-classifiers-are-here), and the [source code for Classifier](https://github.com/quantopian/zipline/blob/master/zipline/pipeline/classifiers/classifier.py) ###Code from zipline.pipeline.classifiers import Classifier from zipline.utils.numpy_utils import int64_dtype class Sector(Classifier): dtype = int64_dtype window_length = 0 inputs = () missing_value = -1 def __init__(self): self.data = np.load('../../data/project_4_sector/data.npy') def _compute(self, arrays, dates, assets, mask): return np.where( mask, self.data[assets], self.missing_value, ) sector = Sector() sector len(sector.data) sector.data ###Output _____no_output_____ ###Markdown Quiz 1How many unique sectors are in the sector variable? Answer 1There are 11 sector categories.-1 represents missing values. There are categories 0 to 10 ###Code print(f"set of unique categories: {set(sector.data)}") ###Output _____no_output_____ ###Markdown Create an alpha factor based on momentumWe want to calculate the one-year return. In other words, get the close price of today, minus the close price of 252 trading days ago, and divide by that price from 252 days ago.$1YearReturn_t = \frac{price_{t} - price_{t-252}}{price_{t-252}}$ ###Code from zipline.pipeline.factors import Returns ###Output _____no_output_____ ###Markdown We'll use 2 years of data to calculate the factor **Note:** Going back 2 years falls on a day when the market is closed. Pipeline package doesn't handle start or end dates that don't fall on days when the market is open. To fix this, we went back 2 extra days to fall on the next day when the market is open. ###Code factor_start_date = universe_end_date - pd.DateOffset(years=2, days=2) factor_start_date ## 1 year returns can be the basis for an alpha factor p1 = Pipeline(screen=universe) rets1 = Returns(window_length=252, mask=universe) p1.add(rets1,"1YearReturns") df1 = engine.run_pipeline(p1, factor_start_date, universe_end_date) #graphviz lets us visualize the pipeline import graphviz p1.show_graph(format='png') ###Output _____no_output_____ ###Markdown View the data of the factor ###Code df1.head() ###Output _____no_output_____ ###Markdown Explore the demean functionThe Returns class inherits from zipline.pipeline.factors.factor. [The documentation for demean is located here](https://www.zipline.io/appendix.htmlzipline.pipeline.factors.Factor.demean), and is also pasted below:```demean(mask=sentinel('NotSpecified'), groupby=sentinel('NotSpecified'))[source]Construct a Factor that computes self and subtracts the mean from row of the result.If mask is supplied, ignore values where mask returns False when computing row means, and output NaN anywhere the mask is False.If groupby is supplied, compute by partitioning each row based on the values produced by groupby, de-meaning the partitioned arrays, and stitching the sub-results back together.Parameters: mask (zipline.pipeline.Filter, optional) – A Filter defining values to ignore when computing means.groupby (zipline.pipeline.Classifier, optional) – A classifier defining partitions over which to compute means.``` Quiz 2By looking at the documentation, and then the source code for `demean`, what are two parameters for this function? Which one or ones would you call if you wanted to demean by sector and wish to demean for all values in the chosen universe?[The source code](https://www.zipline.io/_modules/zipline/pipeline/factors/factor.htmlFactor.demean) has useful comments to help you answer this question. Answer 2We would use the groupby parameter, and we don't need to use the mask parameter, since we are not going to exclude any of the stocks in the universe from the demean calculation. Quiz 3Turn 1 year returns into an alpha factorWe can do some processing to convert our signal (1 year return) into an alpha factor. One step is to demean by sector.* demeanFor each stock, we want to take the average return of stocks that are in the same sector, and then remove this from the return of each individual stock. Answer 3 ###Code #TODO # create a pipeline called p2 p2 = Pipeline(screen=universe) # create a factor of one year returns, deman by sector factor_demean_by_sector = ( Returns(window_length=252, mask=universe). demean(groupby=Sector()) #we use the custom Sector class that we reviewed earlier ) # add the factor to the p2 pipeline p2.add(factor_demean_by_sector, 'Momentum_1YR_demean_by_sector') ###Output _____no_output_____ ###Markdown visualize the second pipeline ###Code p2.show_graph(format='png') ###Output _____no_output_____ ###Markdown Quiz 4How does this pipeline compare with the first pipeline that we created earlier? Answer 4The second pipeline now adds sector information in the GroupedRowTransform('demean') step. run pipeline and view the factor data ###Code df2 = engine.run_pipeline(p2, factor_start_date, universe_end_date) df2.head() ###Output _____no_output_____
Unsupervised Classification With Autoencoder.ipynb
###Markdown Unsupervised Classification With Autoencoder Arda Mavi[Arda Mavi - GitHub](https://github.com/ardamavi) Summary:In this project, we use autoencoders for classification as unsupervised machine learning algorithms with Deep Learning. Give the 'images' and 'number of the class', then let the program do the rest! First we look up what is autoencoder:[Building Autoencoders in Keras](https://blog.keras.io/building-autoencoders-in-keras.html) Example of image denoising: ###Code # Arda Mavi # Unsupervised Classification With Autoencoder # Import import keras import numpy as np from keras.datasets import mnist import matplotlib.pyplot as plt %matplotlib inline # Getting Dataset: def get_dataset(): (X, Y), (X_test, Y_test) = mnist.load_data() X = X.astype('float32') / 255. X_test = X_test.astype('float32') / 255. X = np.reshape(X, (len(X), 28, 28, 1)) X_test = np.reshape(X_test, (len(X_test), 28, 28, 1)) # Add noise: noise_factor = 0.4 X_train_noisy = X + noise_factor * np.random.normal(loc=0.0, scale=1.0, size=X.shape) X_test_noisy = X_test + noise_factor * np.random.normal(loc=0.0, scale=1.0, size=X_test.shape) X_train_noisy = np.clip(X_train_noisy, 0., 1.) X_test_noisy = np.clip(X_test_noisy, 0., 1.) return X, X_test, Y, Y_test, X_train_noisy, X_test_noisy X, X_test, Y, Y_test, X_train_noisy, X_test_noisy = get_dataset() # About Dataset: print('Training shape:', X.shape) print(X.shape[0], 'sample,',X.shape[1] ,'x',X.shape[2] ,'size grayscale image.\n') print('Test shape:', X_test.shape) print(X_test.shape[0], 'sample,',X_test.shape[1] ,'x',X_test.shape[2] ,'size grayscale image.\n') print('Examples:') n = 10 plt.figure(figsize=(20, 4)) for i in range(1, n): # display original ax = plt.subplot(2, n, i) plt.imshow(X[i].reshape(28, 28)) plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) # display reconstruction ax = plt.subplot(2, n, i + n) plt.imshow(X_train_noisy[i].reshape(28, 28)) plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) # Deep Learning Model: from keras.layers import Input, Conv2D, MaxPooling2D, UpSampling2D, Dense from keras.models import Model input_img = Input(shape=(28, 28, 1)) x = Conv2D(16, (3, 3), activation='relu', padding='same')(input_img) x = MaxPooling2D((2, 2), padding='same')(x) x = Conv2D(8, (3, 3), activation='relu', padding='same')(x) x = MaxPooling2D((2, 2), padding='same')(x) x = Conv2D(8, (3, 3), activation='relu', padding='same')(x) encoded = MaxPooling2D((2, 2), padding='same')(x) # Output Shape: 4x4x8 x = Conv2D(8, (3, 3), activation='relu', padding='same')(encoded) x = UpSampling2D((2, 2))(x) x = Conv2D(8, (3, 3), activation='relu', padding='same')(x) x = UpSampling2D((2, 2))(x) x = Conv2D(16, (3, 3), activation='relu')(x) x = UpSampling2D((2, 2))(x) decoded = Conv2D(1, (3, 3), activation='sigmoid', padding='same')(x) # Output Shape: 28x28x1 autoencoder = Model(input_img, decoded) autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy') autoencoder.summary() # Checkpoints: from keras.callbacks import ModelCheckpoint, TensorBoard checkpoints = [] #checkpoints.append(TensorBoard(log_dir='/Checkpoints/logs')) ###Output _____no_output_____ ###Markdown For training model with Data Augmentation run this cell: ###Code # Creates live data: # For better yield. The duration of the training is extended. from keras.preprocessing.image import ImageDataGenerator generated_data = ImageDataGenerator(featurewise_center=False, samplewise_center=False, featurewise_std_normalization=False, samplewise_std_normalization=False, zca_whitening=False, rotation_range=0, width_shift_range=0.1, height_shift_range=0.1, horizontal_flip = True, vertical_flip = False) generated_data.fit(X_train_noisy) autoencoder.fit_generator(generated_data.flow(X_train_noisy, X, batch_size=batch_size), steps_per_epoch=X.shape[0], epochs=epochs, validation_data=(X_test_noisy, X_test), callbacks=checkpoints) # Training Model: epochs = 3 batch_size = 100 autoencoder.fit(X_train_noisy, X, batch_size=batch_size, epochs=epochs, validation_data=(X_test_noisy, X_test), shuffle=True, callbacks=checkpoints) decoded_imgs = autoencoder.predict(X_test_noisy) n = 10 plt.figure(figsize=(20, 4)) for i in range(1, n): # display original ax = plt.subplot(2, n, i) plt.imshow(X_test_noisy[i].reshape(28, 28)) plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) # display reconstruction ax = plt.subplot(2, n, i + n) plt.imshow(decoded_imgs[i].reshape(28, 28)) plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) ###Output _____no_output_____ ###Markdown Now we use autoencoder for unsupervised classification: ###Code # Describe the number of classes: num_class = 10 from keras.layers import Input, Conv2D, MaxPooling2D, UpSampling2D, Conv2DTranspose, Dense, Activation, Lambda, Reshape, Flatten from keras.models import Model from keras import backend as K # Custom classifier function: def classifier_func(x): return x+x*K.one_hot(K.argmax(x, axis=1), num_classes=num_class) # Deep Learning Model: inputs = Input(shape=(28, 28, 1)) #Encoder: conv_1 = Conv2D(32, (3,3), strides=(1,1))(inputs) act_1 = Activation('relu')(conv_1) maxpool_1 = MaxPooling2D(pool_size=(2, 2), strides=(2, 2))(act_1) conv_2 = Conv2D(64, (3,3), strides=(1,1), padding='same')(maxpool_1) act_2 = Activation('relu')(conv_2) maxpool_2 = MaxPooling2D(pool_size=(2, 2), strides=(2, 2))(act_2) # Output Shape: 6x6x64 flat_1 = Flatten()(maxpool_2) fc_1 = Dense(256)(flat_1) act_3 = Activation('relu')(fc_1) fc_2 = Dense(128)(act_3) act_4 = Activation('relu')(fc_2) fc_3 = Dense(num_class)(act_4) act_class = Lambda(classifier_func, output_shape=(num_class,))(fc_3) # Output Shape: 10 #Decoder: fc_4 = Dense(256)(act_class) act_5 = Activation('relu')(fc_4) fc_5 = Dense(2304)(act_5) act_6 = Activation('relu')(fc_5) reshape_1 = Reshape((6,6,64))(act_6) upsample_1 = UpSampling2D((2, 2))(reshape_1) deconv_1 = Conv2DTranspose(64, (3, 3), strides=(1, 1))(upsample_1) act_7 = Activation('relu')(deconv_1) upsample_2 = UpSampling2D((2, 2))(act_7) deconv_2 = Conv2DTranspose(32, (3, 3), strides=(1, 1))(upsample_2) act_8 = Activation('relu')(deconv_2) conv_3 = Conv2D(1, (3, 3), strides=(1, 1))(act_8) act_9 = Activation('sigmoid')(conv_3) # Output Shape: 28x28x1 autoencoder = Model(inputs, act_9) autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy') autoencoder.summary() ###Output _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= input_2 (InputLayer) (None, 28, 28, 1) 0 _________________________________________________________________ conv2d_8 (Conv2D) (None, 26, 26, 32) 320 _________________________________________________________________ activation_1 (Activation) (None, 26, 26, 32) 0 _________________________________________________________________ max_pooling2d_4 (MaxPooling2 (None, 13, 13, 32) 0 _________________________________________________________________ conv2d_9 (Conv2D) (None, 13, 13, 64) 18496 _________________________________________________________________ activation_2 (Activation) (None, 13, 13, 64) 0 _________________________________________________________________ max_pooling2d_5 (MaxPooling2 (None, 6, 6, 64) 0 _________________________________________________________________ flatten_1 (Flatten) (None, 2304) 0 _________________________________________________________________ dense_1 (Dense) (None, 256) 590080 _________________________________________________________________ activation_3 (Activation) (None, 256) 0 _________________________________________________________________ dense_2 (Dense) (None, 128) 32896 _________________________________________________________________ activation_4 (Activation) (None, 128) 0 _________________________________________________________________ dense_3 (Dense) (None, 10) 1290 _________________________________________________________________ lambda_1 (Lambda) (None, 10) 0 _________________________________________________________________ dense_4 (Dense) (None, 256) 2816 _________________________________________________________________ activation_5 (Activation) (None, 256) 0 _________________________________________________________________ dense_5 (Dense) (None, 2304) 592128 _________________________________________________________________ activation_6 (Activation) (None, 2304) 0 _________________________________________________________________ reshape_1 (Reshape) (None, 6, 6, 64) 0 _________________________________________________________________ up_sampling2d_4 (UpSampling2 (None, 12, 12, 64) 0 _________________________________________________________________ conv2d_transpose_1 (Conv2DTr (None, 14, 14, 64) 36928 _________________________________________________________________ activation_7 (Activation) (None, 14, 14, 64) 0 _________________________________________________________________ up_sampling2d_5 (UpSampling2 (None, 28, 28, 64) 0 _________________________________________________________________ conv2d_transpose_2 (Conv2DTr (None, 30, 30, 32) 18464 _________________________________________________________________ activation_8 (Activation) (None, 30, 30, 32) 0 _________________________________________________________________ conv2d_10 (Conv2D) (None, 28, 28, 1) 289 _________________________________________________________________ activation_9 (Activation) (None, 28, 28, 1) 0 ================================================================= Total params: 1,293,707 Trainable params: 1,293,707 Non-trainable params: 0 _________________________________________________________________ ###Markdown For training model with Data Augmentation run this cell: ###Code # Creates live data: # For better yield. The duration of the training is extended. from keras.preprocessing.image import ImageDataGenerator generated_data = ImageDataGenerator(featurewise_center=False, samplewise_center=False, featurewise_std_normalization=False, samplewise_std_normalization=False, zca_whitening=False, rotation_range=0, width_shift_range=0.1, height_shift_range=0.1, horizontal_flip = True, vertical_flip = False) generated_data.fit(X) autoencoder.fit_generator(generated_data.flow(X, X, batch_size=batch_size), steps_per_epoch=X.shape[0], epochs=epochs, validation_data=(X_test, X_test), callbacks=checkpoints) # Training Model: epochs = 4 batch_size = 100 autoencoder.fit(X, X, batch_size=batch_size, epochs=epochs, validation_data=(X_test, X_test), shuffle=True, callbacks=checkpoints) decoded_imgs = autoencoder.predict(X_test) n = 10 plt.figure(figsize=(20, 4)) for i in range(1, n): # display original ax = plt.subplot(2, n, i) plt.imshow(X_test[i].reshape(28, 28)) plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) # display reconstruction ax = plt.subplot(2, n, i + n) plt.imshow(decoded_imgs[i].reshape(28, 28)) plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) # Split autoencoder: encoder = Model(inputs, act_class) encoder.summary() ###Output _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= input_2 (InputLayer) (None, 28, 28, 1) 0 _________________________________________________________________ conv2d_8 (Conv2D) (None, 26, 26, 32) 320 _________________________________________________________________ activation_1 (Activation) (None, 26, 26, 32) 0 _________________________________________________________________ max_pooling2d_4 (MaxPooling2 (None, 13, 13, 32) 0 _________________________________________________________________ conv2d_9 (Conv2D) (None, 13, 13, 64) 18496 _________________________________________________________________ activation_2 (Activation) (None, 13, 13, 64) 0 _________________________________________________________________ max_pooling2d_5 (MaxPooling2 (None, 6, 6, 64) 0 _________________________________________________________________ flatten_1 (Flatten) (None, 2304) 0 _________________________________________________________________ dense_1 (Dense) (None, 256) 590080 _________________________________________________________________ activation_3 (Activation) (None, 256) 0 _________________________________________________________________ dense_2 (Dense) (None, 128) 32896 _________________________________________________________________ activation_4 (Activation) (None, 128) 0 _________________________________________________________________ dense_3 (Dense) (None, 10) 1290 _________________________________________________________________ lambda_1 (Lambda) (None, 10) 0 ================================================================= Total params: 643,082 Trainable params: 643,082 Non-trainable params: 0 _________________________________________________________________ ###Markdown Use the code to finding which cluster:`np.argmax(, axis=0)` Now we look up result: ###Code encode = encoder.predict(X) class_dict = np.zeros((num_class, num_class)) for i, sample in enumerate(Y): class_dict[np.argmax(encode[i], axis=0)][sample] += 1 print(class_dict) neuron_class = np.zeros((num_class)) for i in range(num_class): neuron_class[i] = np.argmax(class_dict[i], axis=0) print(neuron_class) encode = encoder.predict(X_test) predicted = np.argmax(encode, axis=1) for i, sample in enumerate(predicted): predicted[i] = neuron_class[predicted[i]] comparison = Y_test == predicted loss = 1 - np.sum(comparison.astype(int))/Y_test.shape[0] print('Loss:', loss) print('Examples:') for i in range(10): plt.imshow(X_test[i].reshape(28,28), cmap='gray') plt.axis('off') plt.show() neuron = np.argmax(encode[i], axis=0) print('Class:', Y_test[i], '- Model\'s Output Class:', neuron_class[neuron]) ###Output Examples:
CH3 Indexing.ipynb
###Markdown set_index() ###Code # set athelet as set_index oo.set_index('Athlete') # we can figur out nothing change oo.head() # so if we want to change in orignal dataframe we should use inplace oo.set_index('Athlete', inplace=True) oo.head() ###Output _____no_output_____ ###Markdown reset_index() ###Code # the opposite of set_index, it return the datafram with default index oo.reset_index(inplace=True) oo.head() ###Output _____no_output_____ ###Markdown sort_index() ###Code #alows all item to sorted by specific index. We can sort objects by a lable along the axis oo.sort_index(inplace=True) oo.head() ###Output _____no_output_____ ###Markdown loc[] DataFrame.loc[] / DataFrame.Series.loc[] A label-based indexer for selection by lable loc[] will raise a KeyError when the items are not found ###Code oo.set_index('Athlete', inplace=True) oo.loc['BOLT, Usain'] oo.reset_index(inplace=True) oo.head() oo.loc[oo.Athlete == 'BOLT, Usain'] ###Output _____no_output_____ ###Markdown iloc[] DataFram.iloc[] iloc[] is primarily integer position based from 0 to length -a of the axis Allows traditional Pythonic slicing ###Code oo.head() oo.iloc[1700] oo.iloc[[200, 2, 15, 800]] oo.iloc[1:4] ###Output _____no_output_____
timeseries/Timezones.ipynb
###Markdown Pandas time zone information ###Code import pandas as pd import numpy as np rng = pd.date_range('3/6/2016 00:00',periods=15, freq='d') rng print(rng.tz) rng = pd.date_range('3/6/2016 00:00',periods=15, freq='d',tz='Europe/London') rng ###Output _____no_output_____ ###Markdown Getting lists of timezones ###Code from pytz import common_timezones,all_timezones print(len(common_timezones)) print(common_timezones[1:10]) print(len(all_timezones)) ###Output 593 ###Markdown What are some time zones not considered common? ###Code set(all_timezones).difference(set(common_timezones)) ###Output _____no_output_____ ###Markdown Localizing a timestamp ###Code t_native = pd.Timestamp('2016-05-05 8:15') t_native t= t_native.tz_localize(tz='Asia/Calcutta') t t.tz_convert('Asia/Tokyo') ###Output _____no_output_____ ###Markdown What is the difference between tz_convert and tz_localize?hint:try to run tz_convert on naive timestamp Fun with daylight savings ###Code # you will get weirdness with timezones based on daylight savings: rng = pd.date_range('2016-03-10',periods=10,tz='US/Eastern') ts = pd.Series(range(10),index=rng) #what do you notice below? ts ###Output _____no_output_____ ###Markdown Ambiguous times ###Code # for the same reason you can run into 'ambiguous' dates rng_hourly= pd.DatetimeIndex(['11/06/2011 00:00','11/06/2011 01:00','11/06/2011 01:00','11/06/2011 02:00', '11/06/2011 03:00','11/06/2011 04:00']) rng_hourly # What happens when you do this? rng_hourly.tz_localize('US/Eastern') ###Output _____no_output_____ ###Markdown How do we deal with this ambiguous time error?https://pandas.pydata.org/pandas-docs/stable/timeseries.htmlambiguous-times-when-localizing ###Code rng_hourly.tz_localize('US/Central',ambiguous='infer') ###Output _____no_output_____ ###Markdown How can we check whether the inference did what we wanted? ###Code rng_hourly.tz_localize('US/Central',ambiguous='infer').tz_convert('utc') ###Output _____no_output_____ ###Markdown Pandas goes to amazing length to try to figure things out for you ###Code # whats going on here ? pd.Timestamp('2016-03-13 02:00',tz='US/Eastern') ###Output _____no_output_____
experiments/tl_3v2/filter/cores-oracle.run1.framed/trials/1/trial.ipynb
###Markdown Transfer Learning Template ###Code %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 ###Output _____no_output_____ ###Markdown Allowed ParametersThese are allowed parameters, not defaultsEach 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 ###Code 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_3-filterv2:cores -> oracle.run1.framed", "device": "cuda", "lr": 0.0001, "x_shape": [2, 200], "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, 200]}}, { "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": 16000, "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": [ "1-10.", "1-11.", "1-15.", "1-16.", "1-17.", "1-18.", "1-19.", "10-4.", "10-7.", "11-1.", "11-14.", "11-17.", "11-20.", "11-7.", "13-20.", "13-8.", "14-10.", "14-11.", "14-14.", "14-7.", "15-1.", "15-20.", "16-1.", "16-16.", "17-10.", "17-11.", "17-2.", "19-1.", "19-16.", "19-19.", "19-20.", "19-3.", "2-10.", "2-11.", "2-17.", "2-18.", "2-20.", "2-3.", "2-4.", "2-5.", "2-6.", "2-7.", "2-8.", "3-13.", "3-18.", "3-3.", "4-1.", "4-10.", "4-11.", "4-19.", "5-5.", "6-15.", "7-10.", "7-14.", "8-18.", "8-20.", "8-3.", "8-8.", ], "domains": [1, 2, 3, 4, 5], "num_examples_per_domain_per_label": -1, "pickle_path": "/mnt/wd500GB/CSC500/csc500-main/datasets/cores.stratified_ds.2022A.pkl", "source_or_target_dataset": "source", "x_transforms": ["unit_mag", "lowpass_+/-10MHz", "take_200"], "episode_transforms": [], "domain_prefix": "C_", }, { "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": 2000, "pickle_path": "/mnt/wd500GB/CSC500/csc500-main/datasets/oracle.Run1_framed_2000Examples_stratified_ds.2022A.pkl", "source_or_target_dataset": "target", "x_transforms": ["unit_mag", "take_200", "resample_20Msps_to_25Msps"], "episode_transforms": [], "domain_prefix": "O_", }, ], "seed": 1337, "dataset_seed": 1337, } # 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) ###Output _____no_output_____
class_materials/class_1/.ipynb_checkpoints/Class 1-checkpoint.ipynb
###Markdown Topics CoveredWhy Learn PythonKeywordsIdentifiersCommentsIndentationStatementsVariablesData TypesStandard I/OOperators Why Python 1. Extremely easy to learn2. Great packages for AI like matplotlib, numpy, scipy, scikit-learn, tensorflow3. IPython Notebooks for interactive data analysis & modeling4. Extensively used in the industry Keywords Reserved words in PythonCannot use them for variable names, function names or any other identifiersKeywords are case sensitive ###Code #Get all keywords in python 3.6 import keyword # remember #include<stdio.h> print(keyword.kwlist) print("\nTotal number of keywords", len(keyword.kwlist)) ###Output ['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield'] Total number of keywords 33 ###Markdown Identifiers Names given to entities like classes, functions, variables etc in Python.can be a combination of letters in lowercase(a - z) or uppercase(A-Z) or digits(0-9) or underscoreCannot use special symbols like !, @, , $, % etc ###Code 212_aaa=123 if=2 ###Output _____no_output_____ ###Markdown Comments ###Code # following line of code prints a line to console print("This is a line") ###Output _____no_output_____ ###Markdown Multi line Comments ###Code #this is a # multi line # comment ###Output _____no_output_____ ###Markdown Better still, use """ or ''' ###Code """multi line comment using double quotes""" '''this multi line has single quotes''' ###Output _____no_output_____ ###Markdown Indentation ###Code for i in range(10): print(i) # print(i*2) # print(10) ###Output _____no_output_____ ###Markdown Code readability ###Code if True: print("Machine Learning") where="PSF" if True: print("Machine Learning"); where = "PSF" ###Output _____no_output_____ ###Markdown Python statement Commands that will be executed by Python Interpreter ###Code value = 1 ###Output _____no_output_____ ###Markdown Multi line statement ###Code value = 10 + 11 \ +12 - 2 \ -10 print(value) #another method is to use paranthesis () value=(21+19+10 +12+13) print(value) #multiple statements in a single line val=12;x=10;y=9;z=8 print(val,x,y,z) ###Output _____no_output_____ ###Markdown Variables 1. Location in memeory to store data2. Variable names follow same rules as identifiers3. No need to declare variable Multiple assignments ###Code a,b,c="hello",21,2.4 print(a,b,c) a=b=c="PSF" print(a,b,c) ###Output _____no_output_____ ###Markdown Location of storage ###Code val=21 print(id(val)) val2=21 print(id(val2)) val2=22 print(id(val2)) #is operator val is val2 ###Output _____no_output_____ ###Markdown Data Types Every variable in Python has a datatypeEvery thing in Python is an object ###Code a = 50 print(a,"is of type ",type(a)) a=5.5 print(a,"is of type ",type(a)) a=3+4j print(a,"is of type ",type(a)) ###Output _____no_output_____ ###Markdown Boolean ###Code a=True print(type(a)) ###Output _____no_output_____ ###Markdown Python Strings Sequence of Unicode characters, not ASCIICan use single quotes or double quotes to represent stringMulti line strings can be denoted using triple quotes like """ and '''String is a sequence of characters - letters, numbers and special charactersFirst character of string is indexed at 0 ###Code s = "This is skill development course" print(s) print(type(s)) s = 'This is skill development course' print(s) print(type(s)) print(s[0]) s="""I wish this class got more interesting """ print(s) print(type(s)) print(s[0]) #what if i want to print the lsat character, 2nd last character etc #slicing #print the characters from 5th index till 10th index ###Output _____no_output_____ ###Markdown List Something that makes life so easyList is an ordered sequence of items.List can have elements of different types ###Code a=["start",21,21.9,3+4j] print(a) print(a[1]) print(type(a)) ###Output _____no_output_____ ###Markdown Any element within the list can be modifiedHence a list is mutable ###Code a[2]=99 print(a) ###Output _____no_output_____ ###Markdown TupleDifferences between list and tuple Tuple is an ordered sequence of items same as list.Tuples are immutableTuples once created, cannot be modified ###Code tup=(21,5-3j,"hello") print(tup) print(tup[1]) tup[2]="Bye" ###Output _____no_output_____ ###Markdown Python Set Set is an unordered collection of unique items.Set is defined by comma separated elements within curly braces.Items in a set are unordered ###Code set_a={12,21,"Hello",4+3j,12,21} print(set_a) print(set_a[2]) ###Output _____no_output_____ ###Markdown Python Dictionary Unordered collection of key-value pairsDefined within curly braces {} with each item in the form of a key-value pair ###Code dict_student={'name':"Andrew","major":"CS","score":130} print(dict_student["name"]) print(dict_student["phone"]) ###Output _____no_output_____ ###Markdown Conversion of Data Types ###Code float(50) int(99.6) str(29) int('10p') print(dict_student) print("hello "+dict_student['name']+". Congratulations on scoring "+str(dict_student['score'])) ###Output _____no_output_____ ###Markdown Convert one sequence to another ###Code a=[1,2,3] print(type(a)) s=set(a) print(type(s)) hello_string="hello" print(hello_string) list_hello=list(hello_string) print(list_hello) ###Output _____no_output_____ ###Markdown Python Input and Output Python output ###Code a=11 print("The value of a is ",a) print("the value of a is "+a) ###Output _____no_output_____ ###Markdown Output formatting ###Code val=41 str_val="garfield" print("{} is {} years old".format(str_val,val)) print("{} is {} years old".format(val,str_val)) print("{1} is {0} years old".format(val,str_val)) #how about keyword arguments to format the string print("The character {name} is {age} years old".format(name="Garfield",age="42")) #now combine positional with keyword arguments print("The show {show_name} is about a {0} and his {1}".format('cat','master',show_name="Garfield")) ###Output _____no_output_____ ###Markdown Python Inputthe input() function to take input feom user ###Code num= input("Enter a number") # print(num) print(num) ###Output _____no_output_____ ###Markdown OperatorsCarry out logical and arithmetic operationsOperator and operands Types of Operators1. Arithmetic2. Relational(Comparison)3. Boolean(Logical)4. Bitwise 5. Assignment6. Special Arithmetic operators+, -, *, /, %, //, ** are arithmetic operators ###Code x,y=30,12 print(x + y) ###Output _____no_output_____ ###Markdown Comparison OperatorsUsed to compare values, ==, !=, >=, >= ###Code a,b=10,21 print(a>b) ###Output _____no_output_____ ###Markdown Logical operatorsand, or, not operators ###Code a,b=True,False print(a and b) print(a or b) print(not b) ###Output _____no_output_____ ###Markdown Bitwise operatorsAct on operands as if they are strings of bindary digitsImportant to know the binray representationOperators are &, | , ~, ^, >>, <<AND, OR, NOT, XOR, RightShift, LeftShift ###Code a,b=11,3 print(a&b) ###Output _____no_output_____ ###Markdown Assignment operators =, +=, -=, *=, /=, //=, ***=, &=, |=, ^=, >>=, <<= ###Code a=2 a+=2 print(a) a%=2 print(a) ###Output _____no_output_____ ###Markdown Special OperatorsIdentity Operatorsis and is not are the identity operatorscheck if two values or variables are located in the same part of memory ###Code a=5 b=5 print(a is b) l1=[21,12,13] l2=[21,12,13] print(l1 is l2) str1="PSF" str2="PSF" print(str1 is str2) ###Output _____no_output_____ ###Markdown Membership operator ###Code lis=[1,3,5,7] print(1 in lis) di={'a':1,'b':2} print('a' in di) print(1 in di) ###Output _____no_output_____ ###Markdown if else ###Code num=-10 if num>0: print("positive") else: print("negative") ###Output _____no_output_____ ###Markdown if... elif.. else ###Code val=-10 if val>0: print("Positive") elif val2==0: print("0") else: print("Negative number") ###Output _____no_output_____ ###Markdown Nested If ###Code val1=20 if val>=0: if val == 0: print("Zero") else: print("Positive") else: print("Ngeative") ###Output _____no_output_____
notebooks/Dropout_and_DataAugmentation.ipynb
###Markdown Dropout and Data AugmentationIn this exercise we will implement two ways to reduce overfitting.Like the previous assignment, we will train ConvNets to recognize the categories in CIFAR-10. However unlike the previous assignment where we used 49,000 images for training, in this exercise we will use just 500 images for training.If we try to train a high-capacity model like a ConvNet on this small amount of data, we expect to overfit, and end up with a solution that does not generalize. We will see that we can drastically reduce overfitting by using dropout and data augmentation. ###Code # A bit of setup import numpy as np import matplotlib.pyplot as plt from time import time from skynet.neural_network.layers import * from skynet.neural_network.fast_layers import * from skynet.utils.data_utils import load_CIFAR10 %matplotlib inline plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots plt.rcParams['image.interpolation'] = 'nearest' plt.rcParams['image.cmap'] = 'gray' # for auto-reloading extenrnal modules # see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython %load_ext autoreload %autoreload 2 def rel_error(x, y): """ returns relative error """ return np.max(np.abs(x - y) / (np.maximum(1e-8, np.abs(x) + np.abs(y)))) ###Output _____no_output_____ ###Markdown Load dataFor this exercise our training set will contain 500 images and our validation and test sets will contain 1000 images as usual. ###Code from skynet.utils.data_utils import load_CIFAR10 def get_CIFAR10_data(num_training=500, num_validation=1000, num_test=1000, normalize=True): """ Load the CIFAR-10 dataset from disk and perform preprocessing to prepare it for the two-layer neural net classifier. These are the same steps as we used for the SVM, but condensed to a single function. """ # Load the raw CIFAR-10 data cifar10_dir = '../skynet/datasets/cifar-10-batches-py' X_train, y_train, X_test, y_test = load_CIFAR10(cifar10_dir) # Subsample the data mask = list(range(num_training, num_training + num_validation)) X_val = X_train[mask] y_val = y_train[mask] mask = list(range(num_training)) X_train = X_train[mask] y_train = y_train[mask] mask = list(range(num_test)) X_test = X_test[mask] y_test = y_test[mask] # Normalize the data: subtract the mean image if normalize: mean_image = np.mean(X_train, axis=0) X_train -= mean_image X_val -= mean_image X_test -= mean_image # Transpose so that channels come first X_train = X_train.transpose(0, 3, 1, 2).copy() X_val = X_val.transpose(0, 3, 1, 2).copy() X_test = X_test.transpose(0, 3, 1, 2).copy() return X_train, y_train, X_val, y_val, X_test, y_test # Invoke the above function to get our data. X_train, y_train, X_val, y_val, X_test, y_test = get_CIFAR10_data(num_training=500) print('Train data shape: ', X_train.shape) print('Train labels shape: ', y_train.shape) print('Validation data shape: ', X_val.shape) print('Validation labels shape: ', y_val.shape) print('Test data shape: ', X_test.shape) print('Test labels shape: ', y_test.shape) ###Output Train data shape: (500, 3, 32, 32) Train labels shape: (500,) Validation data shape: (1000, 3, 32, 32) Validation labels shape: (1000,) Test data shape: (1000, 3, 32, 32) Test labels shape: (1000,) ###Markdown OverfitNow that we've loaded our data, we will attempt to train a three layer convnet on this data. The three layer convnet has the architecture`conv - relu - pool - affine - relu - affine - softmax`We will use 32 5x5 filters, and our hidden affine layer will have 128 neurons.This is a very expressive model given that we have only 500 training samples, so we should expect to massively overfit this dataset, and achieve a training accuracy of nearly 0.9 with a much lower validation accuracy. ###Code from skynet.neural_network.classifiers.convnet import * from skynet.solvers.classifier_trainer import ClassifierTrainer model = init_three_layer_convnet(filter_size=5, num_filters=(32, 128)) trainer = ClassifierTrainer() best_model, loss_history, train_acc_history, val_acc_history = trainer.train( X_train, y_train, X_val, y_val, model, three_layer_convnet, dropout=None, reg=0.05, learning_rate=0.00005, batch_size=50, num_epochs=15, learning_rate_decay=1.0, update='rmsprop', verbose=True) # Visualize the loss and accuracy for our network trained on a small dataset plt.subplot(2, 1, 1) plt.plot(train_acc_history) plt.plot(val_acc_history) plt.title('accuracy vs time') plt.legend(['train', 'val'], loc=4) plt.xlabel('epoch') plt.ylabel('classification accuracy') plt.subplot(2, 1, 2) plt.plot(loss_history) plt.title('loss vs time') plt.xlabel('iteration') plt.ylabel('loss') plt.show() ###Output _____no_output_____ ###Markdown DropoutThe first way we will reduce overfitting is to use dropout.Open the file `cs231n/layers.py` and implement the `dropout_forward` and `dropout_backward` functions. We can check the forward pass by looking at the statistics of the outputs in train and test modes, and we can check the backward pass using numerical gradient checking. ###Code # Check the dropout forward pass x = np.random.randn(100, 100) dropout_param_train = {'p': 0.25, 'mode': 'train'} dropout_param_test = {'p': 0.25, 'mode': 'test'} out_train, _ = dropout_forward(x, dropout_param_train) out_test, _ = dropout_forward(x, dropout_param_test) # Test dropout training mode; about 25% of the elements should be nonzero print(np.mean(out_train != 0)) # Test dropout test mode; all of the elements should be nonzero print(np.mean(out_test != 0)) from skynet.utils.gradient_check import eval_numerical_gradient_array # Check the dropout backward pass x = np.random.randn(5, 4) dout = np.random.randn(*x.shape) dropout_param = {'p': 0.8, 'mode': 'train', 'seed': 123} dx_num = eval_numerical_gradient_array(lambda x: dropout_forward(x, dropout_param)[0], x, dout) _, cache = dropout_forward(x, dropout_param) dx = dropout_backward(dout, cache) # The error should be around 1e-12 print('Testing dropout_backward function:') print('dx error: ', rel_error(dx_num, dx)) ###Output Testing dropout_backward function: dx error: 5.51291055509e-14 ###Markdown Data AugmentationThe next way we will reduce overfitting is to implement data augmentation. Since we have very little training data, we will use what little training data we have to generate artificial data, and use this artificial data to train our network.CIFAR-10 images are 32x32, and up until this point we have used the entire image as input to our convnets. Now we will do something different: our convnet will expect a smaller input (say 28x28). Instead of feeding our training images directly to the convnet, at training time we will randomly crop each training image to 28x28, randomly flip half of the training images horizontally, and randomly adjust the contrast and tint of each training image.Open the file `cs231n/data_augmentation.py` and implement the `random_flips`, `random_crops`, `random_contrast`, and `random_tint` functions. In the same file we have implemented the `fixed_crops` function to get you started. When you are done you can run the cell below to visualize the effects of each type of data augmentation. ###Code from skynet.preprocessing.data_augmentation import * X = get_CIFAR10_data(num_training=100, normalize=False)[0] num_imgs = 8 print('X data type:', X.dtype) X = X[np.random.randint(100, size=num_imgs)] X_flip = random_flips(X) X_rand_crop = random_crops(X, (28, 28)) X_fixed_crop = random_crops(X, (28, 28)) # To give more dramatic visualizations we use large scales for random contrast # and tint adjustment. X_contrast = random_contrast(X, scale=(0.5, 1.0)) X_tint = random_tint(X, scale=(-50, 50)) next_plt = 1 for i in range(num_imgs): titles = ['original', 'flip', 'rand crop', 'fixed crop', 'contrast', 'tint'] for j, XX in enumerate([X, X_flip, X_rand_crop, X_fixed_crop, X_contrast, X_tint]): plt.subplot(num_imgs, 6, next_plt) img = XX[i].transpose(1, 2, 0) if j == 4: # For visualization purposes we rescale the pixel values of the # tinted images low, high = np.min(img), np.max(img) img = 255 * (img - low) / (high - low) plt.imshow(img.astype('uint8')) if i == 0: plt.title(titles[j]) plt.gca().axis('off') next_plt += 1 plt.show() ###Output X data type: float64 ###Markdown Train againWe will now train a new network with the same training data and the same architecture, but using data augmentation and dropout.If everything works, you should see a higher validation accuracy than above and a smaller gap between the training accuracy and the validation accuracy.Networks with dropout usually take a bit longer to train, so we will use more training epochs this time. ###Code input_shape = (3, 28, 28) def augment_fn(X): out = random_flips(random_crops(X, input_shape[1:])) out = random_tint(random_contrast(out)) return out def predict_fn(X): return fixed_crops(X, input_shape[1:], 'center') model = init_three_layer_convnet(filter_size=5, input_shape=input_shape, num_filters=(32, 128)) trainer = ClassifierTrainer() best_model, loss_history, train_acc_history, val_acc_history = trainer.train( X_train, y_train, X_val, y_val, model, three_layer_convnet, reg=0.05, learning_rate=0.00005, learning_rate_decay=1.0, batch_size=50, num_epochs=30, update='rmsprop', verbose=True, dropout=0.6, augment_fn=augment_fn, predict_fn=predict_fn) # Visualize the loss and accuracy for our network trained with dropout and data augmentation. # You should see less overfitting, and you may also see slightly better performance on the # validation set. plt.subplot(2, 1, 1) plt.plot(train_acc_history) plt.plot(val_acc_history) plt.title('accuracy vs time') plt.legend(['train', 'val'], loc=4) plt.xlabel('epoch') plt.ylabel('classification accuracy') plt.subplot(2, 1, 2) plt.plot(loss_history) plt.title('loss vs time') plt.xlabel('iteration') plt.ylabel('loss') plt.show() ###Output _____no_output_____
courses/11. Errors management in Python.ipynb
###Markdown Python: Errors management Goals:* Learn how to find the unique values in a dataset* Manage missing values in a dataset* Use the try/except block to avoid errors* Extract a year from a date, convert it to an integer and add the year column in a dataset Sets The **set()** function returns a **set** that contains the **unique elements** of a list. ###Code # Example animals = ["Dog", "Tiger", "Cat", "Cat", "Dog", "Dog"] unique_animals = set(animals) print(unique_animals) ###Output {'Dog', 'Cat', 'Tiger'} ###Markdown To add elements to a set, we use the **add()** method. ###Code # Example unique_animals.add("Turtle") print(unique_animals) ###Output {'Dog', 'Cat', 'Tiger', 'Turtle'} ###Markdown To remove an element, we use the **remove()** method. ###Code # Example unique_animals.remove("Cat") print(unique_animals) ###Output {'Dog', 'Tiger', 'Turtle'} ###Markdown To convert a set into a list, we use the **list()** function. ###Code unique_animals = list(unique_animals) print(unique_animals) ###Output ['Dog', 'Tiger', 'Turtle'] ###Markdown Training ###Code import csv f = open("legislators.csv") legislators = list(csv.reader(f)) print(legislators[0:5]) gender = [] for item in legislators: gender.append(item[3]) print(gender[0:50]) gender = set(gender) print(gender) ###Output {'M', '', 'gender', 'F'} ###Markdown Dataset exploration Let's look at all the unique party in our dataset. ###Code party = [] for item in legislators: party.append(item[6]) party = set(party) print(party) ###Output {'', 'Constitutional Unionist', 'American Labor', 'Readjuster', 'Whig', 'Crawford Republican', 'Unknown', 'Jacksonian', 'Populist', 'Socialist', 'Union Democrat', 'Prohibitionist', 'Coalitionist', 'Pro-Administration', 'Anti Masonic', 'National Greenbacker', 'Farmer-Labor', 'Adams Democrat', 'Adams', 'Conservative', 'Independent', 'Conservative Republican', 'Jackson Republican', 'Progressive Republican', 'Anti Jacksonian', 'Liberty', 'Anti-Lecompton Democrat', 'Silver Republican', 'Ind. Republican-Democrat', 'Anti Jackson', 'States Rights', 'Republican', 'Unconditional Unionist', 'Unionist', 'American', 'Democrat-Liberal', 'Anti-Administration', 'Ind. Whig', 'Anti-Jacksonian', 'Nonpartisan', 'party', 'Progressive', 'Nullifier', 'Union', 'Liberal Republican', 'Jackson', 'Free Soil', 'Law and Order', 'Union Labor', 'Republican-Conservative', 'Free Silver', 'Ind. Republican', 'Democratic and Union Labor', 'New Progressive', 'Federalist', 'Readjuster Democrat', 'Ind. Democrat', 'Democrat', 'Independent Democrat', 'Democratic Republican', 'Popular Democrat'} ###Markdown Missing values Let's replace all missing values in the party column with "No Party" label. ###Code for row in legislators: if row[6] == '': row[6] = "No Party" party = [] for item in legislators: party.append(item[6]) party = set(party) print(party) ###Output {'Constitutional Unionist', 'American Labor', 'Readjuster', 'Whig', 'Crawford Republican', 'Unknown', 'Jacksonian', 'Populist', 'Socialist', 'Union Democrat', 'Prohibitionist', 'No Party', 'Coalitionist', 'Pro-Administration', 'Anti Masonic', 'National Greenbacker', 'Farmer-Labor', 'Adams Democrat', 'Adams', 'Conservative', 'Independent', 'Conservative Republican', 'Jackson Republican', 'Progressive Republican', 'Anti Jacksonian', 'Liberty', 'Anti-Lecompton Democrat', 'Silver Republican', 'Ind. Republican-Democrat', 'Anti Jackson', 'States Rights', 'Republican', 'Unconditional Unionist', 'Unionist', 'American', 'Democrat-Liberal', 'Anti-Administration', 'Ind. Whig', 'Anti-Jacksonian', 'Nonpartisan', 'party', 'Progressive', 'Nullifier', 'Union', 'Liberal Republican', 'Jackson', 'Free Soil', 'Law and Order', 'Union Labor', 'Republican-Conservative', 'Free Silver', 'Ind. Republican', 'Democratic and Union Labor', 'New Progressive', 'Federalist', 'Readjuster Democrat', 'Ind. Democrat', 'Democrat', 'Independent Democrat', 'Democratic Republican', 'Popular Democrat'} ###Markdown Training Replace all missing values in the gender column with sex "M". ###Code for row in legislators: if row[3] == '': row[3] = "M" gender = [] for item in legislators: gender.append(item[3]) gender = set(gender) print(gender) ###Output {'M', 'F', 'gender'} ###Markdown Analysis of the years of birth The **split()** method is widely used to **extract information** about dates as shown in the following example. ###Code # Example date = "2022-01-04" date_parts = date.split('-') date_parts year = date_parts[0] year month = date_parts[1] month day = date_parts[2] day ###Output _____no_output_____ ###Markdown Training ###Code birth_years = [] for row in legislators: date = row[2] date_parts = date.split('-') birth_years.append(date_parts[0]) print(birth_years[0:10]) ###Output ['birthday', '1745', '1742', '1743', '1730', '1739', '', '1738', '1745', '1748'] ###Markdown Try / Except block ###Code # Motivation int('') ###Output _____no_output_____ ###Markdown The **try/except** block allows to continue the execution even if there is an error. ###Code # Example try: int('') except: print("Impossible to convert!") ###Output Impossible to convert! ###Markdown Let's take a closer look at what is in the exception class. ###Code try: int('') except Exception as e: print(type(e)) print(str(e)) ###Output <class 'ValueError'> invalid literal for int() with base 10: '' ###Markdown The keyword pass ###Code # Example numbers = [1,2,3,4,5,6,7,8,9,10] for i in numbers: try: int('') except Exception: print("There is an error!") ###Output There is an error! There is an error! There is an error! There is an error! There is an error! There is an error! There is an error! There is an error! There is an error! There is an error! ###Markdown In the try/except context, the **pass** keyword is used if you do not want to execute an action in case of an error. ###Code numbers = [1,2,3,4,5,6,7,8,9,10] for i in numbers: try: int('') except Exception: pass ###Output _____no_output_____ ###Markdown Training ###Code int_years = [] for year in birth_years: try: year = int(year) except Exception: pass int_years.append(year) print(int_years[0:42]) ###Output ['birthday', 1745, 1742, 1743, 1730, 1739, '', 1738, 1745, 1748, 1734, 1756, '', 1737, 1754, 1736, '', 1727, 1733, 1732, 1737, 1739, 1734, 1740, 1745, 1728, '', 1738, 1737, 1739, 1744, '', 1761, 1756, 1752, 1737, 1745, 1744, 1742, 1726, '', 1733] ###Markdown Convert the year of birth into integer in the dataset Training ###Code for row in legislators: birthday = row[2] birth_year = birthday.split('-')[0] try: birth_year = int(birth_year) except Exception: birth_year = 0 row.append(birth_year) legislators[0][7] = "birth_year" print(legislators[0:10]) ###Output [['last_name', 'first_name', 'birthday', 'gender', 'type', 'state', 'party', 'birth_year'], ['Bassett', 'Richard', '1745-04-02', 'M', 'sen', 'DE', 'Anti-Administration', 1745], ['Bland', 'Theodorick', '1742-03-21', 'M', 'rep', 'VA', 'No Party', 1742], ['Burke', 'Aedanus', '1743-06-16', 'M', 'rep', 'SC', 'No Party', 1743], ['Carroll', 'Daniel', '1730-07-22', 'M', 'rep', 'MD', 'No Party', 1730], ['Clymer', 'George', '1739-03-16', 'M', 'rep', 'PA', 'No Party', 1739], ['Contee', 'Benjamin', '', 'M', 'rep', 'MD', 'No Party', 0], ['Dalton', 'Tristram', '1738-05-28', 'M', 'sen', 'MA', 'Pro-Administration', 1738], ['Elmer', 'Jonathan', '1745-11-29', 'M', 'sen', 'NJ', 'Pro-Administration', 1745], ['Few', 'William', '1748-06-08', 'M', 'sen', 'GA', 'Anti-Administration', 1748]] ###Markdown Modify the values of the missing years Training ###Code last_value = 1 for row in legislators: if row[7] == 0: row[7] = last_value last_value = row[7] print(legislators[0:10]) ###Output [['last_name', 'first_name', 'birthday', 'gender', 'type', 'state', 'party', 'birth_year'], ['Bassett', 'Richard', '1745-04-02', 'M', 'sen', 'DE', 'Anti-Administration', 1745], ['Bland', 'Theodorick', '1742-03-21', 'M', 'rep', 'VA', 'No Party', 1742], ['Burke', 'Aedanus', '1743-06-16', 'M', 'rep', 'SC', 'No Party', 1743], ['Carroll', 'Daniel', '1730-07-22', 'M', 'rep', 'MD', 'No Party', 1730], ['Clymer', 'George', '1739-03-16', 'M', 'rep', 'PA', 'No Party', 1739], ['Contee', 'Benjamin', '', 'M', 'rep', 'MD', 'No Party', 1739], ['Dalton', 'Tristram', '1738-05-28', 'M', 'sen', 'MA', 'Pro-Administration', 1738], ['Elmer', 'Jonathan', '1745-11-29', 'M', 'sen', 'NJ', 'Pro-Administration', 1745], ['Few', 'William', '1748-06-08', 'M', 'sen', 'GA', 'Anti-Administration', 1748]]
Fake News Classifier/Fake_News_Classifier_NLP_TFIDF.ipynb
###Markdown Importing the DatasetDataset: https://www.kaggle.com/c/fake-news/data ###Code import pandas as pd import re df = pd.read_csv('fake-news/train.csv') df.head() df.isnull().sum() ###Output _____no_output_____ ###Markdown Get the Independent Features ###Code X = df.drop('label', axis=1) X.head() ###Output _____no_output_____ ###Markdown Get the Dependent features ###Code y=df['label'] y.head() df.shape df = df.dropna() df.head(10) messages=df.copy() messages.head(10) messages.reset_index(inplace=True) messages.head(10) messages['title'][6] ###Output _____no_output_____ ###Markdown Cleaning the Texts and Applying Stemming ###Code from nltk.corpus import stopwords from nltk.stem.porter import PorterStemmer ps = PorterStemmer() corpus = [] for i in range(0, len(messages)): review = re.sub('[^a-zA-Z]', ' ', messages['title'][i]) review = review.lower() review = review.split() review = [ps.stem(word) for word in review if not word in stopwords.words('english')] review = ' '.join(review) corpus.append(review) corpus[6] ###Output _____no_output_____ ###Markdown Making a TF-IDF Model using TfidfVectorizer ###Code from sklearn.feature_extraction.text import TfidfVectorizer tfidf_v=TfidfVectorizer(max_features=5000,ngram_range=(1,3)) X=tfidf_v.fit_transform(corpus).toarray() X.shape y=messages['label'] ###Output _____no_output_____ ###Markdown Divide the dataset into Train and Test set ###Code from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=0) tfidf_v.get_feature_names()[:15] tfidf_v.get_params() count_df = pd.DataFrame(X_train, columns=tfidf_v.get_feature_names()) count_df.head() import matplotlib.pyplot as plt ###Output _____no_output_____ ###Markdown Plotting the Confusion Matrix ###Code def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues): """ See full source and example: http://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45) plt.yticks(tick_marks, classes) if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] print("Normalized confusion matrix") else: print('Confusion matrix, without normalization') thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, cm[i, j], horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label') ###Output _____no_output_____ ###Markdown Multinomial Naive Bayes Classifier ###Code from sklearn.naive_bayes import MultinomialNB classifier=MultinomialNB() from sklearn.metrics import confusion_matrix, accuracy_score, classification_report import numpy as np import itertools classifier.fit(X_train, y_train) pred = classifier.predict(X_test) score = accuracy_score(y_test, pred) print("Accuracy: %0.3f" % score) cm = confusion_matrix(y_test, pred) plot_confusion_matrix(cm, classes=['FAKE', 'REAL']) ###Output Accuracy: 0.880 Confusion matrix, without normalization ###Markdown Multinomial Classifier with Hyper Parameter Tuning ###Code import warnings warnings.filterwarnings('ignore') previous_score=0 for alpha in np.arange(0,1,0.1): sub_classifier=MultinomialNB(alpha=alpha) sub_classifier.fit(X_train,y_train) y_pred=sub_classifier.predict(X_test) score = accuracy_score(y_test, y_pred) if score>previous_score: classifier=sub_classifier print("Alpha: {}, Score : {}".format(alpha,score)) ###Output Alpha: 0.0, Score : 0.8654515327257664 Alpha: 0.1, Score : 0.8765534382767192 Alpha: 0.2, Score : 0.8792046396023198 Alpha: 0.30000000000000004, Score : 0.8803645401822701 Alpha: 0.4, Score : 0.8803645401822701 Alpha: 0.5, Score : 0.8810273405136703 Alpha: 0.6000000000000001, Score : 0.8811930405965203 Alpha: 0.7000000000000001, Score : 0.8806959403479702 Alpha: 0.8, Score : 0.8806959403479702 Alpha: 0.9, Score : 0.8811930405965203 ###Markdown Passive Aggressive Classifier Algorithm ###Code from sklearn.linear_model import PassiveAggressiveClassifier linear_clf = PassiveAggressiveClassifier(max_iter=50) linear_clf.fit(X_train, y_train) pred = linear_clf.predict(X_test) score = accuracy_score(y_test, pred) print("Accuracy: %0.3f" % score) cm = confusion_matrix(y_test, pred) plot_confusion_matrix(cm, classes=['FAKE Data', 'REAL Data']) ###Output Confusion matrix, without normalization ###Markdown Finding the Most Fake and Real words in the News Get Features names ###Code feature_names = tfidf_v.get_feature_names() classifier.coef_[0] ###Output _____no_output_____ ###Markdown Most Real News ###Code sorted(zip(classifier.coef_[0], feature_names), reverse=True)[:20] ###Output _____no_output_____ ###Markdown Most Fake Words in the News ###Code sorted(zip(classifier.coef_[0], feature_names))[:10] ###Output _____no_output_____
notebooks/4-files/PY0101EN-4-1-ReadFile.ipynb
###Markdown Reading Files Python Welcome! This notebook will teach you about reading the text file in the Python Programming Language. By the end of this lab, you'll know how to read text files. Table of Contents Download Data Reading Text Files A Better Way to Open a File Estimated time needed: 40 min Download Data ###Code # Download Example file !wget /resources/data/Example1.txt https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/PY0101EN/labs/example1.txt ###Output _____no_output_____ ###Markdown Reading Text Files One way to read or write a file in Python is to use the built-in open function. The open function provides a File object that contains the methods and attributes you need in order to read, save, and manipulate the file. In this notebook, we will only cover .txt files. The first parameter you need is the file path and the file name. An example is shown as follow: The mode argument is optional and the default value is r. In this notebook we only cover two modes:  r Read mode for reading files w Write mode for writing files For the next example, we will use the text file Example1.txt. The file is shown as follow: We read the file: ###Code # Read the Example1.txt example1 = "/content/example1.txt" file1 = open(example1, "r") ###Output _____no_output_____ ###Markdown We can view the attributes of the file. The name of the file: ###Code # Print the path of file file1.name ###Output _____no_output_____ ###Markdown The mode the file object is in: ###Code # Print the mode of file, either 'r' or 'w' file1.mode ###Output _____no_output_____ ###Markdown We can read the file and assign it to a variable : ###Code # Read the file FileContent = file1.read() FileContent ###Output _____no_output_____ ###Markdown The /n means that there is a new line. We can print the file: ###Code # Print the file with '\n' as a new line print(FileContent) ###Output _____no_output_____ ###Markdown The file is of type string: ###Code # Type of file content type(FileContent) ###Output _____no_output_____ ###Markdown We must close the file object: ###Code # Close file after finish file1.close() ###Output _____no_output_____ ###Markdown A Better Way to Open a File Using the with statement is better practice, it automatically closes the file even if the code encounters an exception. The code will run everything in the indent block then close the file object. ###Code # Open file using with with open(example1, "r") as file1: FileContent = file1.read() print(FileContent) ###Output _____no_output_____ ###Markdown The file object is closed, you can verify it by running the following cell: ###Code # Verify if the file is closed file1.closed ###Output _____no_output_____ ###Markdown We can see the info in the file: ###Code # See the content of file print(FileContent) ###Output _____no_output_____ ###Markdown The syntax is a little confusing as the file object is after the as statement. We also don’t explicitly close the file. Therefore we summarize the steps in a figure: We don’t have to read the entire file, for example, we can read the first 4 characters by entering three as a parameter to the method **.read()**: ###Code # Read first four characters with open(example1, "r") as file1: print(file1.read(4)) ###Output _____no_output_____ ###Markdown Once the method .read(4) is called the first 4 characters are called. If we call the method again, the next 4 characters are called. The output for the following cell will demonstrate the process for different inputs to the method read(): ###Code # Read certain amount of characters with open(example1, "r") as file1: print(file1.read(4)) print(file1.read(4)) print(file1.read(7)) print(file1.read(15)) ###Output _____no_output_____ ###Markdown The process is illustrated in the below figure, and each color represents the part of the file read after the method read() is called: Here is an example using the same file, but instead we read 16, 5, and then 9 characters at a time: ###Code # Read certain amount of characters with open(example1, "r") as file1: print(file1.read(16)) print(file1.read(5)) print(file1.read(9)) ###Output _____no_output_____ ###Markdown We can also read one line of the file at a time using the method readline(): ###Code # Read one line with open(example1, "r") as file1: print("first line: " + file1.readline()) ###Output _____no_output_____ ###Markdown We can use a loop to iterate through each line: ###Code # Iterate through the lines with open(example1,"r") as file1: i = 0; for line in file1: print("Iteration", str(i), ": ", line) i = i + 1; ###Output _____no_output_____ ###Markdown We can use the method readlines() to save the text file to a list: ###Code # Read all lines and save as a list with open(example1, "r") as file1: FileasList = file1.readlines() ###Output _____no_output_____ ###Markdown Each element of the list corresponds to a line of text: ###Code # Print the first line FileasList[0] # Print the second line FileasList[1] # Print the third line FileasList[2] ###Output _____no_output_____
python-fundamentals-data-analysis-3.0/PythonFundamentos/Cap09/Mini-Projeto2/Mini-Projeto2 - Analise3.ipynb
###Markdown Data Science Academy - Python Fundamentos - Capítulo 9 Download: http://github.com/dsacademybr Mini-Projeto 2 - Análise Exploratória em Conjunto de Dados do Kaggle Análise 3 ###Code # Imports import os import subprocess import stat import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from datetime import datetime sns.set(style = "white") %matplotlib inline # Dataset clean_data_path = "dataset/autos.csv" df = pd.read_csv(clean_data_path,encoding = "latin-1") df.columns ###Output _____no_output_____ ###Markdown Preço médio do veículo por tipo de combustível e tipo de caixa de câmbio ###Code # Crie um Barplot com o Preço médio do veículo por tipo de combustível e tipo de caixa de câmbio figure, ax = plt.subplots(figsize=(12, 6)) sns.barplot(x='fuelType', y='price', hue='gearbox', palette='flare', data=df, capsize=.1) ax.set_title("Preço médio dos veículos por tipo de veículo e tipo de caixa de câmbio", fontdict={'size':18}) ax.xaxis.set_label_text('Preço médio', fontdict={'size': 14}) ax.yaxis.set_label_text('Tipo de combustível', fontdict={'size': 14}) plt.show() # Salvando o plot fig.savefig("plots/Analise3/fueltype-vehicleType-price.png") # Salvando o plot figure.savefig("plots/Analise3/fueltype-vehicleType-price-2.png") ###Output _____no_output_____ ###Markdown Potência média de um veículo por tipo de veículo e tipo de caixa de câmbio ###Code # Crie um Barplot com a Potência média de um veículo por tipo de veículo e tipo de caixa de câmbio figure, ax = plt.subplots(figsize=(12, 6)) sns.barplot(x='vehicleType', y='powerPS', hue='gearbox', palette='flare', data=df, capsize=.1) ax.set_title("Potência média dos veículos por tipo de veículo e tipo de caixa de câmbio", fontdict={'size':18}) ax.xaxis.set_label_text('Potência média', fontdict={'size': 14}) ax.yaxis.set_label_text('Tipo de veículo', fontdict={'size': 14}) plt.show() # Salvando o plot fig.savefig("plots/Analise3/vehicletype-fueltype-power.png") figure.savefig('plots/Analise3/vehicletype-fueltype-power-2.png') ###Output _____no_output_____
notebooks/04-convolutional-neural-networks/04-special-applications/02-neural-style-transfer/01-art-generation-with-neural-style-transfer.ipynb
###Markdown Deep Learning & Art: Neural Style TransferWelcome to the second assignment of this week. In this assignment, you will learn about Neural Style Transfer. This algorithm was created by Gatys et al. (2015) (https://arxiv.org/abs/1508.06576). **In this assignment, you will:**- Implement the neural style transfer algorithm - Generate novel artistic images using your algorithm Most of the algorithms you've studied optimize a cost function to get a set of parameter values. In Neural Style Transfer, you'll optimize a cost function to get pixel values! ###Code import os import sys import scipy.io import scipy.misc import matplotlib.pyplot as plt from matplotlib.pyplot import imshow from PIL import Image from nst_utils import * import numpy as np import tensorflow as tf %matplotlib inline ###Output _____no_output_____ ###Markdown 1 - Problem StatementNeural Style Transfer (NST) is one of the most fun techniques in deep learning. As seen below, it merges two images, namely, a "content" image (C) and a "style" image (S), to create a "generated" image (G). The generated image G combines the "content" of the image C with the "style" of image S. In this example, you are going to generate an image of the Louvre museum in Paris (content image C), mixed with a painting by Claude Monet, a leader of the impressionist movement (style image S).Let's see how you can do this. 2 - Transfer LearningNeural Style Transfer (NST) uses a previously trained convolutional network, and builds on top of that. The idea of using a network trained on a different task and applying it to a new task is called transfer learning. Following the original NST paper (https://arxiv.org/abs/1508.06576), we will use the VGG network. Specifically, we'll use VGG-19, a 19-layer version of the VGG network. This model has already been trained on the very large ImageNet database, and thus has learned to recognize a variety of low level features (at the earlier layers) and high level features (at the deeper layers). Run the following code to load parameters from the VGG model. This may take a few seconds. ###Code model = load_vgg_model("pretrained-model/imagenet-vgg-verydeep-19.mat") print(model) ###Output _____no_output_____ ###Markdown The model is stored in a python dictionary where each variable name is the key and the corresponding value is a tensor containing that variable's value. To run an image through this network, you just have to feed the image to the model. In TensorFlow, you can do so using the [tf.assign](https://www.tensorflow.org/api_docs/python/tf/assign) function. In particular, you will use the assign function like this: ```pythonmodel["input"].assign(image)```This assigns the image as an input to the model. After this, if you want to access the activations of a particular layer, say layer `4_2` when the network is run on this image, you would run a TensorFlow session on the correct tensor `conv4_2`, as follows: ```pythonsess.run(model["conv4_2"])``` 3 - Neural Style Transfer We will build the NST algorithm in three steps:- Build the content cost function $J_{content}(C,G)$- Build the style cost function $J_{style}(S,G)$- Put it together to get $J(G) = \alpha J_{content}(C,G) + \beta J_{style}(S,G)$. 3.1 - Computing the content costIn our running example, the content image C will be the picture of the Louvre Museum in Paris. Run the code below to see a picture of the Louvre. ###Code content_image = plt.imread("images/louvre_small.jpg") imshow(content_image) ###Output _____no_output_____ ###Markdown The content image (C) shows the Louvre museum's pyramid surrounded by old Paris buildings, against a sunny sky with a few clouds.** 3.1.1 - How do you ensure the generated image G matches the content of the image C?**As we saw in lecture, the earlier (shallower) layers of a ConvNet tend to detect lower-level features such as edges and simple textures, and the later (deeper) layers tend to detect higher-level features such as more complex textures as well as object classes. We would like the "generated" image G to have similar content as the input image C. Suppose you have chosen some layer's activations to represent the content of an image. In practice, you'll get the most visually pleasing results if you choose a layer in the middle of the network--neither too shallow nor too deep. (After you have finished this exercise, feel free to come back and experiment with using different layers, to see how the results vary.)So, suppose you have picked one particular hidden layer to use. Now, set the image C as the input to the pretrained VGG network, and run forward propagation. Let $a^{(C)}$ be the hidden layer activations in the layer you had chosen. (In lecture, we had written this as $a^{[l](C)}$, but here we'll drop the superscript $[l]$ to simplify the notation.) This will be a $n_H \times n_W \times n_C$ tensor. Repeat this process with the image G: Set G as the input, and run forward progation. Let $$a^{(G)}$$ be the corresponding hidden layer activation. We will define as the content cost function as:$$J_{content}(C,G) = \frac{1}{4 \times n_H \times n_W \times n_C}\sum _{ \text{all entries}} (a^{(C)} - a^{(G)})^2\tag{1} $$Here, $n_H, n_W$ and $n_C$ are the height, width and number of channels of the hidden layer you have chosen, and appear in a normalization term in the cost. For clarity, note that $a^{(C)}$ and $a^{(G)}$ are the volumes corresponding to a hidden layer's activations. In order to compute the cost $J_{content}(C,G)$, it might also be convenient to unroll these 3D volumes into a 2D matrix, as shown below. (Technically this unrolling step isn't needed to compute $J_{content}$, but it will be good practice for when you do need to carry out a similar operation later for computing the style const $J_{style}$.)**Exercise:** Compute the "content cost" using TensorFlow. **Instructions**: The 3 steps to implement this function are:1. Retrieve dimensions from a_G: - To retrieve dimensions from a tensor X, use: `X.get_shape().as_list()`2. Unroll a_C and a_G as explained in the picture above - If you are stuck, take a look at [Hint1](https://www.tensorflow.org/versions/r1.3/api_docs/python/tf/transpose) and [Hint2](https://www.tensorflow.org/versions/r1.2/api_docs/python/tf/reshape).3. Compute the content cost: - If you are stuck, take a look at [Hint3](https://www.tensorflow.org/api_docs/python/tf/reduce_sum), [Hint4](https://www.tensorflow.org/api_docs/python/tf/square) and [Hint5](https://www.tensorflow.org/api_docs/python/tf/subtract). ###Code # GRADED FUNCTION: compute_content_cost def compute_content_cost(a_C, a_G): """ Computes the content cost Arguments: a_C -- tensor of dimension (1, n_H, n_W, n_C), hidden layer activations representing content of the image C a_G -- tensor of dimension (1, n_H, n_W, n_C), hidden layer activations representing content of the image G Returns: J_content -- scalar that you compute using equation 1 above. """ ### START CODE HERE ### # Retrieve dimensions from a_G (≈1 line) m, n_H, n_W, n_C = a_G.get_shape().as_list() # Reshape a_C and a_G (≈2 lines) a_C_unrolled = tf.transpose(a_C) a_G_unrolled = tf.transpose(a_G) # compute the cost with tensorflow (≈1 line) J_content = (1/ (4* n_H * n_W * n_C)) * tf.reduce_sum(tf.pow((a_G_unrolled - a_C_unrolled), 2)) ### END CODE HERE ### return J_content tf.reset_default_graph() with tf.Session() as test: tf.set_random_seed(1) a_C = tf.random_normal([1, 4, 4, 3], mean=1, stddev=4) a_G = tf.random_normal([1, 4, 4, 3], mean=1, stddev=4) J_content = compute_content_cost(a_C, a_G) print("J_content = " + str(J_content.eval())) ###Output _____no_output_____ ###Markdown **Expected Output**: **J_content** 6.76559 **What you should remember**:- The content cost takes a hidden layer activation of the neural network, and measures how different $a^{(C)}$ and $a^{(G)}$ are. - When we minimize the content cost later, this will help make sure $G$ has similar content as $C$. 3.2 - Computing the style costFor our running example, we will use the following style image: ###Code style_image = plt.imread("images/monet.jpg") imshow(style_image) ###Output _____no_output_____ ###Markdown This painting was painted in the style of *[impressionism](https://en.wikipedia.org/wiki/Impressionism)*.Lets see how you can now define a "style" const function $J_{style}(S,G)$. 3.2.1 - Style matrixThe style matrix is also called a "Gram matrix." In linear algebra, the Gram matrix G of a set of vectors $(v_{1},\dots ,v_{n})$ is the matrix of dot products, whose entries are ${\displaystyle G_{ij} = v_{i}^T v_{j} = np.dot(v_{i}, v_{j}) }$. In other words, $G_{ij}$ compares how similar $v_i$ is to $v_j$: If they are highly similar, you would expect them to have a large dot product, and thus for $G_{ij}$ to be large. Note that there is an unfortunate collision in the variable names used here. We are following common terminology used in the literature, but $G$ is used to denote the Style matrix (or Gram matrix) as well as to denote the generated image $G$. We will try to make sure which $G$ we are referring to is always clear from the context. In NST, you can compute the Style matrix by multiplying the "unrolled" filter matrix with their transpose:The result is a matrix of dimension $(n_C,n_C)$ where $n_C$ is the number of filters. The value $G_{ij}$ measures how similar the activations of filter $i$ are to the activations of filter $j$. One important part of the gram matrix is that the diagonal elements such as $G_{ii}$ also measures how active filter $i$ is. For example, suppose filter $i$ is detecting vertical textures in the image. Then $G_{ii}$ measures how common vertical textures are in the image as a whole: If $G_{ii}$ is large, this means that the image has a lot of vertical texture. By capturing the prevalence of different types of features ($G_{ii}$), as well as how much different features occur together ($G_{ij}$), the Style matrix $G$ measures the style of an image. **Exercise**:Using TensorFlow, implement a function that computes the Gram matrix of a matrix A. The formula is: The gram matrix of A is $G_A = AA^T$. If you are stuck, take a look at [Hint 1](https://www.tensorflow.org/api_docs/python/tf/matmul) and [Hint 2](https://www.tensorflow.org/api_docs/python/tf/transpose). ###Code # GRADED FUNCTION: gram_matrix def gram_matrix(A): """ Argument: A -- matrix of shape (n_C, n_H*n_W) Returns: GA -- Gram matrix of A, of shape (n_C, n_C) """ ### START CODE HERE ### (≈1 line) GA = tf.matmul(A, tf.transpose(A)) ### END CODE HERE ### return GA tf.reset_default_graph() with tf.Session() as test: tf.set_random_seed(1) A = tf.random_normal([3, 2*1], mean=1, stddev=4) GA = gram_matrix(A) print("GA = " + str(GA.eval())) ###Output _____no_output_____ ###Markdown **Expected Output**: **GA** [[ 6.42230511 -4.42912197 -2.09668207] [ -4.42912197 19.46583748 19.56387138] [ -2.09668207 19.56387138 20.6864624 ]] 3.2.2 - Style cost After generating the Style matrix (Gram matrix), your goal will be to minimize the distance between the Gram matrix of the "style" image S and that of the "generated" image G. For now, we are using only a single hidden layer $a^{[l]}$, and the corresponding style cost for this layer is defined as: $$J_{style}^{[l]}(S,G) = \frac{1}{4 \times {n_C}^2 \times (n_H \times n_W)^2} \sum _{i=1}^{n_C}\sum_{j=1}^{n_C}(G^{(S)}_{ij} - G^{(G)}_{ij})^2\tag{2} $$where $G^{(S)}$ and $G^{(G)}$ are respectively the Gram matrices of the "style" image and the "generated" image, computed using the hidden layer activations for a particular hidden layer in the network. **Exercise**: Compute the style cost for a single layer. **Instructions**: The 3 steps to implement this function are:1. Retrieve dimensions from the hidden layer activations a_G: - To retrieve dimensions from a tensor X, use: `X.get_shape().as_list()`2. Unroll the hidden layer activations a_S and a_G into 2D matrices, as explained in the picture above. - You may find [Hint1](https://www.tensorflow.org/versions/r1.3/api_docs/python/tf/transpose) and [Hint2](https://www.tensorflow.org/versions/r1.2/api_docs/python/tf/reshape) useful.3. Compute the Style matrix of the images S and G. (Use the function you had previously written.) 4. Compute the Style cost: - You may find [Hint3](https://www.tensorflow.org/api_docs/python/tf/reduce_sum), [Hint4](https://www.tensorflow.org/api_docs/python/tf/square) and [Hint5](https://www.tensorflow.org/api_docs/python/tf/subtract) useful. ###Code # GRADED FUNCTION: compute_layer_style_cost def compute_layer_style_cost(a_S, a_G): """ Arguments: a_S -- tensor of dimension (1, n_H, n_W, n_C), hidden layer activations representing style of the image S a_G -- tensor of dimension (1, n_H, n_W, n_C), hidden layer activations representing style of the image G Returns: J_style_layer -- tensor representing a scalar value, style cost defined above by equation (2) """ ### START CODE HERE ### # Retrieve dimensions from a_G (≈1 line) m, n_H, n_W, n_C = a_G.get_shape().as_list() # Reshape the images to have them of shape (n_H*n_W, n_C) (≈2 lines) a_S = tf.transpose(tf.reshape(a_S, [n_H*n_W, n_C])) a_G = tf.transpose(tf.reshape(a_G, [n_H*n_W, n_C])) # Computing gram_matrices for both images S and G (≈2 lines) GS = gram_matrix(a_S) GG = gram_matrix(a_G) # Computing the loss (≈1 line) J_style_layer = (1./(4 * n_C**2 * (n_H*n_W)**2)) * tf.reduce_sum(tf.pow((GS - GG), 2)) ### END CODE HERE ### return J_style_layer tf.reset_default_graph() with tf.Session() as test: tf.set_random_seed(1) a_S = tf.random_normal([1, 4, 4, 3], mean=1, stddev=4) a_G = tf.random_normal([1, 4, 4, 3], mean=1, stddev=4) J_style_layer = compute_layer_style_cost(a_S, a_G) print("J_style_layer = " + str(J_style_layer.eval())) ###Output _____no_output_____ ###Markdown **Expected Output**: **J_style_layer** 9.19028 3.2.3 Style WeightsSo far you have captured the style from only one layer. We'll get better results if we "merge" style costs from several different layers. After completing this exercise, feel free to come back and experiment with different weights to see how it changes the generated image $G$. But for now, this is a pretty reasonable default: ###Code STYLE_LAYERS = [ ('conv1_1', 0.2), ('conv2_1', 0.2), ('conv3_1', 0.2), ('conv4_1', 0.2), ('conv5_1', 0.2)] ###Output _____no_output_____ ###Markdown You can combine the style costs for different layers as follows:$$J_{style}(S,G) = \sum_{l} \lambda^{[l]} J^{[l]}_{style}(S,G)$$where the values for $\lambda^{[l]}$ are given in `STYLE_LAYERS`. We've implemented a compute_style_cost(...) function. It simply calls your `compute_layer_style_cost(...)` several times, and weights their results using the values in `STYLE_LAYERS`. Read over it to make sure you understand what it's doing. <!-- 2. Loop over (layer_name, coeff) from STYLE_LAYERS: a. Select the output tensor of the current layer. As an example, to call the tensor from the "conv1_1" layer you would do: out = model["conv1_1"] b. Get the style of the style image from the current layer by running the session on the tensor "out" c. Get a tensor representing the style of the generated image from the current layer. It is just "out". d. Now that you have both styles. Use the function you've implemented above to compute the style_cost for the current layer e. Add (style_cost x coeff) of the current layer to overall style cost (J_style)3. Return J_style, which should now be the sum of the (style_cost x coeff) for each layer.!--> ###Code def compute_style_cost(model, STYLE_LAYERS): """ Computes the overall style cost from several chosen layers Arguments: model -- our tensorflow model STYLE_LAYERS -- A python list containing: - the names of the layers we would like to extract style from - a coefficient for each of them Returns: J_style -- tensor representing a scalar value, style cost defined above by equation (2) """ # initialize the overall style cost J_style = 0 for layer_name, coeff in STYLE_LAYERS: # Select the output tensor of the currently selected layer out = model[layer_name] # Set a_S to be the hidden layer activation from the layer we have selected, by running the session on out a_S = sess.run(out) # Set a_G to be the hidden layer activation from same layer. Here, a_G references model[layer_name] # and isn't evaluated yet. Later in the code, we'll assign the image G as the model input, so that # when we run the session, this will be the activations drawn from the appropriate layer, with G as input. a_G = out # Compute style_cost for the current layer J_style_layer = compute_layer_style_cost(a_S, a_G) # Add coeff * J_style_layer of this layer to overall style cost J_style += coeff * J_style_layer return J_style ###Output _____no_output_____ ###Markdown **Note**: In the inner-loop of the for-loop above, `a_G` is a tensor and hasn't been evaluated yet. It will be evaluated and updated at each iteration when we run the TensorFlow graph in model_nn() below.<!-- How do you choose the coefficients for each layer? The deeper layers capture higher-level concepts, and the features in the deeper layers are less localized in the image relative to each other. So if you want the generated image to softly follow the style image, try choosing larger weights for deeper layers and smaller weights for the first layers. In contrast, if you want the generated image to strongly follow the style image, try choosing smaller weights for deeper layers and larger weights for the first layers!-->**What you should remember**:- The style of an image can be represented using the Gram matrix of a hidden layer's activations. However, we get even better results combining this representation from multiple different layers. This is in contrast to the content representation, where usually using just a single hidden layer is sufficient.- Minimizing the style cost will cause the image $G$ to follow the style of the image $S$. 3.3 - Defining the total cost to optimize Finally, let's create a cost function that minimizes both the style and the content cost. The formula is: $$J(G) = \alpha J_{content}(C,G) + \beta J_{style}(S,G)$$**Exercise**: Implement the total cost function which includes both the content cost and the style cost. ###Code # GRADED FUNCTION: total_cost def total_cost(J_content, J_style, alpha = 10, beta = 40): """ Computes the total cost function Arguments: J_content -- content cost coded above J_style -- style cost coded above alpha -- hyperparameter weighting the importance of the content cost beta -- hyperparameter weighting the importance of the style cost Returns: J -- total cost as defined by the formula above. """ ### START CODE HERE ### (≈1 line) J = alpha * J_content + beta * J_style ### END CODE HERE ### return J tf.reset_default_graph() with tf.Session() as test: np.random.seed(3) J_content = np.random.randn() J_style = np.random.randn() J = total_cost(J_content, J_style) print("J = " + str(J)) ###Output _____no_output_____ ###Markdown **Expected Output**: **J** 35.34667875478276 **What you should remember**:- The total cost is a linear combination of the content cost $J_{content}(C,G)$ and the style cost $J_{style}(S,G)$- $\alpha$ and $\beta$ are hyperparameters that control the relative weighting between content and style 4 - Solving the optimization problem Finally, let's put everything together to implement Neural Style Transfer!Here's what the program will have to do:1. Create an Interactive Session2. Load the content image 3. Load the style image4. Randomly initialize the image to be generated 5. Load the VGG16 model7. Build the TensorFlow graph: - Run the content image through the VGG16 model and compute the content cost - Run the style image through the VGG16 model and compute the style cost - Compute the total cost - Define the optimizer and the learning rate8. Initialize the TensorFlow graph and run it for a large number of iterations, updating the generated image at every step.Lets go through the individual steps in detail. You've previously implemented the overall cost $J(G)$. We'll now set up TensorFlow to optimize this with respect to $G$. To do so, your program has to reset the graph and use an "[Interactive Session](https://www.tensorflow.org/api_docs/python/tf/InteractiveSession)". Unlike a regular session, the "Interactive Session" installs itself as the default session to build a graph. This allows you to run variables without constantly needing to refer to the session object, which simplifies the code. Lets start the interactive session. ###Code # Reset the graph tf.reset_default_graph() # Start interactive session sess = tf.InteractiveSession() ###Output _____no_output_____ ###Markdown Let's load, reshape, and normalize our "content" image (the Louvre museum picture): ###Code content_image = plt.imread("images/louvre_small.jpg") content_image = reshape_and_normalize_image(content_image) ###Output _____no_output_____ ###Markdown Let's load, reshape and normalize our "style" image (Claude Monet's painting): ###Code style_image = plt.imread("images/monet.jpg") style_image = reshape_and_normalize_image(style_image) ###Output _____no_output_____ ###Markdown Now, we initialize the "generated" image as a noisy image created from the content_image. By initializing the pixels of the generated image to be mostly noise but still slightly correlated with the content image, this will help the content of the "generated" image more rapidly match the content of the "content" image. (Feel free to look in `nst_utils.py` to see the details of `generate_noise_image(...)`; to do so, click "File-->Open..." at the upper-left corner of this Jupyter notebook.) ###Code generated_image = generate_noise_image(content_image) imshow(generated_image[0]) ###Output _____no_output_____ ###Markdown Next, as explained in part (2), let's load the VGG16 model. ###Code model = load_vgg_model("pretrained-model/imagenet-vgg-verydeep-19.mat") ###Output _____no_output_____ ###Markdown To get the program to compute the content cost, we will now assign `a_C` and `a_G` to be the appropriate hidden layer activations. We will use layer `conv4_2` to compute the content cost. The code below does the following:1. Assign the content image to be the input to the VGG model.2. Set a_C to be the tensor giving the hidden layer activation for layer "conv4_2".3. Set a_G to be the tensor giving the hidden layer activation for the same layer. 4. Compute the content cost using a_C and a_G. ###Code # Assign the content image to be the input of the VGG model. sess.run(model['input'].assign(content_image)) # Select the output tensor of layer conv4_2 out = model['conv4_2'] # Set a_C to be the hidden layer activation from the layer we have selected a_C = sess.run(out) # Set a_G to be the hidden layer activation from same layer. Here, a_G references model['conv4_2'] # and isn't evaluated yet. Later in the code, we'll assign the image G as the model input, so that # when we run the session, this will be the activations drawn from the appropriate layer, with G as input. a_G = out # Compute the content cost J_content = compute_content_cost(a_C, a_G) ###Output _____no_output_____ ###Markdown **Note**: At this point, a_G is a tensor and hasn't been evaluated. It will be evaluated and updated at each iteration when we run the Tensorflow graph in model_nn() below. ###Code # Assign the input of the model to be the "style" image sess.run(model['input'].assign(style_image)) # Compute the style cost J_style = compute_style_cost(model, STYLE_LAYERS) ###Output _____no_output_____ ###Markdown **Exercise**: Now that you have J_content and J_style, compute the total cost J by calling `total_cost()`. Use `alpha = 10` and `beta = 40`. ###Code ### START CODE HERE ### (1 line) J = total_cost(J_content, J_style, alpha = 10, beta = 40) ### END CODE HERE ### ###Output _____no_output_____ ###Markdown You'd previously learned how to set up the Adam optimizer in TensorFlow. Lets do that here, using a learning rate of 2.0. [See reference](https://www.tensorflow.org/api_docs/python/tf/train/AdamOptimizer) ###Code # define optimizer (1 line) optimizer = tf.train.AdamOptimizer(2.0) # define train_step (1 line) train_step = optimizer.minimize(J) ###Output _____no_output_____ ###Markdown **Exercise**: Implement the model_nn() function which initializes the variables of the tensorflow graph, assigns the input image (initial generated image) as the input of the VGG16 model and runs the train_step for a large number of steps. ###Code def model_nn(sess, input_image, num_iterations = 2000): # Initialize global variables (you need to run the session on the initializer) ### START CODE HERE ### (1 line) sess.run(tf.global_variables_initializer()) ### END CODE HERE ### # Run the noisy input image (initial generated image) through the model. Use assign(). ### START CODE HERE ### (1 line) sess.run(model['input'].assign(input_image)) ### END CODE HERE ### for i in range(num_iterations): # Run the session on the train_step to minimize the total cost ### START CODE HERE ### (1 line) sess.run(train_step) ### END CODE HERE ### # Compute the generated image by running the session on the current model['input'] ### START CODE HERE ### (1 line) generated_image = sess.run(model['input']) ### END CODE HERE ### # Print every 20 iteration. if i%100 == 0: Jt, Jc, Js = sess.run([J, J_content, J_style]) print("Iteration " + str(i) + " :") print("total cost = " + str(Jt)) print("content cost = " + str(Jc)) print("style cost = " + str(Js)) # save current generated image in the "/output" directory save_image("output/" + str(i) + ".png", generated_image) # save last generated image save_image('output/generated_image.jpg', generated_image) return generated_image ###Output _____no_output_____ ###Markdown Run the following cell to generate an artistic image. It should take about 3min on CPU for every 20 iterations but you start observing attractive results after ≈140 iterations. Neural Style Transfer is generally trained using GPUs. ###Code model_nn(sess, generated_image) ###Output _____no_output_____
notebooks/67-PRMT-2355--Vision-core-extract-not-sent-July-half-August-2021.ipynb
###Markdown PRMT-2355 Vision 'Core extract not sent' transfers July & Half August 2021 ContextVision have got back to us regarding ‘pending’ transfers, and would like a list of transfers for them to look into to help diagnose the issue. ‘Pending’ transfers in this context are transfers that have gotten stuck in transit, have no error code(s) but have failed to be received by the receiving practice (i.e. this would include: the transfer outcome failure type as ‘core extract not sent’). ScopeGenerate list of transfers for July (14 day cut off) and beginning of August where Vision is the sender and the failure type is ‘core extract not sent’ with no error codes. List should have:* Sending NACs* Recieving NACs* Recieving NACs supplier * Time stamp* Conversation ID ###Code import pandas as pd from datetime import datetime transfer_files = [ "s3://prm-gp2gp-transfer-data-preprod/v4/2021/7/transfers.parquet", "s3://prm-gp2gp-notebook-data-prod/PRMT-2355-half-august-data-with-14-day-cutoff/transfers/v4/2021/8/transfers.parquet" ] transfers_raw = pd.concat(( pd.read_parquet(f) for f in transfer_files )) transfers = transfers_raw.copy() # Supplier name mapping supplier_renaming = { "EGTON MEDICAL INFORMATION SYSTEMS LTD (EMIS)":"EMIS", "IN PRACTICE SYSTEMS LTD":"Vision", "MICROTEST LTD":"Microtest", "THE PHOENIX PARTNERSHIP":"TPP", None: "Unknown" } # Generate ASID lookup that contains all the most recent entry for all ASIDs encountered asid_lookup_file_location = "s3://prm-gp2gp-asid-lookup-preprod/" asid_lookup_files = [ "2021/7/asidLookup.csv.gz", "2021/8/asidLookup.csv.gz", "2021/9/asidLookup.csv.gz" ] asid_lookup_input_files = [asid_lookup_file_location + f for f in asid_lookup_files] asid_lookup = pd.concat(( pd.read_csv(f) for f in asid_lookup_input_files )).drop_duplicates().groupby("ASID").last().reset_index() lookup = asid_lookup[["ASID", "NACS","OrgName"]] transfers = transfers.merge(lookup, left_on='requesting_practice_asid',right_on='ASID',how='left') transfers = transfers.rename({'ASID': 'requesting_supplier_asid', 'NACS': 'requesting_ods_code','OrgName':'requesting_practice_name'}, axis=1) transfers = transfers.merge(lookup, left_on='sending_practice_asid',right_on='ASID',how='left') transfers = transfers.rename({'ASID': 'sending_supplier_asid', 'NACS': 'sending_ods_code','OrgName':'sending_practice_name'}, axis=1) # Making the status to be more human readable here transfers["status"] = transfers["status"].str.replace("_", " ").str.title() # filter data to just include the first 2 weeks (15 days) of august date_filter_bool = transfers["date_requested"] < datetime(2021, 8, 16) transfers = transfers[date_filter_bool] # filter for Vision as the sender wi vision_sender_bool = transfers["sending_supplier"]=="Vision" core_extract_not_sent_bool = transfers["failure_reason"]=="Core Extract not Sent" vision_sender_where_core_extract_not_sent = transfers[vision_sender_bool & core_extract_not_sent_bool].copy() sorted_vision_sender_where_core_extract_not_sent = vision_sender_where_core_extract_not_sent.sort_values(by="date_requested", ascending=False).reset_index() columns_to_keep = ['conversation_id', 'date_requested', "requesting_ods_code", "requesting_practice_name", "sending_ods_code", "sending_practice_name", 'requesting_supplier', 'sending_supplier'] sorted_vision_sender_where_core_extract_not_sent = sorted_vision_sender_where_core_extract_not_sent[columns_to_keep] sorted_vision_sender_where_core_extract_not_sent with pd.ExcelWriter("Vision 'Core extract not sent' transfers July & Half August 2021 PRMT-2355.xlsx") as writer: sorted_vision_sender_where_core_extract_not_sent.to_excel(writer, sheet_name="All",index=False) ###Output _____no_output_____
experiments/tl_1v2/oracle.run1-oracle.run2/trials/21/trial.ipynb
###Markdown Transfer Learning Template ###Code %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 ###Output _____no_output_____ ###Markdown Allowed ParametersThese are allowed parameters, not defaultsEach 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 ###Code 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": ["unit_power"], "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": ["unit_power"], "episode_transforms": [], "domain_prefix": "ORACLE.run2_", }, ], "dataset_seed": 7, "seed": 7, } # 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) ###Output _____no_output_____
aux8/Auxiliar_8.ipynb
###Markdown CC3501 - Aux 8: Método de Diferencias Finitas **Profesor: Daniel Calderón** **Auxiliares: Diego Donoso y Pablo Pizarro** **Ayudantes: Francisco Muñoz, Matías Rojas y Sebastián Contreras** Fecha: 06/06/2019 Pregunta 1 - Métodos Numéricos - Ecuación de LaplaceSe sabe que en un problema de flujo en suelos la carga del sistema h(x,y) (O energía potencial) responde a la ecuación de Laplace, la cual asumiendo asumiendo igual permeabilidad se cumple que:$$\frac{\partial^2h}{\partial x^2} + \frac{\partial^2h}{\partial y^2} + \frac{\partial^2h}{\partial z^2} = 0$$Como prestigioso ingeniero se le pide modelar el problema de un estanque de agua de 50 metrosde ancho y 25 metros de alto, relleno de áridos (piedras, gravas, etc.) el cual se muestra en la figura.Este se encuentra abierto a la atmósfera en su superficie superior y no posee filtraciones en superímetro.![image.png](attachment:image.png) a) Discretize el problema considerando dh = 1m ###Code # Importamos librerías import numpy as np import matplotlib.pyplot as plt import tqdm ITERATIONS = 10000 # Número de iteraciones # Reemplace los valores del sistema ancho = 1 alto = 1 dh = 0.1 # Almacenamos cantidad de celdas de la matriz w = int(ancho / dh) h = int(alto / dh) # Creamos la matriz (mallado) matrix = np.zeros((h, w)) # Definimos la condición de borde matrix[0, :] = alto # ¿Se requiere de más condiciones de borde? ###Output _____no_output_____ ###Markdown b) Encuentre la expresión para calcular la carga h(x,y) en cada punto de su discretización ESCRIBA AQUÍ SU EXPRESIÓN El siguiente código recorre todo el dominio, resolviendo la ecuación: ###Code for _ in tqdm.tqdm(range(ITERATIONS)): # Borde izquierdo for i in range(1, h - 1): matrix[i, 0] = 0.25 * (2 * matrix[i, 1] + matrix[i - 1, 0] + matrix[i + 1, 0]) # Borde derecho for i in range(1, h - 1): matrix[i, w - 1] = 0.25 * (2 * matrix[i, w - 2] + matrix[i - 1, w - 1] + matrix[i + 1, w - 1]) # Borde inferior for j in range(1, w - 1): matrix[h - 1, j] = 0.25 * (2 * matrix[h - 2, j] + matrix[h - 1, j - 1] + matrix[h - 1, j + 1]) # Esquina izquierda matrix[h - 1, 0] = 0.5 * (matrix[h - 2, 0] + matrix[h - 1, 1]) # Esquina derecha matrix[h - 1, w - 1] = 0.5 * (matrix[h - 2, w - 1] + matrix[h - 1, w - 2]) # Trabajamos en el interior del sistema for i in range(1, h - 1): # fila for j in range(1, w - 1): # columnas matrix[i, j] = 0.25 * (matrix[i - 1, j] + matrix[i + 1, j] + matrix[i, j - 1] + matrix[i, j + 1]) ###Output 100%|██████████████████████████████████████████████████████████████████████████| 10000/10000 [00:01<00:00, 6926.09it/s] ###Markdown El siguiente código genera un gráfico del sistema ###Code def generarGrafico(m): fig = plt.figure() ax = fig.add_subplot(111) # Se agrega grafico al plot cax = ax.imshow(m) fig.colorbar(cax) ax.set_xlabel('x') ax.set_ylabel('y') ax.set_title('Función potencial h(x,y)') plt.show() generarGrafico(matrix) ###Output _____no_output_____ ###Markdown c) ¿Qué debería suceder en la solución si el estanque posee una filtración en su base, en la cual se registra una carga constante de 50m?, ¿Esta es tipo Dirichlet o Neumann? Grafique su solución. ###Code # ESCRIBA AQUÍ SU CÓDIGO # GRAFIQUE LA SOLUCIÓN ###Output _____no_output_____ ###Markdown d) Si existe un sólido dentro del dominio (suelo) el cual imprime una condición de borde de Neumann, ¿Qué cambios propondría en el código de b) para solucionar el problema?. Evalúe el caso c) considerando una región cudrada de tamaño 10x10 en el medio del estanque. ###Code # Su código debe ser capaz de resolver un problema con una región NaN en su interior ###Output _____no_output_____
notebooks/monomer_analysis.ipynb
###Markdown Analysis of *-seq data from satellite monomers ###Code from __future__ import division %pylab inline import seaborn as sns sns.set_style('ticks') sns.set_context('paper') from scipy.stats import kendalltau,pearsonr,spearmanr def parse_monomer_cvg(fn,norm=False): data = {} reads = {} with open(fn,'r') as f: for line in f: line = line.strip().split() name = line[0] + ':' + line[1] + '-' + line[2] cvg = int(line[-1]) data[name] = cvg if line[0] in reads: reads[line[0]] += cvg else: reads[line[0]] = cvg if norm: tot = 0 for name in reads.keys(): tot += reads[name] for name in data.keys(): chrom = name.split(':')[0] if reads[chrom] != 0: data[name] *= reads[chrom]/tot return data def parse_rnafold(fn): ctr = 0 data = {} with open(fn,'r') as f: for line in f: line = line.rstrip() if '>' == line[0]: name = line.strip('>') data[name] = {} ctr = 0 elif ctr == 1: data[name]['seq'] = line elif ctr == 2: line = line.split() data[name]['mfe_deltaG'] = float(line[-1].strip('()')) elif ctr == 3: line = line.split() data[name]['ensemble_deltaG'] = float(line[-1].strip('[]')) ctr +=1 return data def parse_nearest(fn): data = {} nboxes = {} with open(fn,'r') as f: for line in f: line = line.rstrip().split() name = line[0] + ':' + line[1] + '-' + line[2] data[name] = {} data[name]['d'] = int(line[-1]) try: data[name]['score'] = float(line[-3]) except: data[name]['score'] = '-1' if line[0] not in nboxes: nboxes[line[0]] = 1 else: nboxes[line[0]] += 1 return data,nboxes cenpa_d = parse_monomer_cvg('../data/cenpa_huref.cons_mono.cvg',norm=False) ssdna_d = parse_monomer_cvg('../data/raji_ssdna.cons_mono.cvg',norm=False) norm_d = parse_monomer_cvg('../data/input.human_no_ambig.cons_mono.cvg',norm=True) norm_d2 = parse_monomer_cvg('../data/NA12877.cons_mono.cvg',norm=True) fold_d = parse_rnafold('../data/cons_mono.rnafold.txt') box_d, nb_d= parse_nearest('../data/human_asat.1.25kb.no_ambig.cons_mono.closest_b.bed') names = sorted(cenpa_d.keys()) # names = sorted(fold_d.keys()) cenpa = np.array([cenpa_d[name] for name in names],dtype=float) ssdna = np.array([ssdna_d[name] for name in names],dtype=float) norm = np.array([norm_d[name] for name in names],dtype=float) norm2 = np.array([norm_d2[name] for name in names],dtype=float) fold = np.array([fold_d[name]['ensemble_deltaG'] for name in names],dtype=float) boxdist = np.array([box_d[name]['d'] for name in names],dtype=float) boxscore = np.array([box_d[name]['score'] for name in names],dtype=float) # nb = np.array([nb_d[name] for name in names]) def parse_nearest_filter(fn,names=None,normbed=None): """Parse the bedtools nearest output; limit monomers that are within delta of the ends of the Sanger read""" if names is None: nom = {} else: nom=names norm = {} if normbed is not None: with open(normbed,'r') as f: for line in f: line = line.rstrip().split() if len(line) >= 12: n = line[0]+':'+line[1]+':'+line[2] + ';' + line[10]+':'+line[11]+':'+line[12] norm[n] = float(line[8]) arr = [] with open(fn,'r') as f: for line in f: line = line.rstrip().split() n = line[0]+':'+line[1]+':'+line[2] if len(line)< 12: n2 = ';' d1,d2 = -1,-1 else: n2 = ';'+line[10] + ':' +line[11] + ':' + line[12] d1,d2 = float(line[-3]),int(line[-1]) if (names is not None) and (n+n2 not in nom): continue nom[n+n2] = 1 try: d = np.array([float(line[8]),d1,d2]) if normbed is not None: if n+n2 not in norm: continue if norm[n+n2] == 0: continue d[0] /= norm[n+n2] if d1 != -1: arr.append(d) except: pass return nom,np.array(arr) n,X = parse_nearest_filter('../data/human_cenpa.alphoid.sample.mono.nearest_bbox.txt',names=None) print X.shape bins = np.digitize(X[:,0],np.percentile(X[:,0],q=range(25,99,25))) cscheme = ['#e41a1c','#f18c8d','#f9d1d1','#ffffff'][::-1] # cscheme = ['#e41a1c','#f9d1d1'][::-1] plt.figure(figsize=(1.25,1)) # plt.yscale('log') sns.violinplot(x=bins,y=np.log(X[:,0]+1),fliersize=0,whis=1.5,width=0.7,palette=cscheme,bw=0.25,lw=1) plt.yticks(size=5) plt.tick_params('y',length=4) # plt.ylim(0,200) plt.xticks([0,1,2,3],['Q1','Q2','Q3','Q4'],size=5,y=0.05) plt.ylabel('log occupancy',size=5) plt.xlabel('CENP-B box strength\nquartile',size=5) plt.title('CENP-A',size=6,y=0.9) sns.despine(bottom=True,trim=True) plt.tick_params('x',length=0) # plt.savefig('../figures/cenpa_at_cenpb_quartiles_human.svg') plt.figure(figsize=(1.25,1)) # plt.yscale('log') sns.violinplot(x=bins,y=X[:,1],fliersize=0,whis=1.5,width=0.7,palette=cscheme,bw=0.5,lw=1) plt.yticks(size=5) plt.tick_params('y',length=4) # plt.ylim(0,200) plt.xticks([0,1,2,3],['Q1','Q2','Q3','Q4'],size=5,y=0.05) plt.ylabel('Distance (bp)',size=5) plt.xlabel('CENP-B box strength\nquartile',size=5) plt.title('Distance to CENP-B box',size=6,y=0.9) sns.despine(bottom=True,trim=True) plt.tick_params('x',length=0) plt.savefig('../figures/cenpb_dist_at_cenpb_quartiles_human.svg') plt.figure(figsize=(2,2)) # plt.yscale('log') sns.boxplot(x=bins,y=X[:,1],fliersize=0,whis=1.5,width=0.7,palette=cscheme) plt.yticks(size=12) # plt.ylim(0,200) plt.xticks([0,1,2,3],['Q1','Q2','Q3','Q4'],size=12,y=0.05) plt.ylabel('FIMO score',size=12) plt.xlabel('CENP-A occupancy quartile',size=12) plt.title('CENP-B box strength',size=14) sns.despine(bottom=True,trim=True) plt.tick_params('x',length=0) # plt.savefig('../figures/cenpb_box_strength_human.svg') spearmanr(X[:,0],X[:,1]) n2,Y = parse_nearest_filter('../data/human_ssdna.alphoid.sample.mono.nearest_bbox.txt',names=n) plt.figure(figsize=(2,2)) plt.yscale('log') sns.boxplot(x=bins,y=1000*Y[:,0],fliersize=0,whis=1,width=0.7,palette=cscheme) plt.yticks(size=12) # plt.ylim(10,10000) plt.xticks([0,1,2,3],['Q1','Q2','Q3','Q4'],size=12,y=0.05) plt.ylabel('FIMO score',size=12) plt.xlabel('CENP-A occupancy quartile',size=12) plt.title('CENP-B box strength',size=14) sns.despine(bottom=True,trim=True) plt.tick_params('x',length=0) class Interval(object): """Generic class for holding interval information""" def __init__(self,start,end,dtype=None,chrom=None,data=None,string=None,strand=None): self.chrom=chrom self.start = start self.end = end self.dtype=dtype self.data=data self.string = string self.strand = strand def __len__(self): return self.end-self.start def dist(self,I): x, y = sorted(((self.start,self.end), (I.start,I.end))) dist = min(y)-max(x) if dist > 0: return dist else: return 0 def bed2intervals(bedfn,col=5): bed = {} with open(bedfn,'r') as f: for line in f: line = line.rstrip().split() chrom = line[0] s,e = int(line[1]),int(line[2]) score = float(line[col-1]) strand = line[5] if chrom not in bed: bed[chrom] = [] I = Interval(s,e,chrom=chrom,data=score,strand=strand,string='\t'.join(line)) bed[chrom].append(I) for chrom in bed.iterkeys(): bed[chrom] = sorted(bed[chrom],key=lambda k:k.start) return bed def get_closest(mono_fn,box_fn,outfn,delta=50,orientation='both'): def does_ovl(a1,b1,a2,b2): return max(a1,a2) <= min(b1,b2) def get_best(M,blist): if orientation != 'both': if orientation == 'up': if M.strand == '+': s,e = M.start-delta,M.end else: s,e = M.start,M.end-delta if orientation == 'down': if M.strand == "+": s,e = M.start,M.end+delta else: s,e = M.start-delta,M.end else: s,e = M.start - delta, M.end + delta candidates = [] for b in blist: if does_ovl(s,e,b.start,b.end): candidates.append(b) if len(candidates) == 0: return -1 else: candidate = sorted(candidates,key=lambda k: (k.data,-k.start)) return candidates[-1] monos = bed2intervals(mono_fn,col=9) boxes = bed2intervals(box_fn) out = open(outfn,'w') for chrom in monos.iterkeys(): if chrom not in boxes: continue for m in monos[chrom]: b = get_best(m,boxes[chrom]) if b == -1: dist = "-1" out.write (m.string + "\t" + str(b) +"\t"+dist+"\n") else: dist = str(m.dist(b)) out.write(m.string+"\t"+b.string+"\t"+dist+"\n") out.close() delta = 340 bfn = '../data/human_asat.1.25kb.no_ambig.sample.1k.cenp_b.fimo.bed' mfn = '../data/human_cenpa.alphoid.sample.mono.cvg' get_closest(mfn,bfn,'../data/human_cenpa.alphoid.sample.mono.nearest_bbox.txt',orientation='both',delta=delta) bfn = '../data/human_asat.1.25kb.no_ambig.sample.1k.cenp_b.fimo.bed' mfn = '../data/human_ssdna.alphoid.sample.mono.cvg' get_closest(mfn,bfn,'../data/human_ssdna.alphoid.sample.mono.nearest_bbox.txt',orientation='both',delta=delta) bfn = '../data/human_asat.1.25kb.no_ambig.sample.1k.cenp_b.fimo.bed' mfn = '../data/human_ssdna_sim.alphoid.sample.mono.cvg' # get_closest(mfn,bfn,'../data/human_ssdna_sim.alphoid.sample.mono.nearest_bbox.txt',orientation='both',delta=delta) # bfn = '../data/human_asat.1.25kb.no_ambig.sample.1k.cenp_b.fimo.bed' # mfn = '../data/human_wgs.alphoid.sample.mono.cvg' # get_closest(mfn,bfn,'../data/human_wgs.alphoid.sample.mono.nearest_bbox.txt',orientation='both',delta=delta) bfn = '../data/human_asat.1.25kb.no_ambig.sample.1k.cenp_b.fimo.bed' mfn = '../data/human_input.alphoid.sample.mono.cvg' get_closest(mfn,bfn,'../data/human_input.alphoid.sample.mono.nearest_bbox.txt',orientation='both',delta=delta) ###Output _____no_output_____ ###Markdown Mouse ###Code bfn = '../data/misat_118-122.1kb.cenp_b.fimo.bed' mfn = '../data/mouse_cenpa.misat.mono.cvg' get_closest(mfn,bfn,'../data/mouse_cenpa.misat.mono.nearest_bbox.txt',orientation='both',delta=20) bfn = '../data/misat_118-122.1kb.cenp_b.fimo.bed' mfn = '../data/mouse_input.misat.mono.cvg' get_closest(mfn,bfn,'../data/mouse_input.misat.mono.nearest_bbox.txt',orientation='both',delta=20) bfn = '../data/misat_118-122.1kb.cenp_b.fimo.bed' mfn = '../data/mouse_ssdna_activ.misat.mono.cvg' get_closest(mfn,bfn,'../data/mouse_ssdna_activ.misat.mono.nearest_bbox.txt',orientation='both',delta=20) bfn = '../data/misat_118-122.1kb.cenp_b.fimo.bed' mfn = '../data/mouse_ssdna_rest.misat.mono.cvg' get_closest(mfn,bfn,'../data/mouse_ssdna_rest.misat.mono.nearest_bbox.txt',orientation='both',delta=20) bfn = '../data/misat_118-122.1kb.cenp_b.fimo.bed' mfn = '../data/mouse_wgs.misat.mono.cvg' get_closest(mfn,bfn,'../data/mouse_.mono.nearest_bbox.txt',orientation='both',delta=20) bfn = '../data/misat_118-122.1kb.cenp_b.fimo.bed' mfn = '../data/mouse_ssdna_control.misat.mono.cvg' get_closest(mfn,bfn,'../data/mouse_ssdna_control.misat.mono.nearest_bbox.txt',orientation='both',delta=20) n,X = parse_nearest_filter('../data/mouse_cenpa.misat.mono.nearest_bbox.txt',names=None, normbed='../data/mouse_ssdna_control.misat.mono.nearest_bbox.txt') print X.shape bins = np.digitize(X[:,0],np.percentile(X[:,0],q=range(50,100,50))) cscheme = ['#e41a1c','#ffffff'][::-1] # cscheme = ['#e41a1c','#f9d1d1'][::-1] plt.figure(figsize=(1.25,1)) # plt.yscale('log') sns.boxplot(x=bins,y=X[:,0],fliersize=0,whis=1.5,width=0.7,palette=cscheme) plt.yticks(size=5) plt.tick_params('y',length=4) # plt.ylim(0,1000) plt.xticks([0,1,2,3],['Q1','Q2','Q3','Q4'],size=5,y=0.05) plt.ylabel('log occupancy',size=5) plt.xlabel('CENP-B box strength\nquartile',size=5) plt.title('CENP-A',size=6,y=0.9) sns.despine(bottom=True,trim=True) plt.tick_params('x',length=0) # plt.savefig('../figures/cenpa_at_cenpb_quartiles_human.svg') def per_read_summation(cvgfn,log=False,scale=1): reads = {} with open(cvgfn,'r') as f: for line in f: line = line.strip().split() val = float(line[8]) if val == 0: continue if line[0] not in reads: reads[line[0]] = val else: reads[line[0]] += val for rname in reads.keys(): reads[rname] *= scale if log: reads[rname] = np.log(reads[rname]) return reads def per_read_boxes(bedfn,thresh=1e-3,score=False): reads = {} with open(bedfn,'r') as f: for line in f: line = line.strip().split() pv = float(line[4]) if pv <= thresh: if score: val = float(line[-2]) else: val = 1 if line[0] not in reads: reads[line[0]] = val else: reads[line[0]] += val return reads def get_lens(lenfn): lens = {} with open(lenfn,'r') as f: for line in f: line = line.rstrip().split() lens[line[0]] = int(line[1]) return lens def corr_dicts(r1,r2): data = [] name_order = [] for rname in set(r1.keys()).intersection(set(r2.keys())): data.append([r1[rname],r2[rname]]) name_order.append(rname) return name_order,np.array(data) def corr_files(cvgfn1,cvgfn2,scale1=1,scale2=1): r1 = per_read_summation(cvgfn1,scale=scale1) r2 = per_read_summation(cvgfn2,scale=scale2) return corr_dicts(r1,r2) def norm_file(cvgfn1,cvgfn2,scale1=1,scale2=1,log=True): r1 = per_read_summation(cvgfn1,scale=scale1) r2 = per_read_summation(cvgfn2,scale=scale2) normed = {} for rname in set(r1.keys()).intersection(set(r2.keys())): if r2[rname] == 0: continue if log: normed[rname] = np.log2(r1[rname]+1)-np.log2(r2[rname]+1) else: normed[rname] = (r1[rname]+1)/(r2[rname]+1) return normed # boxes = per_read_boxes('../data/misat_118-122.1kb.cenp_b.fimo.bed',score=False,thresh=1e-7) boxes = per_read_boxes('../data/human_asat.1.25kb.cenp_b.fimo.bed',score=True,thresh=0.95e-7) asats = per_read_boxes('../data/human_asat.1.25kb.no_ambig.sample.alphoid.bed',score=False,thresh=np.inf) lens = get_lens('../data/human_asat.1.25kb.no_ambig.sizes') f1 = '../data/human_cenpa.alphoid.sample.mono.nearest_bbox.txt' n1 = '../data/human_input.alphoid.sample.mono.cvg' f2 = '../data/human_ssdna.alphoid.sample.mono.nearest_bbox.txt' n2 = '../data/human_wgs.alphoid.sample.mono.cvg' # f1_s = 3e8*(18557894+127084)/32167098 f1_s = 3e9/(18557894+127084) n1_s = (63428+12140)/17828342 # n1_s = 3e9/(63428+12140) f2_s = (5748089+4523061)/116355230 # f2_s = 3e9/(5748089+4523061) # SIM # n2_s = 3e8*(42103008+2075713)/54820904 # n2_s = 3e9/(42103008+2075713) # WGS n2_s = (8341837+1108237)/307767790 # n2_s = 3e9/(8341837+1108237) # n1_s = n2_s # d1 = norm_file(f1,n1,f1_s,n1_s,log=False) d1 = per_read_summation(f1,log=False,scale=f1_s) d1n = per_read_summation(n1,log=False,scale=n1_s) # d2 = norm_file(f2,n2,f2_s,n2_s,log=False) d2 = per_read_summation(f2,log=False,scale=f2_s) d2n = per_read_summation(n2,log=False,scale=n2_s) for rname in d1.keys(): # if rname in asats and rname in lens: # d1[rname] *= (asats[rname]/lens[rname]) if rname in d1n and rname in asats: d1[rname] /= (d1n[rname])#*(lens[rname]/asats[rname]) else: del d1[rname] for rname in d2.keys(): # if rname in asats and rname in lens: # d2[rname] *= (asats[rname]/lens[rname]) if rname in d2n and rname in asats: # d2[rname] /= (d2n[rname])#*(lens[rname]/asats[rname]) continue else: del d2[rname] order,X = corr_dicts(d1,d2) print X.shape c = [] for rname in order: if rname in boxes: c.append(boxes[rname]) else: c.append(-1) c = np.array(c) bins = np.percentile(c,q=np.arange(25,76,25)) binned = np.digitize(c,bins) # cdict = {1:cm.Paired(0),2:cm.Paired(1),3:cm.Paired(4),4:cm.Paired(5)} # cdict = {4:'#e41a1c',3:'#f18c8d',2:'#f9d1d1',1:'lightgrey'} cdict = {3:'#e41a1c',2:'#f18c8d',1:'grey'} colors = [cdict[cc] for cc in binned] xmin = np.floor(np.log(np.min(X[:,0]/10000))) xmax = np.ceil(np.log(np.max(X[:,0]/10000))) ymin = np.floor(np.log(np.min(X[:,1]))) ymax = np.ceil(np.log(np.max(X[:,1]))) xbins=np.logspace(xmin,xmax,75) ybins=np.logspace(2,6,30) g = sns.JointGrid(X[:,0]/10000,X[:,1],xlim=[10**0,10**5],ylim=[10**2,10**6],space=0,size=5) # g = sns.JointGrid(X[:,0],X[:,1],space=0,size=2.5) g.ax_marg_x.hist(X[:,0]/10000, color='darkgrey', alpha=1,bins=xbins) g.ax_marg_y.hist(X[:,1], color='darkgrey', alpha=1,bins=ybins,orientation='horizontal') g.plot_joint(plt.scatter, color=colors ,s=20,lw=0,zorder=1,rasterized=True) ax = g.ax_joint ax.set_xscale('log') ax.set_yscale('log') g.ax_marg_x.set_xscale('log') g.ax_marg_y.set_yscale('log') g.ax_marg_y.tick_params(which='both',length=0) g.ax_marg_x.tick_params(which='both',length=0) ax.tick_params(labelsize=16,length=14) ax.tick_params(length=7, which='minor') ax.set_xlabel('CENP-A occupancy',size=22) ax.set_ylabel('Permanganate-seq signal',size=22) plt.savefig('../figures/human_corr_cenp_b_boxes.svg',dpi=300) xmin = np.floor(np.log(np.min(X[:,0]/10000))) xmax = np.ceil(np.log(np.max(X[:,0]/10000))) ymin = np.floor(np.log(np.min(X[:,1]/10000))) ymax = np.ceil(np.log(np.max(X[:,1]/10000))) xbins=np.logspace(xmin,xmax,75) ybins=np.logspace(ymin,ymax,75) g = sns.JointGrid(X[:,0]/10000,X[:,1]/10000,space=0,size=2.5, xlim=[10**0,10**5],ylim=[1e-2,10**2]) g.ax_marg_x.hist(X[:,0]/10000, color='darkgrey', alpha=1,bins=xbins) g.ax_marg_y.hist(X[:,1]/10000, color='darkgrey', alpha=1,bins=ybins,orientation='horizontal') # g.ax_joint.axvspan(np.exp(xmin),np.exp(-1.25),np.exp(ymin),np.exp(ymax),color='grey',zorder=0,alpha=0.1) # g.ax_joint.axhspan(np.exp(ymin),np.exp(-1.2),np.exp(xmin),np.exp(xmax),color='grey',zorder=0,alpha=0.1) # g.ax_joint.axvspan(np.exp(-1.25),np.exp(xmax),np.exp(-0.76),np.exp(ymax),color='red',zorder=0,alpha=0.1) g.plot_joint(plt.scatter, color=colors,s=25,lw=0,zorder=1,rasterized=True) ax = g.ax_joint ax.set_xscale('log') ax.set_yscale('log') g.ax_marg_x.set_xscale('log') g.ax_marg_y.set_yscale('log') g.ax_marg_y.tick_params(which='both',length=0) g.ax_marg_x.tick_params(which='both',length=0) ax.tick_params(labelsize=8) ax.set_xlabel('CENP-A occupancy',size=11) ax.set_ylabel('Permanganate-seq signal',size=11) plt.savefig('../figures/human_corr_cenp_b_boxes.svg',dpi=300) # boxes = per_read_boxes('../data/misat_118-122.1kb.cenp_b.fimo.bed',score=False,thresh=1e-7) boxes = per_read_boxes('../data/misat_118-122.1kb.cenp_b.fimo.bed',score=True,thresh=0.95e-7) asats = per_read_boxes('../data/misat.118-122.1kb.misat.blast.bed',score=False,thresh=np.inf) c = [] for rname in order: if rname in boxes: c.append(boxes[rname]) else: c.append(-1) c = np.array(c) bins = np.percentile(c,q=np.arange(33,67,33)) binned = np.digitize(c,bins) # cdict = {1:cm.Paired(0),2:cm.Paired(1),3:cm.Paired(4),4:cm.Paired(5)} # cdict = {3:'#e41a1c',2:'#f18c8d',1:'#f9d1d1',0:'lightgrey'} cdict = {2:'#e41a1c',1:'#f18c8d',0:'grey'} colors = [cdict[cc] for cc in binned] f1 = '../data/mouse_cenpa.misat.mono.cvg' n1 = '../data/mouse_input.misat.mono.cvg' f2 = '../data/mouse_ssdna_activ.misat.mono.cvg' n2 = '../data/mouse_ssdna_control.misat.mono.cvg' d1 = norm_file(f1,n1,1,1,log=False) # d1 = per_read_summation(f1,log=False,scale=1) # d1n = per_read_summation(n1,log=False,scale=1) d2 = norm_file(f2,n2,1,1,log=False) # d2 = per_read_summation(f2,log=False,scale=1) # d2n = per_read_summation(n2,log=False,scale=1) # for rname in d1.keys(): # if rname in d1n: # d1[rname] /= d1n[rname] # else: # del d1[rname] # for rname in d2.keys(): # if rname in d2n: # d2[rname] /= d2n[rname] # else: # del d2[rname] order,X = corr_dicts(d1,d2) print X.shape xmin = np.floor(np.log(np.min(X[:,0]))) xmax = np.ceil(np.log(np.max(X[:,0]))) ymin = np.floor(np.log(np.min(X[:,1]))) ymax = np.ceil(np.log(np.max(X[:,1]))) xbins=np.logspace(xmin,xmax,75) ybins=np.logspace(ymin,ymax,75) g = sns.JointGrid(X[:,0],X[:,1],xlim=[10**-1.5,10**3.5],ylim=[10**-0.75,10**1],space=0,size=2.5) g.ax_marg_x.hist(X[:,0], color='darkgrey', alpha=1,bins=xbins) g.ax_marg_y.hist(X[:,1], color='darkgrey', alpha=1,bins=ybins,orientation='horizontal') # g.ax_joint.axvspan(np.exp(xmin),np.exp(-1.25),np.exp(ymin),np.exp(ymax),color='grey',zorder=0,alpha=0.1) # g.ax_joint.axhspan(np.exp(ymin),np.exp(-1.2),np.exp(xmin),np.exp(xmax),color='grey',zorder=0,alpha=0.1) # g.ax_joint.axvspan(np.exp(-1.25),np.exp(xmax),np.exp(-0.76),np.exp(ymax),color='red',zorder=0,alpha=0.1) g.plot_joint(plt.scatter, color=colors,s=25,lw=0,zorder=1,rasterized=True) ax = g.ax_joint ax.set_xscale('log') ax.set_yscale('log') g.ax_marg_x.set_xscale('log') g.ax_marg_y.set_yscale('log') g.ax_marg_y.tick_params(which='both',length=0) g.ax_marg_x.tick_params(which='both',length=0) ax.tick_params(labelsize=8) ax.set_xlabel('CENP-A occupancy',size=11) ax.set_ylabel('Permanganate-seq signal',size=11) plt.savefig('../figures/mouse_corr_cenp_b_boxes.svg',dpi=300) ###Output _____no_output_____
final_project/pacilio_final_project.ipynb
###Markdown Costantino Pacilio date: 18 March 2019 Final Project, Numerical Analysis, 2018-2019This is a notebook containing my solution of the assignments.In the course of the notebook, I will justify my design in terms of time optimisation. PreparationsBefore starting with the actual assignments, I prepare myself with some preliminary definitions and rearrangings.For later reference, I will refer to the book "Arnold, A concise introduction to numerical analysis" symply as Arnold.First of all, I load the rquired data from the `mnist.pnz` file, as explained in the original assignment notebook. ###Code %pylab inline img_rows, img_cols = 28, 28 arc = load('mnist.npz') x_train = arc['arr_0'] y_train = arc['arr_1'] x_test = arc['arr_2'] y_test = arc['arr_3'] print(x_train.shape, y_train.shape) print(x_test.shape, y_test.shape) ###Output Populating the interactive namespace from numpy and matplotlib (60000, 28, 28) (60000,) (10000, 28, 28) (10000,) ###Markdown Then, I create a context-manager class Timer(), which I will use to measure times and optimise my strategies. ###Code ## to measure time import time class Timer(): def __enter__(self): self._t0 = time.perf_counter() def __exit__(self,type,value,traceback): self._t1 = time.perf_counter() print("Time spent: [%0.8f] secs" % (self._t1-self._t0)) ###Output _____no_output_____ ###Markdown Here I load various libraries, which are needed in the course of the notebook: to plot results, to print arrays and matrices in a nice way, to integrate, to define a ball tree.Notice that, although I loaded Simpson's quadrature method from `scipy.integrate`, I do not actually use it. Indeed, I will implement my quadrature function, which exploits the properties of the MNIST dataset and runs faster, whithout losing much accuracy. ###Code ## libraries for various tasks import matplotlib.pyplot as plt # for plots from pprint import pprint # to print matrices in nice ways from scipy.integrate import simps as quad ## to integrate (but I will not use it) from sklearn.neighbors import * ## to define a ball tree ###Output _____no_output_____ ###Markdown It is convenient to reshape the images as vectors. This is somewhat optional up to Assignment 7, but it is mandatory for Assignment 8, because the `BallTree` function accepts only vectors. Therefore, I shall implement Assignments 1-7 in such a way that they are already adapted to vectorised form. ###Code ## it is convenient to vectorize the images v_train = [x_train[i].reshape(28*28) for i in range(x_train.shape[0])] v_test = [x_test[i].reshape(28*28) for i in range(x_test.shape[0])] ###Output _____no_output_____ ###Markdown Finally, I define some recurrent variables. ###Code ## recurrent variables S = 1600 L = shape(x_train)[0] ## 64000 T = shape(x_test)[0] ## 10**4 test_range = 1000 ###Output _____no_output_____ ###Markdown Assignment 1I define the three norms, $D\infty$, $D1$ and $D2$.In $D2$ I do not take a `sqrt` of the result, because it is a waste of time and does not affect the final query result.Notice that, as they are written, the distances are well defined for both matricial and vectorial forms of the images. ###Code ## ASSIGNMENT 1 ## define d_infty def _Dinfty(a,b): return abs(a-b).max() ## define d_one def _D1(a,b): return abs(a-b).sum() ## define d_two def _D2(a,b): return square(a-b).sum() ###Output _____no_output_____ ###Markdown In the following, it will be useful to have the distances in a set list, and a dictionary which assign a name string to each dictionary. In the course of the notebook, I will update these objects when new distances are defined. ###Code ## define distances array and names dictionary distances = [_D1,_D2,_Dinfty] names = {_D1:'D1',_D2:'D2',_Dinfty:'D_infty'} ###Output _____no_output_____ ###Markdown Assignment 2I write a function `my_func()` which computes the $(N,N)$ distance matrix between the first $N$ images of the set `x`. ###Code ## ASSIGNMENT 2 ## function returning matrix of distances def my_func(x,N,dist): X=x[:N] ret = zeros((N,N)) for i in range(N): for j in range(i+1,N): ret[i,j] = dist(X[i],X[j]) return ret+ret.T ###Output _____no_output_____ ###Markdown Assignment 3Plot the distance matrix between the first 100 elements of `x_train`, for each of the three distances defined above. I use the vectorised form `v_train`. ###Code ## ASSIGNMENT 3 fig, axs = plt.subplots(1,3,figsize=(10,6)) for ax, distance in zip(axs, distances): ax.imshow(my_func(v_train,100,distance),cmap='gray_r') ax.set_title(names[distance].capitalize()) plt.show() ###Output _____no_output_____ ###Markdown Assignments 4 - 5I implement Assignments 4 and 5 together. They consist in computing the error with the **leave-one-out** strategy, for each distance defined above and for different number $N=[100,200,400,800,1600]$ of training images.The heaviest part of the exercise is the computation of the distance matrices. Therefore I precompute them. I precompute them directly for $N=1600$, and I will slice them appropriately when lower $N$ is needed. (Recall from above that `S=1600`) ###Code ## ASSIGNMENT 4 and 5 ## precompute heavy part of the computation with Timer(): M1 = my_func(v_train,S,_D1) M2 = my_func(v_train,S,_D2) M3 = my_func(v_train,S,_Dinfty) ###Output Time spent: [16.82209515] secs ###Markdown It is convenient to define a list of distance matrices and a list of dimensions $N$. ###Code methods = [M1,M2,M3] dims = [100,200,400,800,1600] ###Output _____no_output_____ ###Markdown I define a function `efficiency()` which implements the leave-one-out strategy and plots the results.The function is flexible, in that it calls elements from the objects defined above: `methods`, `dims`, `distances` and `names`. Therefore we can use it also later, without modifications, by just updating and/or redefining the above objects. ###Code ## set difference dimensions to test efficiency def efficiency(): errors = [] ## computation of the relative errors for num in dims: loc_errors=[] for matrix in methods: error_counter = 0. for i in range(num): M = matrix[i:i+1][0][:num] MM = delete(M,i) arg = argmin(MM) + int(argmin(MM)>=i) digit = y_train[arg] if y_train[i] != digit: error_counter +=1 loc_errors.append(error_counter*100/num) errors.append(loc_errors) for k in range(size(distances)): plt.plot(dims,[errors[i][k] for i in range(size(dims))],'-o',label=names[distances[k]]) plt.legend() plt.xlabel('slice dimesnion') plt.ylabel('percentage error') plt.title('Compare different norms') plt.grid() plt.show() return errors ###Output _____no_output_____ ###Markdown Now we plot the results and print the error matrix, which coincides with the one shown in the original assignments. **Notice that, w.r.t. the original assignments, I prefer to multiply the errors by 100, in such a way to have a percentual error.** ###Code errors = efficiency() pprint(errors) ###Output _____no_output_____ ###Markdown From the plot, we see that the distance $D\infty$ is much less performant. Therefore, we focus in more detail on the difference between $D1$ and $D2$. ###Code ## Focus on the difference between D1 and D2 plt.plot(dims,[errors[i][0] for i in range(size(dims))],'-o',label='D1') plt.plot(dims,[errors[i][1] for i in range(size(dims))],'-o',label='D2') plt.legend() plt.title('Compare D1 and D2') plt.xlabel('slice dimension') plt.ylabel('percentage error') plt.grid() plt.show() ###Output _____no_output_____ ###Markdown Here below, I do some extra work.I define a function `classify()`, which associates a number to any image in a set `z`, by computing its distance `dist` from the members of a training set `X`. ###Code ## define the classify function for later usage def classify(z,dist,X): all_distances = [dist(z,x) for x in X] digit = y_train[argmin(all_distances)] return digit ###Output _____no_output_____ ###Markdown I also define a function `my_test()`, which computes the classification errors of a test set `X`, relative to a distance `dist` and a training set `Z`.Notice that this is the same kind of test that I will have to do in Assignment 8, although with a different algorithm. Therefore, it is useful to do it, in order to define needed objects in advance and anticipate possible problems not related to the details of a ball-tree. ###Code ## test x_test angainst y_test with the distance D2 ## notice that, for consistency, if you test x_train vs y_train ## then you should get 0.000 errors with any norm: try it! ## my_test function def my_test(X,Y,dist,Z): errors = 0. for i in range(test_range): candidate = classify(X[i],dist,Z) if candidate != Y[i]: errors += 1 errors = errors*100/test_range print("percentage error: %0.5f" % errors) ###Output _____no_output_____ ###Markdown The typical test that I perform is on `v_test[:1000]` against `v_train[:1600]`. ###Code with Timer(): my_test(v_test[:test_range],y_test[:test_range],_D2,v_train[:S]) ###Output percentage error: 14.10000 Time spent: [6.43535997] secs ###Markdown Assignment 6In this assignment, we have to implement a new distance based on integrals and gradients.Regarding the integrals, I could do them with the `scypy.integrate` library. However, I implemented my own integration function `my_quad()`, because I recognized the existence of a faster method. This method is not general, but it is specific of the boundary conditions of the images in our sets.Let me explain. Suppose we integrate using a Newton quadrature with trapezoids. Our images are discrete functions $f$, defined on a grid with unit spacing. Therefore the integral reads (restricting for simplicity to one dimension)$$I = \sum_{i=0}^{N-1}\frac{f(i)+f(i+1)}{2}. $$But this can be rewritten as$$I = \left(\sum_{i=0}^N f(i)\right)-\frac{f(0)+f(N)}{2} $$However, given that our images are null at the boundaries, the second term vanishes and the integral eventually reduces to the sum of all the points.This is essentially my quadrature function. It is faster because it uses the built-in `sum` function of numpy arrays. ###Code ## ASSIGNMENT 6 def my_quad(obj): return obj.sum() ###Output _____no_output_____ ###Markdown Before defining the new distance, I precompute some integrals and set up several useful objects:- compute the integrals $$ I[i] = \int_\Omega x[i] $$- compute the densitized images $$ z[i] = \frac{x[i]}{I[i]} $$ and their vectorial forms $$w[i]=z[i].\text{reshape}(28*28)$$- compute the gradients of the $z[i]$'s (notice that you have to use the matricial forms, because the gradients are in 2D)Finally, I construct a family of "super-vectors" `xd[i]` which contain, for each `i`, $$xd[i]=(w[i],\partial_xz[i],\partial_yz[i])$$ ###Code ## compute all the integrals integrals = [ my_quad(x_train[i]) for i in range(L) ] ## compute the new set of train ... z_train = [x_train[i]/integrals[i] for i in range(L)] w_train = [z_train[i].reshape(28*28) for i in range(L)] ## and their 2D gradients ... ## use z_train because it's 2D! gradients = [gradient(z_train[i]) for i in range(L)] ## finally, construct a collection of big images, containing also the components of the gradients xd_train=[append([w_train[i],gradients[i][0].reshape(28*28)],gradients[i][1].reshape(28*28))\ for i in range(L)] ###Output _____no_output_____ ###Markdown I define two new distances. The second one was not mentioned in the original assignments. I implemented it because it is faster and gives better results w.r.t. the first. Moreover, in the second distance you do not compute any gradient, so it is less costing.The first distance is $$DH1(a,b) = \int_\Omega|\nabla(a-b)|^2+(a-b)^2$$I define it without the square root, because it is not needed for our purposes.The second distance is $$\text{my-dist}(a,b)=\int_\Omega|a-b|$$Notice that, since I am identifying the integral with a sum over all points, the two distances are equivalent to:$$ DH1(x[i],x[j]) = D2(xd[i],xd[j])$$and$$ \text{my-dist}(x[i],x[j]) = D1(w[i],w[j]) $$ ###Code ## define new distances ## notice that I do not sqrt in H1 def _Dh1(a,b): return _D2(a,b) ## this is my_distance ## which is just D1, but with z_train instead of x_train ;) def my_dist(a,b): return _D1(a,b) ###Output _____no_output_____ ###Markdown Now I repeat the same analysis of Assignments 4-5: I compute the distance matrices of the two new distances, I update the various object-lists and I plot the efficiency. I compare the two new distances with $D2$, which was the best performant in the previous cases. From the plot, you see that $\text{my-dist}$ performs better than both $D2$ and $DH1$. ###Code with Timer(): M4 = my_func(xd_train[:S],S,_Dh1) with Timer(): M5 = my_func(w_train[:S],S,my_dist) ## update data for efficiency comparison methods = [M2,M4,M5] distances=[_D2,_Dh1,my_dist] names[_Dh1]='H1' names[my_dist]='my_dist' errors3=efficiency() pprint(errors3) ###Output _____no_output_____ ###Markdown Finally, I also run `my-test` for the new distances. In doing so, I create the test objects that will be also needed for Assignment 8. ###Code ## create objects to test new distances integrals = [ my_quad(x_test[i]) for i in range(T) ] ## compute the new set of train ... z_test = [x_test[i]/integrals[i] for i in range(T)] w_test = [z_test[i].reshape(28*28) for i in range(T)] ## and their gradients ... gradients = [gradient(z_test[i]) for i in range(T)] ## finally, construct a collection of big images, containing also the components of the gradients xd_test=[append([w_test[i],gradients[i][0].reshape(28*28)],gradients[i][1].reshape(28*28))\ for i in range(T)] with Timer(): print('with H1: '), my_test(xd_test[:test_range],y_test[:test_range],_Dh1,xd_train[:S]) with Timer(): print('with my_dist: '), my_test(w_test[:test_range],y_test[:test_range],my_dist,w_train[:S]) ###Output with H1: percentage error: 15.10000 Time spent: [10.00143997] secs with my_dist: percentage error: 14.10000 Time spent: [6.64088391] secs ###Markdown Assignment 7In this Assignment I implement the Morge-Ampere distance. In doing so, I need to solve a Laplacian equation of the form $$\Delta \phi = a-b$$where $a,b\in$ `z_train`, and with boundary conditions $\phi|_{\partial\Omega}=0$Notice that the Eq. is linear. Therefore, given that the solution is unique (see Theorem 6.4 in Arnold), one has $\phi = \phi_a-\phi_b$, where $\Delta\phi_a=a$ and $\Delta\phi_b=b$, and with the same vanishing boundary conditions on $\phi_a$ and $\phi_b$. Therefore it will be sufficient to solve the equation for the single images in `z_train`.Let me implement the objects needed to solve the problem. First, I impelement the finite-element approximation of the Laplacian operator. This is not strictly needed, but I will use it to check the goodness of my solutions. ###Code ## ASSIGNMENT 7 def Laplacian(obj): res = zeros((28,28)) for i in range(1,27): for j in range(1,27): res[i][j] = obj[i+1][j]+obj[i-1][j]-4*obj[i][j]+obj[i][j-1]+obj[i][j+1] return res ###Output _____no_output_____ ###Markdown I will solve the Laplacian equation with the finite-element Jacobi method. The details are explained in Arnold, Chapter 6, Section 2.In brief, one reduces the problem to the solution of a linear system $$ \mathbb{J}\cdot\vec{\phi_a} = \vec{a}$$where $\mathbb{J}$ is the Jacobi matrix, while the vector arrows mean that $\phi_a$ and $a$ are interpreted in their vectorised form.Therefore, I just need to implement the Jacobi matrix (see Arnold pag. 155) for the problem at hand, and to invert it.**Notice that the function Lsolve() returns the solution in the matrix form.** ###Code ## Define a function which returns the inverse of the Jacobi matrix def Jmatrix(size1): size2 = size1*size1 ## Define the building blocks a = ones((size1-1,)) b = -4*ones((size1,)) m = (diag(a, -1) + diag(b, 0) + diag(a, +1)) c = zeros((size1,size1)) for i in range(size1): c[i][i]=1 ## Define the main matrix M = np.zeros((size2,size2)) for d in range(size1): M[d*size1:d*size1+size1, d*size1:d*size1+size1] = m for d in range(size1-1): M[d*size1:d*size1+size1, d*size1+size1:d*size1+2*size1] = c for d in range(1,size1): M[d*size1:d*size1+size1, d*size1-size1:d*size1] = c ## reinitialize boundary elements of M for i in range(size1): M[i,:],M[:,i] = 0,0 M[i,i] = 1 M[-1-i,:],M[:,-1-i] = 0,0 M[-1-i,-1-i] = 1 for i in range(1,size1-1): M[i*size1,:], M[:,i*size1] = 0,0 M[i*size1+size1,:], M[i*size1+size1,:] = 0,0 M[i*size1,i*size1] = 1 M[i*size1+size1,i*size1+size1] = 1 return linalg.inv(M) #return M J = Jmatrix(28) ## Laplacian solver def Lsolve(rhs): #return linalg.solve(J,rhs.reshape(size2)).reshape(size1,size1) return dot(J,rhs.reshape(28*28)).reshape(28,28) ###Output _____no_output_____ ###Markdown To give a demonstration, I solve for $\phi_0$ and $\phi_9$, and I show that $\Delta\phi=z[0]+z[9]$. ###Code RHS1 = z_train[0] RHS2 = z_train[9] with Timer(): psi1 = Lsolve(RHS1) psi2 = Lsolve(RHS2) ## plot the solution and ## verify the coincidence between ## the Laplacian of psi and original picture fig, axs = plt.subplots(1,3,figsize=(10,10)) axs[0].imshow(psi1+psi2,cmap='gray_r') axs[1].imshow(RHS1+RHS2,cmap='gray_r') axs[2].imshow(Laplacian(psi1+psi2),cmap='gray_r') axs[0].set_title('psi') axs[1].set_title('Original picture') axs[2].set_title('Laplacian of psi') plt.show() ###Output Time spent: [0.00226040] secs ###Markdown I am now ready to define the new distance. First, I construct all the $\phi$ for each image in `z_train`. ###Code ## initialize the set of solutions of the Laplace equation with Timer(): phi_train = [Lsolve(z_train[i]) for i in range(L)] ###Output Time spent: [1.94676685] secs ###Markdown Then I compute their derivatives, and I construct a new set of "super vectors" as in the previous assignments, defined as$$ \xi[i]=(w[i],\partial_x\phi[i],\partial_y\phi[i]) $$ ###Code ## Compute the derivatives of psi_train grad_phi = [gradient(phi_train[i]) for i in range(L)] ## build a larger vectorized object with the gradients xi_train=[append([w_train[i],grad_phi[i][0].reshape(28*28)],grad_phi[i][1].reshape(28*28))\ for i in range(L)] ###Output _____no_output_____ ###Markdown Now, I am ready to define the distances. I define two new distances. The first is the Morge-Ampere distance$$DMA(a,b) = \int_\Omega(a+b)\cdot|\nabla\phi_{a-b}|^2$$The second distance was not asked in the assignment, but I implemented by my own (and it will turn out to be the best of all the distances):$$DMA2(a,b) = \int_\Omega|a-b|\cdot|\nabla\phi_{a-b}|^2$$Notice that I implemented the new distances in such a way that the two arguments are supervectors of the form $\xi$. This is to uniform the distances definitions, as functions taking only two arguments. ###Code def _Dma(a,b): step = 28*28 p1 = ((a+b)[:step]).reshape(28,28) c = (a - b)[step:3*step] p2 = (square(c[0:step])+square(c[step:2*step])).reshape(28,28) res = matmul(p1,p2) return res.sum() def _Dma2(a,b): step = 28*28 c = (a - b) p1 = abs(c[:step]).reshape(28,28) p2 = (square(c[step:2*step])+square(c[2*step:3*step])).reshape(28,28) res = matmul(p1,p2) return res.sum() ###Output _____no_output_____ ###Markdown I now have all the ingredients to compute the efficiency of the new distances. ###Code ## compute distance matrices with Timer(): M6 = my_func(xi_train[:S],S,_Dma) with Timer(): M7 = my_func(xi_train[:S],S,_Dma2) ## update data for efficiency comparison methods = [M2,M5,M6,M7] distances=[_D2,my_dist,_Dma,_Dma2] names[_Dma]='MA' names[_Dma2]='MA2' errors4=efficiency() pprint(errors4) ###Output _____no_output_____ ###Markdown Finally, I run `my-test` for the new distances. ###Code ## create objects to test new distances phi_test = [Lsolve(z_test[i]) for i in range(T)] ## and their gradients ... grad_phi2 = [gradient(phi_test[i]) for i in range(T)] ## finally, construct a collection of big images, containing also the components of the gradients xi_test=[append([w_test[i],grad_phi2[i][0].reshape(28*28)],grad_phi2[i][1].reshape(28*28))\ for i in range(T)] with Timer(): print('with MA: '), my_test(xi_test[:test_range],y_test[:test_range],_Dma,xi_train[:S]) with Timer(): print('with MA2: '), my_test(xi_test[:test_range],y_test[:test_range],_Dma2,xi_train[:S]) ###Output with MA: percentage error: 11.40000 Time spent: [24.01735575] secs with MA2: percentage error: 11.10000 Time spent: [25.56775737] secs ###Markdown Assignment 8 In this assignment we build a ball tree with the training data, and use it to di queries of the testing data and estimate the errors in the search.**Due to the limitations in my laptop's computational power, I restrict the query to $10^3$ elements of the `x_test` array, out of the original $10^4$ elements.****Moreover, I restrict my benchmark to $N=[800,1600,3200]$ elements in the training set, out of the original $64000$ elements.**From the previous assignments, I already have, for each distance, all the precomputed training sets and test sets. Here below, I just define/update the relevant lists to use in the ball trees construction.I exclude the distance $D\infty$ from my consideration, because I already know it is badly performing.I also exclude $D1$, because I already know that it is similar to $D2$ but a bit worse. ###Code ## Assignment 8 sizes = [800,1600,3200] distances = [_D2,_Dh1,my_dist,_Dma,_Dma2] test = [v_test,xd_test,w_test,xi_test,xi_test] train = [v_train,xd_train,w_train,xi_train,xi_train] tsize = 10**3 ###Output _____no_output_____ ###Markdown I define an error matrix `errors`. The columns will contain the errors relative to a given slice $N$ of the training set. The rows will contain the errors relative to a given distance. ###Code ## reset errors errors = [] ###Output _____no_output_____ ###Markdown I define a function `append()`, which append to `errors` a new row, relative to a new distance. ###Code ## append to errors[] the errors relative to distance d-th distance def append(d, array): loc_errors = [] for N in sizes: count = 0. tree = BallTree( train[d][:N], leaf_size = 400, metric=distances[d] ) dist, ind = tree.query(test[d][:tsize], k=1) for i in range(ind.size): arg=ind[i][0] if y_test[i]!=y_train[arg]: count+=1 loc_errors.append(count*100/tsize) array.append(loc_errors) ###Output _____no_output_____ ###Markdown Now I append the distances ###Code with Timer(): append(0, errors) # append D2 with Timer(): append(1, errors) # append DH1 append(2, errors) # append my_dist with Timer(): append(3, errors) # append MA append(4, errors) # append MA2 ###Output Time spent: [188.66502758] secs ###Markdown Finally, I define a plot function, to plot the distances that are more interested in. ###Code ## plot the errors of the distances in the set D def plot(D): for i in D: plt.plot(sizes, errors[i],'-o',label=names[distances[i]]) plt.legend(loc=1) plt.tight_layout() plt.xlabel('train dimension') plt.ylabel('percentage error') plt.title('Compare different norms (test dimension = 1000)') plt.grid() plt.show() plot(range(5)) ###Output _____no_output_____ ###Markdown Unfinished TasksI did not manage to finish the last part of Assignment 8, in which it was asked to generalize the previous part to multiple neighboroughs query.I wrote the relative functions, which you find here below. But to a first test they were not performing well, actually increasing the inefficiency.Therefore I left this part blank and I just reported the code that I wrote. ###Code ## append to errors2[] the errors relative to distance d-th distance def append2(d): loc_errors = [] for N in sizes: count = 0. tree = BallTree( train[d][:N], leaf_size = 400, metric=distances[d] ) dist, ind = tree.query(test[d][:tsize], k=10) for i in range(shape(ind)[0]): digits = [y_train[arg] for arg in ind[i]] digit = digits[argmax(digits)-1] if y_test[i]!=digit: count+=1 loc_errors.append(count*100/tsize) errors2.append(loc_errors) def plot2(D): for i in D: plt.plot(sizes, errors2[i],'-o',label=names[distances[i]]) plt.legend(loc=1) plt.tight_layout() plt.xlabel('train dimension') plt.ylabel('percentage error') plt.title('Compare different norms (test dimension = 1000)') plt.grid() plt.show() errors2=[] ###Output _____no_output_____
optim/WGANs-toy.ipynb
###Markdown https://github.com/bruno-31/diff-game/blob/master/WGANs-toy.ipynb ###Code % pylab inline import os os.environ["CUDA_VISIBLE_DEVICES"]="5" import tensorflow as tf import numpy as np import matplotlib.pyplot as plt from tqdm import tqdm # Tqdm 是 Python 进度条库,可以在 Python 长循环中添加一个进度提示信息 from utils import get_getter from tensorflow.contrib.kfac.python.ops.utils import fwd_gradients import seaborn as sns # MoviePy是一个用于视频编辑的python模块 try: from moviepy.video.io.bindings import mplfig_to_npimage import moviepy.editor as mpy except: print("Warning: moviepy not found.") # slim是一个使构建,训练,评估神经网络变得简单的库。它可以消除原生tensorflow里面很多重复的模板性的代码, # 让代码更紧凑,更具备可读性。另外slim提供了很多计算机视觉方面的著名模型(VGG, AlexNet等), # 我们不仅可以直接使用,甚至能以各种方式进行扩展。 slim = tf.contrib.slim ds = tf.contrib.distributions # universal-divergence is a Python module for estimating divergence of two sets of # samples generated from the two underlying distributions. # https://pypi.org/project/universal-divergence/ from universal_divergence import estimate from utils import nn_l2_mean from functools import reduce from operator import mul from optimizers import OptimisticAdamOptimizer, OptimisticMirrorDescentOptimizer ###Output _____no_output_____ ###Markdown Generator and discriminator architectures(same architecture as proposed in google brain paper) ###Code def generator(z, output_dim=2, n_hidden=512, n_layer=4, getter=None, reuse=False): with tf.variable_scope("generator", custom_getter=getter, reuse=reuse): h = slim.stack(z, slim.fully_connected, [n_hidden] * n_layer, activation_fn=tf.nn.relu) x = slim.fully_connected(h, output_dim, activation_fn=None) return x def discriminator(x, n_hidden=512, n_layer=4, getter=None, reuse=False): with tf.variable_scope("discriminator", custom_getter=getter, reuse=reuse): h = slim.stack(x, slim.fully_connected, [n_hidden] * n_layer, activation_fn=tf.nn.relu) log_d = slim.fully_connected(h, 1, activation_fn=None) return log_d ###Output _____no_output_____ ###Markdown Data creation ###Code def sample_mog(batch_size, n_mixture=16, std=0.2): x = np.linspace(-4.5,4.5,4) xs, ys = np.meshgrid(x, x) xs, ys = xs.flatten(), ys.flatten() cat = ds.Categorical(tf.zeros(n_mixture)) comps = [ds.MultivariateNormalDiag([xi, yi], [std, std]) for xi, yi in zip(xs.ravel(), ys.ravel())] data = ds.Mixture(cat, comps) return data.sample(batch_size) def load_mnist_and_sample(batch_size): from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) from sampler import sampler im=mnist.train.next_batch(1)[0] im=im.reshape([28,28]) x = np.linspace(0, 1, 28) y = np.linspace(0, 1,28) xv, yv = np.meshgrid(x, y) z=im s=sampler(x,y,z) vals = s.sample(batch_size) return vals,im def plot_vals_im(vals,im): xVals = []; yVals = [] fig, ax = plt.subplots(nrows=1, ncols=2) for item in vals: # plot point by point xVals.append(item[0]) yVals.append(item[1]) ax[0].plot(item[0], 1-item[1], marker="x", c="red") ax[0].set_title('Complex distribution') ax[1].imshow(im,cmap='gray') ax[1].set_title('Original Image') plt.show() def sample_complex(batch_size): vals, im = load_mnist_and_sample(batch_size) plot_vals_im(vals,im) return tf.stack(vals) ###Output _____no_output_____ ###Markdown Hyperparam ###Code params = dict( batch_size=512, disc_learning_rate=5e-5, gen_learning_rate=5e-5, beta1=0.5, epsilon=1e-8, max_iter=20000, frame_every=2000, viz_every=2000, z_dim=2, x_dim=2, optimizer='optimadam', # prop sgd sga ema = False, align = True, data = 'mog', LAMBDA = .1, mode = 'wgan-gp', generate_movie = False, reg_w = 10, CRITIC_ITERS = 5 # How many critic iterations per generator iteration ) ###Output _____no_output_____ ###Markdown Function for Symplectic gradient adjustmenthttps://github.com/deepmind/symplectic-gradient-adjustment ??? ###Code def jac_vec(ys,xs,vs): return fwd_gradients(ys,xs,grad_xs=vs, stop_gradients=xs) def jac_tran_vec(ys,xs,vs): dydxs = tf.gradients(ys,xs,grad_ys=vs, stop_gradients=xs) return [tf.zeros_like(x) if dydx is None else dydx for (x,dydx) in zip(xs,dydxs)] def get_sym_adj(Ls,xs): xi= [tf.gradients(l,x)[0]for(l,x)in zip(Ls,xs)] H_xi = jac_vec(xi,xs,xi) Ht_xi = jac_tran_vec(xi,xs,xi) At_xi =[(ht-h)/2 for (h,ht) in zip(H_xi,Ht_xi)] return At_xi ###Output _____no_output_____ ###Markdown Construct model and training ops ###Code tf.reset_default_graph() data = sample_complex(params['batch_size']) if params['data']=='complex' else sample_mog(params['batch_size']) noise = ds.Normal(tf.zeros(params['z_dim']), tf.ones(params['z_dim'])).sample(params['batch_size']) # Construct generator and discriminator nets with slim.arg_scope([slim.fully_connected], weights_initializer=tf.orthogonal_initializer(gain=1.4)): samples = generator(noise, output_dim=params['x_dim']) real_score = discriminator(data) fake_score = discriminator(samples, reuse=True) # Saddle objective loss = tf.reduce_mean( # tf.reduce_mean 函数用于计算张量 tensor 沿着指定的轴(tensor的某一维度)上的的平均值 tf.nn.sigmoid_cross_entropy_with_logits(logits=real_score, labels=tf.ones_like(real_score)) + tf.nn.sigmoid_cross_entropy_with_logits(logits=fake_score, labels=tf.zeros_like(fake_score))) # https://zhuanlan.zhihu.com/p/33560183 # https://blog.csdn.net/m0_37393514/article/details/81393819 loss_gen = -tf.reduce_mean(fake_score) loss_dis = tf.reduce_mean(fake_score) - tf.reduce_mean(real_score) gen_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, "generator") disc_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, "discriminator") ###Output _____no_output_____ ###Markdown WGAN or WGAN-GP ###Code if params['mode'] == 'wgan': clip_ops = [] for var in disc_vars: clip_bounds = [-.01, .01] clip_ops.append( tf.assign(var, tf.clip_by_value(var, clip_bounds[0], clip_bounds[1])) ) clip_disc_weights = tf.group(*clip_ops) elif params['mode'] == 'wgan-gp': fake_data = samples real_data = data # Gradient penalty alpha = tf.random_uniform(shape=[params['batch_size'],1], minval=0., maxval=1.) differences = fake_data - real_data interpolates = real_data + (alpha*differences) gradients = tf.gradients(discriminator(interpolates,reuse=True), [interpolates])[0] slopes = tf.sqrt(tf.reduce_sum(tf.square(gradients), reduction_indices=[1])) gradient_penalty = tf.reduce_mean((slopes-1.)**2) loss_dis += params['LAMBDA']*gradient_penalty ###Output _____no_output_____ ###Markdown Optimizers ###Code if params['optimizer'] == 'default': if params['mode']=='wgan': d_train_opt = tf.train.RMSPropOptimizer(learning_rate=5e-5) g_train_opt = tf.train.RMSPropOptimizer(learning_rate=5e-5) elif params['mode']=='wgan-gp': d_train_opt = tf.train.AdamOptimizer(learning_rate=1e-4, beta1=0.5, beta2=0.9) g_train_opt = tf.train.AdamOptimizer(learning_rate=1e-4, beta1=0.5, beta2=0.9) d_train_op = d_train_opt.minimize(loss_dis, var_list=disc_vars) g_train_op = g_train_opt.minimize(loss_gen, var_list=gen_vars) elif params['optimizer'] == 'default_ema': if params['mode']=='wgan': d_train_opt = tf.train.RMSPropOptimizer(learning_rate=5e-5) g_train_opt = tf.train.RMSPropOptimizer(learning_rate=5e-5) elif params['mode']=='wgan-gp': d_train_opt = tf.train.AdamOptimizer(learning_rate=1e-4, beta1=0.5, beta2=0.9) g_train_opt = tf.train.AdamOptimizer(learning_rate=1e-4, beta1=0.5, beta2=0.9) d_train_op = d_train_opt.minimize(loss_dis, var_list=disc_vars) g_train_op = g_train_opt.minimize(loss_gen, var_list=gen_vars) ema = tf.train.ExponentialMovingAverage(decay=0.999) maintain_averages_op = ema.apply(gen_vars) with tf.control_dependencies([g_train_op]): g_train_op = tf.group(maintain_averages_op) samples_ema = generator(noise, output_dim=params['x_dim'], getter=get_getter(ema),reuse=True) elif params['optimizer'] == 'omd': d_train_opt = OptimisticMirrorDescentOptimizer(learning_rate=5e-5) g_train_opt = OptimisticMirrorDescentOptimizer(learning_rate=5e-5) d_train_op = d_train_opt.minimize(loss_dis, var_list=disc_vars) g_train_op = g_train_opt.minimize(loss_gen, var_list=gen_vars) elif params['optimizer'] == 'optimadam': d_train_opt = OptimisticAdamOptimizer(learning_rate=1e-4, beta1=0.5, beta2=0.9) g_train_opt = OptimisticAdamOptimizer(learning_rate=1e-4, beta1=0.5, beta2=0.9) d_train_op = d_train_opt.minimize(loss_dis, var_list=disc_vars) g_train_op = g_train_opt.minimize(loss_gen, var_list=gen_vars) elif params['optimizer'] == 'sga': d_opt = tf.train.RMSPropOptimizer(learning_rate=5e-5) g_opt = tf.train.RMSPropOptimizer(learning_rate=5e-5) dvs = d_opt.compute_gradients(loss_dis, var_list=disc_vars) gvs = g_opt.compute_gradients(loss_gen, var_list=gen_vars) adj = get_sym_adj([loss_dis]*len(disc_vars) + [loss_gen]*len(gen_vars),disc_vars+gen_vars) d_adj= adj[:len(disc_vars)] g_adj = adj[-len(gen_vars)::] dvs_sga = [(grad + adj , var) for (grad,var),adj in zip(dvs,d_adj)] gvs_sga = [(grad + adj , var) for (grad,var),adj in zip(gvs,g_adj)] d_train_op = d_opt.apply_gradients(dvs_sga) g_train_op = g_opt.apply_gradients(gvs_sga) elif params['optimizer'] == 'consensus': d_opt = tf.train.RMSPropOptimizer(learning_rate=5e-5, use_locking=True) g_opt = tf.train.RMSPropOptimizer(learning_rate=5e-5, use_locking=True) dvs = d_opt.compute_gradients(loss, var_list=disc_vars) gvs = g_opt.compute_gradients(-loss, var_list=gen_vars) grads_d = [grad for (grad,var) in dvs] grads_g = [grad for (grad,var) in gvs] grads = grads_d + grads_g # Regularizer reg = 0.5 * sum(tf.reduce_sum(tf.square(g)) for g in grads) # Jacobian times gradiant variables = disc_vars + gen_vars Jgrads = tf.gradients(reg, variables) d_adj = Jgrads[:len(disc_vars)] g_adj = Jgrads[-len(gen_vars)::] dvs_sga = [(grad + params['reg_w'] * adj , var) for (grad,var),adj in zip(dvs,d_adj)] gvs_sga = [(grad + params['reg_w'] * adj , var) for (grad,var),adj in zip(gvs,g_adj)] with tf.control_dependencies([g for (g, v) in dvs_sga]): d_train_op = d_opt.apply_gradients(dvs_sga) with tf.control_dependencies([g for (g, v) in dvs_sga]): g_train_op = g_opt.apply_gradients(gvs_sga) ###Output _____no_output_____ ###Markdown Train ###Code sess = tf.InteractiveSession() sess.run(tf.global_variables_initializer()) xmax = 3 fs = [] raw_frames = [] np_samples = [] n_batches_viz = 10 viz_every = params['viz_every'] frame_every = params['frame_every'] nn_every = 200 y_ref = sess.run(data) nn_dist = [] nn_kl =[] for i in tqdm(range(params['max_iter']+1)): f, _ = sess.run([[loss], g_train_op]) # g_train_op for j in range(params['CRITIC_ITERS']): _ = sess.run(d_train_op) # d_train_op if params['mode'] == 'wgan': _ = sess.run(clip_disc_weights) fs.append(f) if (i) % frame_every == 0: if params['optimizer'] == 'default_ema': np_samples.append(np.vstack([sess.run(samples_ema) for _ in range(n_batches_viz)])) xx, yy = sess.run([samples_ema, data]) else: np_samples.append(np.vstack([sess.run(samples) for _ in range(n_batches_viz)])) xx, yy = sess.run([samples, data]) fig = figure(figsize=(5,5)) scatter(xx[:, 0], xx[:, 1], edgecolor='none',s=10) scatter(yy[:, 0], yy[:, 1], c='g', edgecolor='none',s=10) if params["data"]=="complex": plt.xlim([-0.2, 1.2]) plt.ylim([-0.2, 1.2]) else: plt.xlim([-5.5, 5.5]) plt.ylim([-5.5, 5.5]) axis('off') if params['generate_movie']: raw_frames.append(mplfig_to_npimage(fig)) if (i) % viz_every == 0: show() if (i) % nn_every == 0: if params['optimizer'] == 'default_ema': x = np.vstack([sess.run(samples_ema) for _ in range(n_batches_viz)]) else: x = np.vstack([sess.run(samples) for _ in range(n_batches_viz)]) l2nn = nn_l2_mean(x,y_ref) kl =estimate(x, y_ref,k=1) nn_dist.append(l2nn) nn_kl.append(kl) np_samples_ = np_samples[::1] vizu_frames = [] cols = len(np_samples_) figure(figsize=(2*cols, 2)) for i, samps in enumerate(np_samples_): if i == 0: ax = subplot(1,cols,1) else: subplot(1,cols,i+1, sharex=ax, sharey=ax) ax2 = sns.kdeplot(samps[:, 0], samps[:, 1], shade=True, cmap='coolwarm', bw=.40, n_levels=20, clip=[[-6,6]]*2) xticks([]); yticks([]) title('step %d'%(i*viz_every)) gcf().tight_layout() plt.semilogy(nn_dist) plt.semilogy(nn_kl) plt.legend(['kl','l2 nearest neigbhors']) xlabel('iterations') plt.show() np.save('plot_{}_{}_kl'.format(params['mode'],params['optimizer']),nn_kl) np.save('plot_{}_{}_nn'.format(params['mode'],params['optimizer']),nn_dist) ###Output _____no_output_____ ###Markdown Video maker ###Code if params['generate_movie']: np_samples_ = np_samples[::1] vizu_frames = [] cols = len(np_samples_) bg_color = sns.color_palette('Greens', n_colors=256)[0] fig, ax = plt.subplots() for i, samps in enumerate(np_samples_): ax.clear() ax2 = sns.kdeplot(samps[:, 0], samps[:, 1], shade=True, cmap='coolwarm', bw=.40, n_levels=20, clip=[[-6,6]]*2) xticks([]); yticks([]) title('step %d'%(i*frame_every)) if generate_movie: vizu_frames.append(mplfig_to_npimage(fig)) # Generate movie raw_clip = mpy.ImageSequenceClip(raw_frames[::], fps=10) raw_clip.write_videofile("raw_optimizer_{}_{}_{}.webm".format(params['optimizer'], params['mode'], params['data']), audio=False) vizu_clip = mpy.ImageSequenceClip(vizu_frames[::], fps=10) vizu_clip.write_videofile("vizu_optimizer_{}_{}_{}.webm".format(params['optimizer'], params['mode'], params['data']), audio=False) ###Output _____no_output_____
data-augmentation/Data augmentation.ipynb
###Markdown Data Augmentationwe're going to experiment with augmenting the data. We'll do this by adding noise to the embedding vectors as they go into the model. ###Code import os import time import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) from tqdm import tqdm import math from sklearn.model_selection import train_test_split from sklearn import metrics from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.layers import Dense, Input, CuDNNLSTM, Embedding, Dropout, Activation, CuDNNGRU, Conv1D, Concatenate, Flatten from keras.layers import Bidirectional, GlobalMaxPool1D from keras.optimizers import Adam, RMSprop from keras.models import Model from keras import backend as K from keras.engine.topology import Layer from keras import initializers, regularizers, constraints, optimizers, layers train_df = pd.read_csv("../input/train.csv") test_df = pd.read_csv("../input/test.csv") print("Train shape : ",train_df.shape) print("Test shape : ",test_df.shape) ## split to train and val train_df, val_df = train_test_split(train_df, test_size=0.08, random_state=2018) ## some config values embed_size = 300 # how big is each word vector max_features = 95000 # 95000 # how many unique words to use (i.e num rows in embedding vector) maxlen = 70 # max number of words in a question to use ## fill up the missing values train_X = train_df["question_text"].fillna("_##_").values val_X = val_df["question_text"].fillna("_##_").values test_X = test_df["question_text"].fillna("_##_").values ## Tokenize the sentences tokenizer = Tokenizer(num_words=max_features) tokenizer.fit_on_texts(list(train_X)) train_X = tokenizer.texts_to_sequences(train_X) val_X = tokenizer.texts_to_sequences(val_X) test_X = tokenizer.texts_to_sequences(test_X) ## Pad the sentences train_X = pad_sequences(train_X, maxlen=maxlen) val_X = pad_sequences(val_X, maxlen=maxlen) test_X = pad_sequences(test_X, maxlen=maxlen) ## Get the target values train_y = train_df['target'].values val_y = val_df['target'].values ###Output _____no_output_____ ###Markdown **Attention Layer:** https://www.kaggle.com/suicaokhoailang/lstm-attention-baseline-0-652-lb ###Code class Attention(Layer): def __init__(self, step_dim, W_regularizer=None, b_regularizer=None, W_constraint=None, b_constraint=None, bias=True, **kwargs): self.supports_masking = True self.init = initializers.get('glorot_uniform') self.W_regularizer = regularizers.get(W_regularizer) self.b_regularizer = regularizers.get(b_regularizer) self.W_constraint = constraints.get(W_constraint) self.b_constraint = constraints.get(b_constraint) self.bias = bias self.step_dim = step_dim self.features_dim = 0 super(Attention, self).__init__(**kwargs) def build(self, input_shape): assert len(input_shape) == 3 self.W = self.add_weight((input_shape[-1],), initializer=self.init, name='{}_W'.format(self.name), regularizer=self.W_regularizer, constraint=self.W_constraint) self.features_dim = input_shape[-1] if self.bias: self.b = self.add_weight((input_shape[1],), initializer='zero', name='{}_b'.format(self.name), regularizer=self.b_regularizer, constraint=self.b_constraint) else: self.b = None self.built = True def compute_mask(self, input, input_mask=None): return None def call(self, x, mask=None): features_dim = self.features_dim step_dim = self.step_dim eij = K.reshape(K.dot(K.reshape(x, (-1, features_dim)), K.reshape(self.W, (features_dim, 1))), (-1, step_dim)) if self.bias: eij += self.b eij = K.tanh(eij) a = K.exp(eij) if mask is not None: a *= K.cast(mask, K.floatx()) a /= K.cast(K.sum(a, axis=1, keepdims=True) + K.epsilon(), K.floatx()) a = K.expand_dims(a) weighted_input = x * a return K.sum(weighted_input, axis=1) def compute_output_shape(self, input_shape): return input_shape[0], self.features_dim !ls ../input/embeddings/ ###Output glove.840B.300d paragram_300_sl999 GoogleNews-vectors-negative300 wiki-news-300d-1M ###Markdown Load Some Embeddings We have four different types of embeddings. * GoogleNews-vectors-negative300 - https://code.google.com/archive/p/word2vec/ * glove.840B.300d - https://nlp.stanford.edu/projects/glove/ * paragram_300_sl999 - https://cogcomp.org/page/resource_view/106 * wiki-news-300d-1M - https://fasttext.cc/docs/en/english-vectors.html A very good explanation for different types of embeddings are given in this [kernel](https://www.kaggle.com/sbongo/do-pretrained-embeddings-give-you-the-extra-edge). Please refer the same for more details..**Glove Embeddings:**In this section, let us use the Glove embeddings with LSTM model. ###Code EMBEDDING_FILE = '../input/embeddings/glove.840B.300d/glove.840B.300d.txt' def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32') embeddings_index = dict(get_coefs(*o.split(" ")) for o in open(EMBEDDING_FILE)) all_embs = np.stack(embeddings_index.values()) emb_mean,emb_std = all_embs.mean(), all_embs.std() embed_size = all_embs.shape[1] word_index = tokenizer.word_index nb_words = min(max_features, len(word_index)) embedding_matrix = np.random.normal(emb_mean, emb_std, (nb_words, embed_size)) for word, i in word_index.items(): if i >= max_features: continue embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[i] = embedding_vector train_X[0] embedding_matrix[train_X[0:10]].shape ###Output _____no_output_____ ###Markdown Data Augmentation Data augmentation strategy is adding an additional multiplier p training examples (ie. total training set is p\*m examples) where additional examples are obtained by adding noise to the embedding vector. We could additionally try translations on all the embedding vectors (based on word analogy rationale).First, let's get a matrix of training examples. ###Code train_X.shape # Now let's write a generator function that manually converts train data to embedding matrix def x_generator(x_data, y_data, embedding_matrix, max_features, batch_size = 512): n_batches = int(x_data.shape[0] / batch_size) # set lower index for this batch batch_lower = 0 while True: batch_upper = batch_lower + batch_size #handle the final batch if batch_upper > x_data.shape[0]: batch_upper = x_data.shape[0] x_batch = x_data[batch_lower:batch_upper,:] y_batch = y_data[batch_lower:batch_upper] x_batch_embeddings = embedding_matrix[x_batch] batch_lower += batch_size #handle the final batch if batch_lower > x_data.shape[0]: batch_lower = 0 yield x_batch_embeddings, y_batch #modifying the generator to augment the data by duplicating the batch and adding noise def x_generator_augment(x_data, y_data, embedding_matrix, emb_std, max_features, batch_size=512, # augment_factor=4, noise_scale=0.1): """ emb_std is the standard deviation of the embedding matrix max_features is the number of tokenized words batch_size is the size of the training batch to augment augment_factor is the multiplier for the size of the augmented batch noise_scale is how many standard deviations to scale the noise by """ n_batches = int(x_data.shape[0] / batch_size) # set lower index for this batch batch_lower = 0 # every time we loop round, shuffle the training set np.random.seed(batch_lower) # not using shuffled for now rnd_idx = np.random.permutation(len(x_data)) x_shuffled = x_data[rnd_idx] y_shuffled = y_data[rnd_idx] while True: batch_upper = batch_lower + batch_size #handle the final batch if batch_upper > x_data.shape[0]: batch_upper = x_data.shape[0] x_batch = x_data[batch_lower:batch_upper,:] y_batch = y_data[batch_lower:batch_upper] batch_embeddings = embedding_matrix[x_batch] # create an empty list for the augmented batches augmented_batches = [batch_embeddings] y_batches = [y_batch] for p in range (augment_factor): noise = np.random.normal(0, emb_std * noise_scale, (batch_embeddings.shape)) aug = np.add (noise, batch_embeddings) augmented_batches.append(aug) y_batches.append(y_batch) x_augmented = np.vstack((augmented_batches)) y_augmented = np.hstack((y_batches)) # now reset the counters for the next iteration batch_lower += batch_size #reset the generator and reshuffle the training set if batch_lower > x_data.shape[0]: batch_lower = 0 rnd_idx = np.random.permutation(len(x_data)) x_shuffled = x_data[rnd_idx] y_shuffled = y_data[rnd_idx] yield x_augmented, y_augmented #let's test out the generator by looking at the shapes of the data it outputs x, y = train_generator.__next__() print (x.shape, y.shape) # ORIGINAL MODEL CODE #inp = Input(shape=(maxlen,)) #x = Embedding(max_features, embed_size, weights=[embedding_matrix], trainable=False)(inp) #x = Bidirectional(CuDNNLSTM(128, return_sequences=True))(x) #x = Bidirectional(CuDNNLSTM(64, return_sequences=True))(x) #x = Attention(maxlen)(x) #x = Dense(64, activation="relu")(x) #x = Dense(1, activation="sigmoid")(x) #model = Model(inputs=inp, outputs=x) #model.compile(loss='binary_crossentropy', optimizer=Adam(lr=1e-3), metrics=['accuracy']) ###Output _____no_output_____ ###Markdown Let's try a modification of the LSTM attention model, where we also feed in the internal states of the LSTMs into the fully connected layers. Note that each LSTM has two internal states (c and s) for each of the forward and backward directions. This ends up with quite a lot of units in the Concatenate layer so there's another fully connected layer to reduce the number of units toward the softmax classifier more gradually. ###Code def build_attention_model(embed_matrix): inp = Input(shape=(maxlen,embed_size)) # x = Embedding(max_features, embed_size, weights=[embed_matrix], trainable=False)(inp) # get internal states of LSTM, both forward and back [x, s_1f, s_1b, c_1f, c_1b] = Bidirectional(CuDNNLSTM(128, return_sequences=True, return_state=True))(inp) [x, s_2f, s_2b, c_2f, c_2b] = Bidirectional(CuDNNLSTM(64, return_sequences=True, return_state=True))(x) x = Attention(maxlen)(x) # fully connected part of model, takes internal states of both LSTMs as well as the output of LSTM2 x = Concatenate()([x, s_1f, s_1b, c_1f, c_1b, s_2f, s_2b, c_2f, c_2b]) x = Dense(256, activation="relu")(x) x = Dense(64, activation="relu")(x) x = Dense(1, activation="sigmoid")(x) model = Model(inputs=inp, outputs=x) model.compile(loss='binary_crossentropy', optimizer=RMSprop(lr=1e-3), metrics=['accuracy']) model.summary() return model ###Output _____no_output_____ ###Markdown And code to evaluate the model (F1 scores at various thresholds) on the validation set ###Code from sklearn import metrics def calc_f1_scores(model, dev_x, dev_y): dev_x_embeddings = embedding_matrix[dev_x] pred_glove_dev_Y = model.predict([dev_x_embeddings], batch_size=1024, verbose=1) best_thresh = -1 # init value best_f1 = 0 for thresh in np.arange(0.1, 0.501, 0.01): thresh = np.round(thresh, 2) f1 = metrics.f1_score(dev_y, (pred_glove_dev_Y>thresh).astype(int)) print("F1 score at threshold {0} is {1}".format(thresh, f1)) if f1 > best_f1: best_f1 = f1 best_thresh = thresh print("Best F1 score was at threshold {0}, {1}".format(best_thresh, best_f1)) return (best_thresh, best_f1, pred_glove_dev_Y) ###Output _____no_output_____ ###Markdown Compare the models. First, the untuned model ###Code model = build_attention_model(embedding_matrix) # Configure the generator batch_size=1024 num_train_batches = math.ceil(train_X.shape[0] / batch_size) num_val_batches = math.ceil(val_X.shape[0] / batch_size) print ("num train batches:", num_train_batches) print ("num val batches:", num_val_batches) train_generator = x_generator_augment(train_X, train_y, embedding_matrix, emb_std, max_features, batch_size=batch_size, augment_factor=0, noise_scale=0.05) val_generator = x_generator(val_X, val_y, embedding_matrix, max_features, batch_size = batch_size) ###Output num train batches: 1080 num val batches: 94 ###Markdown Testing the data augmentationModel built, data augmentation algorithm built into the generator, let's test out whether we can get an improvement in prediction accuracy/F1 score by comparing the model trained on the original dataset (trained until it starts to overfit) with the same model trained on the augmented data. ###Code model.fit_generator(train_generator, steps_per_epoch=num_train_batches, epochs=3, validation_data=val_generator, validation_steps=num_val_batches) print ("Original model") (best_thresh, best_f1, pred_glove_val_y) = calc_f1_scores (model, val_X, val_y) pred_glove_test_y = model.predict([embedding_matrix[test_X]], batch_size=1024, verbose=1) ###Output Original model 96131/96131 [==============================] - 9s 96us/step F1 score at threshold 0.1 is 0.5705485635388455 F1 score at threshold 0.11 is 0.5796503420566836 F1 score at threshold 0.12 is 0.5882287679591724 F1 score at threshold 0.13 is 0.5963323522753 F1 score at threshold 0.14 is 0.6032881453706375 F1 score at threshold 0.15 is 0.6103468547912992 F1 score at threshold 0.16 is 0.6155685758699032 F1 score at threshold 0.17 is 0.6214654910307085 F1 score at threshold 0.18 is 0.6262526289743907 F1 score at threshold 0.19 is 0.6311094358587762 F1 score at threshold 0.2 is 0.6364448984803984 F1 score at threshold 0.21 is 0.6400465959099145 F1 score at threshold 0.22 is 0.6439697666776207 F1 score at threshold 0.23 is 0.6474034620505993 F1 score at threshold 0.24 is 0.6503812672919901 F1 score at threshold 0.25 is 0.6523135807531953 F1 score at threshold 0.26 is 0.6541176470588235 F1 score at threshold 0.27 is 0.6565847511027095 F1 score at threshold 0.28 is 0.6584951112370696 F1 score at threshold 0.29 is 0.6604017216642755 F1 score at threshold 0.3 is 0.6614413237535379 F1 score at threshold 0.31 is 0.6630906018076274 F1 score at threshold 0.32 is 0.665377751338489 F1 score at threshold 0.33 is 0.6662657847263981 F1 score at threshold 0.34 is 0.6661596958174905 F1 score at threshold 0.35 is 0.6671787387664183 F1 score at threshold 0.36 is 0.6675984160260889 F1 score at threshold 0.37 is 0.6672419203012236 F1 score at threshold 0.38 is 0.6680932001902045 F1 score at threshold 0.39 is 0.6667199872030712 F1 score at threshold 0.4 is 0.6661291622994437 F1 score at threshold 0.41 is 0.6652552723719567 F1 score at threshold 0.42 is 0.6655149720302731 F1 score at threshold 0.43 is 0.6655049373495975 F1 score at threshold 0.44 is 0.6636531056420559 F1 score at threshold 0.45 is 0.6616020933569681 F1 score at threshold 0.46 is 0.6600255427841636 F1 score at threshold 0.47 is 0.6584800343495062 F1 score at threshold 0.48 is 0.6566155445801923 F1 score at threshold 0.49 is 0.6557032890132961 F1 score at threshold 0.5 is 0.6513437057991514 Best F1 score was at threshold 0.38, 0.6680932001902045 56370/56370 [==============================] - 5s 93us/step ###Markdown Augmented model ###Code # rebuild the model model = build_attention_model(embedding_matrix) batch_size=128 num_train_batches = math.ceil(train_X.shape[0] / batch_size) num_val_batches = math.ceil(val_X.shape[0] / batch_size) print ("num train batches:", num_train_batches) print ("num val batches:", num_val_batches) train_generator = x_generator_augment(train_X, train_y, embedding_matrix, emb_std, max_features, batch_size=batch_size, augment_factor=1, noise_scale=0.15) val_generator = x_generator(val_X, val_y, embedding_matrix, max_features, batch_size = batch_size) model.fit_generator(train_generator, steps_per_epoch=num_train_batches, epochs=3, validation_data=val_generator, validation_steps=num_val_batches) print ("Augmented model") (best_thresh, best_f1, pred_glove_val_y) = calc_f1_scores (model, val_X, val_y) pred_augmented_test_y = model.predict([embedding_matrix[test_X]], batch_size=1024, verbose=1) ###Output Augmented model 96131/96131 [==============================] - 9s 94us/step F1 score at threshold 0.1 is 0.5705485635388455 F1 score at threshold 0.11 is 0.5796503420566836 F1 score at threshold 0.12 is 0.5882287679591724 F1 score at threshold 0.13 is 0.5963323522753 F1 score at threshold 0.14 is 0.6032881453706375 F1 score at threshold 0.15 is 0.6103468547912992 F1 score at threshold 0.16 is 0.6155685758699032 F1 score at threshold 0.17 is 0.6214654910307085 F1 score at threshold 0.18 is 0.6262526289743907 F1 score at threshold 0.19 is 0.6311094358587762 F1 score at threshold 0.2 is 0.6364448984803984 F1 score at threshold 0.21 is 0.6400465959099145 F1 score at threshold 0.22 is 0.6439697666776207 F1 score at threshold 0.23 is 0.6474034620505993 F1 score at threshold 0.24 is 0.6503812672919901 F1 score at threshold 0.25 is 0.6523135807531953 F1 score at threshold 0.26 is 0.6541176470588235 F1 score at threshold 0.27 is 0.6565847511027095 F1 score at threshold 0.28 is 0.6584951112370696 F1 score at threshold 0.29 is 0.6604017216642755 F1 score at threshold 0.3 is 0.6614413237535379 F1 score at threshold 0.31 is 0.6630906018076274 F1 score at threshold 0.32 is 0.665377751338489 F1 score at threshold 0.33 is 0.6662657847263981 F1 score at threshold 0.34 is 0.6661596958174905 F1 score at threshold 0.35 is 0.6671787387664183 F1 score at threshold 0.36 is 0.6675984160260889 F1 score at threshold 0.37 is 0.6672419203012236 F1 score at threshold 0.38 is 0.6680932001902045 F1 score at threshold 0.39 is 0.6667199872030712 F1 score at threshold 0.4 is 0.6661291622994437 F1 score at threshold 0.41 is 0.6652552723719567 F1 score at threshold 0.42 is 0.6655149720302731 F1 score at threshold 0.43 is 0.6655049373495975 F1 score at threshold 0.44 is 0.6636531056420559 F1 score at threshold 0.45 is 0.6616020933569681 F1 score at threshold 0.46 is 0.6600255427841636 F1 score at threshold 0.47 is 0.6584800343495062 F1 score at threshold 0.48 is 0.6566155445801923 F1 score at threshold 0.49 is 0.6557032890132961 F1 score at threshold 0.5 is 0.6513437057991514 Best F1 score was at threshold 0.38, 0.6680932001902045 56370/56370 [==============================] - 5s 93us/step
pandas_02_4.ipynb
###Markdown 그래프 그리기 ###Code import pandas %matplotlib inline import matplotlib.pyplot as plt df = pandas.read_csv('C:/Users/김지상/Downloads/doit_pandas-master/doit_pandas-master/data/gapminder.tsv', sep='\t') global_yearly_life_expectancy = df.groupby('year')['lifeExp'].mean() print(global_yearly_life_expectancy) global_yearly_life_expectancy.plot() ###Output _____no_output_____
notebooks/dubins-rejoin.ipynb
###Markdown Dubins 2D Aircraft Rejoin ExampleThis Jupyter notebook demonstrates a multi-agent task scenario with control system analysis framework (CSAF), where a group of Dubins aircraft attempt to rejoin in formation and collectively fly at a specific heading angle. Dubins aircraft presents a dynamically simple 2D aircraft model, taken from the [AerospaceRL repository on GitHub](https://github.com/act3-ace/aerospaceRL). The state space is 3D, being two position coordinates $(x,y)$and a heading angle $\theta$. The control action simply is to apply a heading angular rate $\dot \theta$ while maintaining constant velocity(no throttle). The update equation is$$ \dot{\mathbf x} = \begin{bmatrix}v \cos (x_2) \\v \sin (x_2) \\u \\\end{bmatrix},$$where $\mathbf{x} = (x, y, \theta)$, and $v$ is some fixed airspeed parameter. Controller DesignA lateral rejoin task is specified: given **n** planes at different orientations, produce **n** maneuver sequences that allow them to be no furtherthan some terminal length apart $r_l$ and at some terminal heading angle $\theta_t$. Given that the only control surface that can be affected is angularrate, the following control scheme is formulated,1. Associate each plane with neighbors that should be considered in collision avoidance; construct a graph $\mathcal G = (\mathcal P, \mathcal C)$ with vertices of planes $\mathcal P$ and edges of neighbors $\mathcal C$. In this case, a simple $k$-neighbors was done, with $k=1$; solve only for the nearest neighbor. This method can be extended to different graph constructions, by appropriately weighting the graph edges inversely to the distances between nodes via a weighted adjacency matrix.2. Solve for the angle that will cause a plane $s_i$ and its nearest neighbor $s_j$ to approach one another the fastest,$$\theta_{i}(s_i, s_j) = \operatorname{atan2}(x_{j1} -x_{i1}, x_{j0} - x_{i0}).$$3. Linearly combine the angle $\theta_i$ and the terminal heading angle $\theta_t$. Apply some weight that is a function of the distance between the aircraft $r$, $w: \overline{\mathbb R^-} \rightarrow [0, 1]$,$$\theta_c(s_i) = w(r(s_i, s_j)) \theta_t + (1-w(r(s_i, s_j))) \theta_j.$$ In this example,$$w(r) = \exp\left( -\frac{(r-r_l)^2}{\tau} \right),$$ where $r_l$ is the desired final distance between aircraft, and $\tau$ is a hyperparameter characterizing how soon to apply the collision avoidance correction.4. This solves for the desired heading angle of the aircraft. As the heading angular rate is the input, control the position quantity via a proportional controller,$$u = k_p (\theta_c - \theta).$$ ###Code # if running locally import sys sys.path.append("..") # import csaf and Dubins rejoin example model import csaf import csaf.utils as csafutils import csaf_examples.rejoin as rejoin # other imports import numpy as np import matplotlib.pyplot as plt %matplotlib inline %config InlineBackend.figure_format='retina' ###Output _____no_output_____ ###Markdown ConfigurationThe Dubins system can be created via the `generate_dubins_system` function by passing in a list of vehicles' initial states. A controller is created dynamically to support the number of vehicles specified with the states list. This system component topology can be viewed via the `view_block_diagram` utility function. ###Code j_states = [[0, 0, np.deg2rad(45)], [-5, -10, np.deg2rad(-30)], [-3, -15, np.deg2rad(90)], [0, -20, np.deg2rad(0)]] system = rejoin.generate_dubins_system(j_states) # view the system csafutils.view_block_diagram(system, ipython_notebook=True) ###Output _____no_output_____ ###Markdown SimulationAfter configuration, the CSAF system is simulated via the method `System.simulate_tspan`. The returned traces `trajs` capture the trajectories of each agent as the controller applies the angular rate. ###Code # run simulation trajs = system.simulate_tspan((0.0, 25.0)) # pack states into convenient data structure states = [np.array(trajs['dub'+str(idx)].states) for idx in range(len(j_states))] # show aircraft trajectories cs = ['g', 'r', 'b', 'k'] fig, ax = plt.subplots(figsize=(15, 7)) for idx in range(4): plt.plot(*states[idx][:, :2].T*10, c=cs[idx]) plt.title("Aircraft Trajectories") plt.xlabel("X (m)") plt.ylabel("Y (m)") plt.show() ###Output _____no_output_____ ###Markdown AnimationWhen running the Jupyter notebook, animation is available to view the trajectories as a movie. Uncomment the following code and run. ###Code # uncomment this to get an animation """ %matplotlib notebook ani = rejoin.plot_air_anim(states) from IPython.display import HTML HTML(ani.to_jshtml()) """ ###Output _____no_output_____
FFD_e_HeuristicaResidual_v2.ipynb
###Markdown ###Code def FFD(L, li, di): padroes = [] sobras = [] demanda = dict(zip(li, di)) while sum(demanda.values()) > 0: sobra = L padrao = [] for i in sorted(li, reverse=True): while (i <= sobra) and (demanda[i] > 0): sobra -= i padrao.append(i) demanda[i] = demanda[i]-1 padroes.append(padrao) sobras.append(sobra) return padroes, sobras ###Output _____no_output_____ ###Markdown Exemplo 1: ###Code #### Exemplo 01 - FFD #### L = 11 li = [3, 4, 5] di = [4, 3, 2] padroes, sobras = FFD(L, li, di) print(padroes) print(len(padroes)) print(sobras) print(sum(sobras)) ### Exemplo 1 - Residual FFD ### !pip install ortools from ortools.linear_solver import pywraplp # Inicializa o solver pl = pywraplp.Solver('Exemplo 1', pywraplp.Solver.GLOP_LINEAR_PROGRAMMING) # Dados do Problema N_VAR = 13 N_REST = 3 # Matriz A vezes o vetor x # A*x <= b A = [[3, 2, 1, 0, 0, 0, 0, 2, 2, 1, 1, 1, 0], [0, 0, 0, 2, 1, 0, 0, 1, 0, 2, 1, 0, 1], [0, 0, 0, 0, 0, 2, 1, 0, 1, 0, 0, 1, 1]] # Matriz de coeficientes das restrições B = [4, 3, 2] # Vetor de resultados C = [2, 5, 8, 3, 7, 1, 6, 1, 0, 0, 4, 3, 2] # Coeficientes da função objetivo # alocação de memória das variáveis e restrições x = [] for j in range(N_VAR): x.append(0) rest = [] for i in range(N_REST): rest.append(0) # VARIÁVEIS DE DECISÃO for j in range(N_VAR): x[j] = pl.NumVar(0, pl.infinity(), 'x'+str(j)) # min, max, nome # RESTRIÇÕES # define o lado direito das restrições == for i in range(N_REST): rest[i] = pl.Constraint(B[i], B[i]) # min, max # define o coeficiente das variáveis no lado esquerdo das restrições for i in range(N_REST): # linhas for j in range(N_VAR): # colunas rest[i].SetCoefficient(x[j], A[i][j]) # função objetivo: Minimizar C1*x1 +... obj = pl.Objective() for j in range(N_VAR): obj.SetCoefficient(x[j], C[j]) obj.SetMinimization() # Resolve pl.Solve() # Imprime o valor de cada variável na solução ótima e da função-objetivo print("Função-objetivo = ", pl.Objective().Value()) print() for j in range(N_VAR): # j = 0, 1 print("Padrão de corte%d" %(j+1),"=", x[j].solution_value()) print() solucao_truncada = [] for i in range(len(C)): solucao_truncada.append(int(x[i].solution_value())) print("Solução truncada = ", solucao_truncada) print("Total de objetos = ", sum(solucao_truncada)) print() perda = [] for i in range(len(solucao_truncada)): perda.append(solucao_truncada[i]*C[i]) print("Perda total = ", sum(perda)) print() demanda = B for i in range(len(B)): for j in range(len(solucao_truncada)): demanda[i] = B[i]-solucao_truncada[j]*A[i][j] #demanda.append(temp) print("Demanda atualizada = ", demanda) di = demanda padroes, sobras = FFD(L, li, di) print(padroes) print(len(padroes)) print(sobras) print(sum(sobras)) ###Output [[5, 4], [3]] 2 [2, 8] 10 ###Markdown Exemplo 2: ###Code #### Exemplo 02 - FFD #### L = 600 li = [35, 42, 34, 27] di = [60, 48, 24, 24] padroes, sobras = FFD(L, li, di) print(padroes) print(len(padroes)) print(sobras) print(sum(sobras)) # Exemplo 2 - Residual FFD # Inicializa o solver pl = pywraplp.Solver('Exemplo 2', pywraplp.Solver.GLOP_LINEAR_PROGRAMMING) # Dados do Problema N_VAR = 14 N_REST = 4 # Matriz A vezes o vetor x # A*x <= b A = [[17, 0, 0, 0, 8, 9, 8, 0, 0, 0, 6, 6, 0, 5], [0, 14, 0, 0, 7, 0, 0, 7, 7, 0, 6, 0, 5, 3], [0, 0, 17, 0, 0, 8, 0, 9, 0, 8, 4, 5, 5, 4], [0, 0, 0, 22, 0, 0, 11, 0, 11, 12, 0, 8, 8, 6]] # Matriz de coeficientes das restrições B = [60, 48, 24, 24] # Vetor de resultados C = [5, 12, 22, 6, 26, 13, 23, 0, 9, 4, 2, 4, 4, 1] # Coeficientes da função objetivo # alocação de memória das variáveis e restrições x = [] for j in range(N_VAR): x.append(0) rest = [] for i in range(N_REST): rest.append(0) # VARIÁVEIS DE DECISÃO for j in range(N_VAR): x[j] = pl.NumVar(0, pl.infinity(), 'x'+str(j)) # min, max, nome # RESTRIÇÕES # define o lado direito das restrições == for i in range(N_REST): rest[i] = pl.Constraint(B[i], B[i]) # min, max # define o coeficiente das variáveis no lado esquerdo das restrições for i in range(N_REST): # linhas for j in range(N_VAR): # colunas rest[i].SetCoefficient(x[j], A[i][j]) # função objetivo: Minimizar C1*x1 +... obj = pl.Objective() for j in range(N_VAR): obj.SetCoefficient(x[j], C[j]) obj.SetMinimization() # Resolve pl.Solve() # Imprime o valor de cada variável na solução ótima e da função-objetivo print("Função-objetivo = ", pl.Objective().Value()) print() for j in range(N_VAR): # j = 0, 1 print("Padrão de corte%d" %(j+1),"=", x[j].solution_value()) print() solucao_truncada = [] for i in range(len(C)): solucao_truncada.append(int(x[i].solution_value())) print("Solução truncada = ", solucao_truncada) print("Total de objetos = ", sum(solucao_truncada)) print() perda = [] for i in range(len(solucao_truncada)): perda.append(solucao_truncada[i]*C[i]) print("Perda total = ", sum(perda)) print() demanda = B for i in range(len(B)): for j in range(len(solucao_truncada)): demanda[i] = B[i]-solucao_truncada[j]*A[i][j] #demanda.append(temp) print("Demanda atualizada = ", demanda) di = demanda padroes, sobras = FFD(L, li, di) print(padroes) print(len(padroes)) print(sobras) print(sum(sobras)) 397+23 ###Output _____no_output_____ ###Markdown Exemplo 3: ###Code #### Exemplo 03 - FFD #### L = 194 li = [108, 13, 90] di = [4, 8, 7] padroes, sobras = FFD(L, li, di) print(padroes) print(len(padroes)) print(sobras) print(sum(sobras)) # Exemplo 3 - Residual FFD # Inicializa o solver pl = pywraplp.Solver('Exemplo 3', pywraplp.Solver.GLOP_LINEAR_PROGRAMMING) # Dados do Problema N_VAR = 5 N_REST = 3 # Matriz A vezes o vetor x # A*x <= b A = [[1, 0, 0, 1, 0], [0, 14, 0, 6, 8], [0, 0, 2, 0, 1]] # Matriz de coeficientes das restrições B = [4, 8, 7] # Vetor de resultados C = [86, 12, 14, 8, 0] # Coeficientes da função objetivo # alocação de memória das variáveis e restrições x = [] for j in range(N_VAR): x.append(0) rest = [] for i in range(N_REST): rest.append(0) # VARIÁVEIS DE DECISÃO for j in range(N_VAR): x[j] = pl.NumVar(0, pl.infinity(), 'x'+str(j)) # min, max, nome # RESTRIÇÕES # define o lado direito das restrições == for i in range(N_REST): rest[i] = pl.Constraint(B[i], B[i]) # min, max # define o coeficiente das variáveis no lado esquerdo das restrições for i in range(N_REST): # linhas for j in range(N_VAR): # colunas rest[i].SetCoefficient(x[j], A[i][j]) # função objetivo: Minimizar C1*x1 +... obj = pl.Objective() for j in range(N_VAR): obj.SetCoefficient(x[j], C[j]) obj.SetMinimization() # Resolve pl.Solve() # Imprime o valor de cada variável na solução ótima e da função-objetivo print("Função-objetivo = ", pl.Objective().Value()) print() for j in range(N_VAR): # j = 0, 1 print("Padrão de corte%d" %(j+1),"=", x[j].solution_value()) print() solucao_truncada = [] for i in range(len(C)): solucao_truncada.append(int(x[i].solution_value())) print("Solução truncada = ", solucao_truncada) print("Total de objetos = ", sum(solucao_truncada)) print() perda = [] for i in range(len(solucao_truncada)): perda.append(solucao_truncada[i]*C[i]) print("Perda total = ", sum(perda)) print() demanda = B for i in range(len(B)): for j in range(len(solucao_truncada)): demanda[i] = B[i]-solucao_truncada[j]*A[i][j] #demanda.append(temp) print("Demanda atualizada = ", demanda) di = demanda padroes, sobras = FFD(L, li, di) print(padroes) print(len(padroes)) print(sobras) print(sum(sobras)) 222+164 ###Output _____no_output_____ ###Markdown Exemplo 4: ###Code #### Exemplo 04 - FFD #### L = 220 li = [80, 60, 40, 20] di = [10, 10, 15, 15] padroes, sobras = FFD(L, li, di) print(padroes) print(len(padroes)) print(sobras) print(sum(sobras)) # Exemplo 4 - Residual FFD # Inicializa o solver pl = pywraplp.Solver('Exemplo 4', pywraplp.Solver.GLOP_LINEAR_PROGRAMMING) # Dados do Problema N_VAR = 18 N_REST = 4 # Matriz A vezes o vetor x # A*x <= b A = [[2,0,0,0,2,1,1,2,1,1,0,0,0,0,0,0,0,0], [0,3,0,0,1,2,2,0,0,0,3,2,2,1,0,0,0,0], [0,0,5,0,0,0,0,1,3,3,1,2,2,4,5,4,3,2], [0,0,0,6,0,0,1,0,0,1,0,0,1,0,1,3,5,6]] # Matriz de coeficientes das restrições B = [10, 10, 15, 15] # Vetor de resultados C = [60,40,20,100,0,20,0,20,20,0,0,20,0,0,0,0,0,20] # Coeficientes da função objetivo # alocação de memória das variáveis e restrições x = [] for j in range(N_VAR): x.append(0) rest = [] for i in range(N_REST): rest.append(0) # VARIÁVEIS DE DECISÃO for j in range(N_VAR): x[j] = pl.NumVar(0, pl.infinity(), 'x'+str(j)) # min, max, nome # RESTRIÇÕES # define o lado direito das restrições == for i in range(N_REST): rest[i] = pl.Constraint(B[i], B[i]) # min, max # define o coeficiente das variáveis no lado esquerdo das restrições for i in range(N_REST): # linhas for j in range(N_VAR): # colunas rest[i].SetCoefficient(x[j], A[i][j]) # função objetivo: Minimizar C1*x1 +... obj = pl.Objective() for j in range(N_VAR): obj.SetCoefficient(x[j], C[j]) obj.SetMinimization() # Resolve pl.Solve() # Imprime o valor de cada variável na solução ótima e da função-objetivo print("Função-objetivo = ", pl.Objective().Value()) print() for j in range(N_VAR): # j = 0, 1 print("Padrão de corte%d" %(j+1),"=", x[j].solution_value()) print() solucao_truncada = [] for i in range(len(C)): solucao_truncada.append(int(x[i].solution_value())) print("Solução truncada = ", solucao_truncada) print("Total de objetos = ", sum(solucao_truncada)) print() perda = [] for i in range(len(solucao_truncada)): perda.append(solucao_truncada[i]*C[i]) print("Perda total = ", sum(perda)) print() demanda = B for i in range(len(B)): for j in range(len(solucao_truncada)): demanda[i] = B[i]-solucao_truncada[j]*A[i][j] #demanda.append(temp) print("Demanda atualizada = ", demanda) di = demanda padroes, sobras = FFD(L, li, di) print(padroes) print(len(padroes)) print(sobras) print(sum(sobras)) ###Output [[80, 80, 60], [80, 60, 40, 40], [40, 20, 20, 20]] 3 [0, 0, 120] 120 ###Markdown Exemplo 5: ###Code #### Exemplo 05 - FFD #### L = 4500 li = [550, 575, 1450, 950] di = [15, 10, 20, 9] padroes, sobras = FFD(L, li, di) print(padroes) print(len(padroes)) print(sobras) print(sum(sobras)) # Exemplo 5 - Residual FFD # Inicializa o solver pl = pywraplp.Solver('Exemplo 5', pywraplp.Solver.GLOP_LINEAR_PROGRAMMING) # Dados do Problema N_VAR = 19 N_REST = 4 # Matriz A vezes o vetor x # A*x <= b A = [[8,0,0,0,7,6,5,4,5,2,1,0,0,0,0,0,0,0,0], [0,7,0,0,1,2,3,4,0,0,0,5,2,6,4,2,1,1,0], [0,0,3,0,0,0,0,0,1,2,2,1,2,0,0,0,0,2,1], [0,0,0,4,0,0,0,0,0,0,1,0,0,1,2,3,4,1,3]] # Matriz de coeficientes das restrições B = [15, 10, 20, 9] # Vetor de resultados C = [100,475,150,700,75,50,25,0,300,500,100,175,450,100,300,500,125,75,200] # Coeficientes da função objetivo # alocação de memória das variáveis e restrições x = [] for j in range(N_VAR): x.append(0) rest = [] for i in range(N_REST): rest.append(0) # VARIÁVEIS DE DECISÃO for j in range(N_VAR): x[j] = pl.NumVar(0, pl.infinity(), 'x'+str(j)) # min, max, nome # RESTRIÇÕES # define o lado direito das restrições == for i in range(N_REST): rest[i] = pl.Constraint(B[i], B[i]) # min, max # define o coeficiente das variáveis no lado esquerdo das restrições for i in range(N_REST): # linhas for j in range(N_VAR): # colunas rest[i].SetCoefficient(x[j], A[i][j]) # função objetivo: Minimizar C1*x1 +... obj = pl.Objective() for j in range(N_VAR): obj.SetCoefficient(x[j], C[j]) obj.SetMinimization() # Resolve pl.Solve() # Imprime o valor de cada variável na solução ótima e da função-objetivo print("Função-objetivo = ", pl.Objective().Value()) print() for j in range(N_VAR): # j = 0, 1 print("Padrão de corte%d" %(j+1),"=", x[j].solution_value()) print() solucao_truncada = [] for i in range(len(C)): solucao_truncada.append(int(x[i].solution_value())) print("Solução truncada = ", solucao_truncada) print("Total de objetos = ", sum(solucao_truncada)) print() perda = [] for i in range(len(solucao_truncada)): perda.append(solucao_truncada[i]*C[i]) print("Perda total = ", sum(perda)) print() demanda = B for i in range(len(B)): for j in range(len(solucao_truncada)): demanda[i] = B[i]-solucao_truncada[j]*A[i][j] #demanda.append(temp) print("Demanda atualizada = ", demanda) di = demanda padroes, sobras = FFD(L, li, di) print(padroes) print(len(padroes)) print(sobras) print(sum(sobras)) 775+1675 ###Output _____no_output_____
Working Notebooks/.ipynb_checkpoints/Base_scrape_1-checkpoint.ipynb
###Markdown Imports ###Code from bs4 import BeautifulSoup import numpy as np import pandas as pd import requests ###Output _____no_output_____ ###Markdown Website URL list construction ###Code ## The 'target_url' is the homepage of the target website ## The 'url_prefix' is the specific URL you use to append with the ## for-loop below. target_url = 'https://sfbay.craigslist.org' url_prefix = 'https://sfbay.craigslist.org/d/musical-instruments/search/msa?s=' pages = ['120','240','360','480','600','720','840', '960','1080','1200','1320','1440','1560','1680', '1800','1920','2040','2160','2280','2400','2520', '2640','2760','2880','3000'] ## This tests to make sure the URL list compiler is working ## on 3 pages. # pages = ['120', '240', '360'] url_list = [] ## This loop takes the base URL and adds just the string from the ## 'pages' object above so that each 'url' that goes into the ## 'url_list' is in the correct step of 120 results. for page in pages: url = url_prefix + page url_list.append(url) ## This prints the 'url_list' as a QC check. url_list ###Output _____no_output_____ ###Markdown Scraping for-loop* This is what I'm calling a "dynamic" scraping function. It's dynamic in the sense that it collects and defines the html as objects in real time. * Another method would be what I'm calling "static" scraping where the output from the 'url in url_list' for-loop is put into a list outside of the function with the entirity of the url's html. The scraping then happens to a static object.* Choose ** **ONE** ** approach: Dynamic or Static The "dynamic" method ###Code ''' ****NOTE**** The two empty lists 'df_list' and 'each_html_output' will need to be empty. Therefore, make sure to restart the kernal before running this cell. ''' df_list = [] each_html_output = [] def attribute_scraping(starting_url): """ These are the 5 attributes I am scraping from Craigslist. Any additional pieces of information to be made into objects will require * adding an empty list *an additional for-loop or if statement depending on the find target * adding to the dictionary at the end of the this function * adding to the print statement set at the end of this function """ has_pics_bool = [] price = [] just_titles = [] HOOD_list = [] just_posted_datetimes = [] """ Parameters ---------- response = requests.get(url) * This makes a request to the URL and returns a status code page = response.text * the html text (str object) from the 'get(url)' soup = BeautifulSoup(page, 'html.parser') * makes a BeautifulSoup object called 'page' * utilizes the parser designated in quotes as the second input of the method results = soup.find_all('li', class_='result-row') * returns an element ResultSet object. * this is the html text that was isolated from using the 'find()' or 'find_all()' methods. * 'li' is an html list tag. * 'class_' is the designator for a class attribute. - Here this corresponds with the 'result_row' class """ for url in url_list: response = requests.get(url) page = response.text soup = BeautifulSoup(page, 'html.parser') results = soup.find_all('li', class_='result-row') for res in results: """PRICE""" ## Loop for finding PRICE for a single page of 120 results p = res.find('span', class_='result-price').text price.append(p) """PICS""" ## Loop for finding the boolean HAS PICS of a single page of ## 120 results. This tests whether >=1 picture is an attribute ## of the post. if res.find('span', class_='pictag') is None: has_pics_bool.append("False") else: has_pics_bool.append('True') """NEIGHBORHOOD""" ## Loop for finding NEIGHBORHOOD name for a single page of 120 ## results. This includes the drop down menu choices on ## Craigslist as well as the manually entered neighborhoods. if res.find('span', class_="result-hood") is None: HOOD_list.append("NONE") else: h = res.find('span', class_="result-hood").text HOOD_list.append(h) """TITLE""" ## Loop for finding TITLE for a single page of 120 results titles=soup.find_all('a', class_="result-title hdrlnk") for title in titles: just_titles.append(title.text) """DATETIME""" ## Loop for finding DATETIME for a single page of 120 results posted_datetimes=soup.find_all(class_='result-date') for posted_datetime in posted_datetimes: if posted_datetime.has_attr('datetime'): just_posted_datetimes.append(posted_datetime['datetime']) # Compilation dictionary of for-loop results comp_dict = {'price': price, 'pics': has_pics_bool, 'hood': HOOD_list, 'title': just_titles, 'datetimes': just_posted_datetimes} return comp_dict print(len(price)) print(len(has_pics_bool)) print(len(HOOD_list)) print(len(just_titles)) print(len(just_posted_datetimes)) ###Output _____no_output_____ ###Markdown Run the function and check the output dictionary. ###Code base_dict = attribute_scraping(target_url) base_dict ###Output _____no_output_____ ###Markdown Construct dataframe using dictionary ###Code df_base = pd.DataFrame(base_dict) df_base ###Output _____no_output_____ ###Markdown Sort the results by the 'datetime' to order them by posting time. ###Code df_base.sort_values('datetimes') ###Output _____no_output_____ ###Markdown Convert to csv for import into regression notebook ###Code df_base.to_csv('/Users/johnmetzger/Desktop/Coding/Project2/base_scrape.csv', index = False) ###Output _____no_output_____
_posts/ithome/2020-12th-ironman/20.XGBoost(分類器)/.ipynb_checkpoints/XGBoost (Classfication-iris)-checkpoint.ipynb
###Markdown 1) 載入資料集 ###Code url = 'https://github.com/1010code/iris-dnn-tensorflow/raw/master/data/Iris.csv' s=requests.get(url).content df_data=pd.read_csv(io.StringIO(s.decode('utf-8'))) df_data = df_data.drop(labels=['Id'],axis=1) # 移除Id df_data ###Output _____no_output_____ ###Markdown 2) 手動編碼處理名目資料 (Nominal variables) - 資料前處理依據特徵資料的特性,可以選擇手動編碼或自動編碼。 使用編碼時機?進行深度學習時,神經網路只能處理數值資料。因此我們需要將所有非數字型態的特徵進行轉換。ex:| Iris-setosa | Iris-versicolor | Iris-virginica ||:---:|:---:|:---:|| 1 | 2 | 3 | ###Code label_map = {'Iris-setosa': 0, 'Iris-versicolor': 1, 'Iris-virginica': 2} #將編碼後的label map存至df_data['Species']中。 df_data['Class'] = df_data['Species'].map(label_map) df_data ###Output _____no_output_____ ###Markdown 3) 檢查缺失值使用 numpy 所提供的函式來檢查是否有 NA 缺失值,假設有缺失值使用dropna()來移除。使用的時機在於當只有少量的缺失值適用,若遇到有大量缺失值的情況,或是本身的資料量就很少的情況下建議可以透過機器學習的方法補值來預測缺失值。```python 移除缺失值train=train.dropna()``` ###Code X = df_data.drop(labels=['Species','Class'],axis=1).values # 移除Species (因為字母不參與訓練) # checked missing data print("checked missing data(NAN mount):",len(np.where(np.isnan(X))[0])) ###Output checked missing data(NAN mount): 0 ###Markdown 4) 切割訓練集與測試集 ###Code from sklearn.model_selection import train_test_split X=df_data.drop(labels=['Class','Species'],axis=1) y=df_data['Class'] X_train , X_test , y_train , y_test = train_test_split(X,y , test_size=.3 , random_state=42) print('Training data shape:',X_train.shape) print('Testing data shape:',X_test.shape) ###Output Training data shape: (105, 4) Testing data shape: (45, 4) ###Markdown XGBoostBoosting 則是希望能夠由後面生成的樹,來修正前面樹學的不好的地方。Parameters:- n_estimators: 總共迭代的次數,即決策樹的個數。預設值為100。- max_depth: 樹的最大深度,默認值為6。- booster: gbtree 樹模型(預設) / gbliner 線性模型- learning_rate: 學習速率,預設0.3。- gamma: 懲罰項係數,指定節點分裂所需的最小損失函數下降值。Attributes:- feature_importances_: 查詢模型特徵的重要程度。Methods:- fit: 放入X、y進行模型擬合。- predict: 預測並回傳預測類別。- score: 預測成功的比例。- predict_proba: 預測每個類別的機率值。 ###Code from xgboost import XGBClassifier # 建立XGBClassifier模型 xgboostModel = XGBClassifier(n_estimators=100, learning_rate= 0.3) # 使用訓練資料訓練模型 xgboostModel.fit(X_train, y_train) # 使用訓練資料預測分類 predicted = xgboostModel.predict(X_train) ###Output _____no_output_____ ###Markdown 使用Score評估模型 ###Code # 預測成功的比例 print('訓練集: ',xgboostModel.score(X_train,y_train)) print('測試集: ',xgboostModel.score(X_test,y_test)) ###Output 訓練集: 1.0 測試集: 1.0 ###Markdown 特徵重要程度 ###Code from xgboost import plot_importance from xgboost import plot_tree plot_importance(xgboostModel) print('特徵重要程度: ',xgboostModel.feature_importances_) ###Output 特徵重要程度: [0.01001516 0.03135139 0.7407739 0.21785954] ###Markdown 真實分類 ###Code # 建立訓練集的 DataFrme df_train=pd.DataFrame(X_train) df_train['Class']=y_train # 建立測試集的 DataFrme df_test=pd.DataFrame(X_test) df_test['Class']=y_test sns.lmplot("PetalLengthCm", "PetalWidthCm", hue='Class', data=df_train, fit_reg=False) ###Output _____no_output_____ ###Markdown 隨機森林 (訓練集)預測結果 ###Code df_train['Predict']=predicted sns.lmplot("PetalLengthCm", "PetalWidthCm", data=df_train, hue="Predict", fit_reg=False) plt.show() ###Output _____no_output_____
Final/Submission.ipynb
###Markdown Genre Prediction based on plot summary __Contributors__: Aaron Riegel and Christoph Schartner__Class__: DS200 Introduction to Data Science__Files__: movie_data.json ###Code import pandas as pd import numpy as np import json import seaborn as sns import matplotlib.pyplot as plt import warnings warnings.filterwarnings('ignore') nltk.download('stopwords') ###Output [nltk_data] Downloading package stopwords to [nltk_data] /home/christoph/nltk_data... [nltk_data] Package stopwords is already up-to-date! ###Markdown Data processing Reading file from *movie_data.json* ###Code with open(r'movie_data.json', 'r') as json_file: data = json.load(json_file) movies = pd.DataFrame(data) movies.drop(movies.columns.difference(['id', 'title', 'genres', 'release_date', 'overview']), axis=1, inplace=True) movies.dropna(inplace=True) movies = movies[['id', 'title', 'genres', 'release_date', 'overview']] movies['release_date'] = pd.to_datetime(movies['release_date']) movies.info() ###Output <class 'pandas.core.frame.DataFrame'> Int64Index: 10000 entries, 0 to 9999 Data columns (total 5 columns): id 10000 non-null int64 title 10000 non-null object genres 10000 non-null object release_date 9995 non-null datetime64[ns] overview 10000 non-null object dtypes: datetime64[ns](1), int64(1), object(3) memory usage: 468.8+ KB ###Markdown Creating binary columns for genres ###Code def update_genre(col): for genre in col.genres: col.loc[genre['name']] = 1 return col genres = set() for movie in movies['genres']: for genre in movie: genres.add(genre['name']) genres = list(genres) movies = pd.merge(movies, pd.DataFrame(data=np.zeros((movies.shape[0], len(genres)), dtype=int), columns=genres), left_index=True, right_index=True) movies = movies.apply(update_genre, axis=1) movies.drop('genres', inplace=True, axis=1) movies.head() ###Output _____no_output_____ ###Markdown Visualization ###Code plt.figure(figsize=(12,6), ) genre_count = movies[genres].sum().sort_values(ascending=False) g = sns.barplot(genre_count.values, genre_count.index, palette='rainbow', ) g.set g.set_title('Genre distribution') g.set_xlabel('Number of movies') pair = sns.pairplot(movies.drop(['title'],axis=1), vars=['person','car', 'pizza','knife','truck'], hue= 'Action') ###Output _____no_output_____ ###Markdown Analysis Clean Data ###Code def clean(text): # use regular expression to remove specific characters text = re.sub("\'", " ", text) text = re.sub("[^a-zA-Z]"," ",text) text = ' '.join(text.split()) text = text.lower() return text movies['clean_overview'] = movies['overview'].astype(str).apply(lambda x: clean(x)) movies.head() ###Output _____no_output_____ ###Markdown YOLO Data Approach ###Code y = final.drop(final[['id','title']], axis = 1) y = y[['Mystery', 'Animation', 'Music', 'History', 'Comedy', 'Science Fiction', 'Family', 'Fantasy', 'Romance', 'Horror', 'War', 'Documentary', 'TV Movie', 'Adventure', 'Drama', 'Western', 'Thriller', 'Action', 'Crime']] X = final.drop(final[['Mystery', 'Animation', 'Music', 'History', 'Comedy', 'Science Fiction', 'Family', 'Fantasy', 'Romance', 'Horror', 'War', 'Documentary', 'TV Movie', 'Adventure', 'Drama', 'Western', 'Thriller', 'Action', 'Crime','overview','release_date']], axis = 1) X = X.drop(X[['title','id']], axis = 1) from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42) from sklearn.svm import SVC from sklearn.multiclass import OneVsRestClassifier model = OneVsRestClassifier(SVC(gamma='auto')) model.fit(X_train,y_train) predicted = model.predict(X_test) from sklearn.metrics import confusion_matrix, classification_report print(f'{classification_report(y_test,predicted)}') ###Output _____no_output_____ ###Markdown Word2Vec Approach ###Code movies_path = '../Data/movies_df.csv' movies = pd.read_csv(movies_path) movies.columns movies = movies.drop(['release_date'], axis=1) movies = movies.drop(['overview'],axis=1) from gensim.models import Word2Vec from gensim.models import KeyedVectors filename = '../GoogleNews-vectors-negative300.bin' model = KeyedVectors.load_word2vec_format(filename, binary=True) stoplist = set('for a of the and to in : &'.split()) punctuation = set('; / " . , :'.split()) def most_likely(title, genres = ['Mystery', 'Animation', 'Music', 'History', 'Comedy', 'Science', 'Family', 'Fantasy', 'Romance', 'Horror', 'War', 'Documentary', 'TV', 'Adventure', 'Drama', 'Western', 'Thriller', 'Action', 'Crime']): broken_title = title.split(' ') print(broken_title) dists = [] d = [0] * len(genres) for word in broken_title: if word.lower() in stoplist: continue else: for stop in punctuation: if stop in word: word = word.split(stop)[0] for genre in genres: d[genres.index(genre)] += model.distance(word.lower(), genre) dists = [x / len(broken_title) for x in d] print(sorted(zip(dists,genres), reverse = False)[:3]) genres = ['Mystery', 'Animation', 'Music', 'History', 'Comedy', 'Science', 'Family', 'Fantasy', 'Romance', 'Horror', 'War', 'Documentary', 'TV', 'Adventure', 'Drama', 'Western', 'Thriller', 'Action', 'Crime'] most_likely('how to train your dragon:', genres) ###Output _____no_output_____ ###Markdown TF-IDF Approach ###Code import re import nltk df = pd.read_csv('../Data/movies_df.csv') def clean(text): # use regular expression to remove specific characters text = re.sub("\'", " ", text) text = re.sub("[^a-zA-Z]"," ",text) text = ' '.join(text.split()) text = text.lower() return text df['clean_overview'] = df['overview'].astype(str).apply(lambda x: clean(x)) stpwrds = set(nltk.corpus.stopwords.words('english')) def remove_stops(text): cleaned = [w for w in text.split() if not w in stpwrds] return ' '.join(cleaned) df['clean_overview'] = df['clean_overview'].astype(str).apply(lambda x: remove_stops(x)) from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.model_selection import train_test_split tfidf_vectorizer = TfidfVectorizer(max_df=0.8, max_features=10000) X = df['clean_overview'] y = df[['Family', 'Animation', 'History', 'Documentary', 'Adventure', 'Western', 'Crime', 'Drama', 'Horror', 'Science Fiction', 'Romance', 'War', 'Mystery', 'Fantasy', 'Action', 'TV Movie', 'Thriller', 'Comedy', 'Music']] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42) tfidf_xtrain = tfidf_vectorizer.fit_transform(X_train) tfidf_xtest = tfidf_vectorizer.transform(X_test) from sklearn.svm import SVC from sklearn.multiclass import OneVsRestClassifier from sklearn.metrics import classification_report model = OneVsRestClassifier(SVC(gamma = 'auto',kernel = 'linear')) model.fit(tfidf_xtrain, y_train) predictions = model.predict(tfidf_xtest) print(classification_report(predictions,y_test)) ###Output _____no_output_____ ###Markdown Use Multilabel Binarizer Instead ###Code def make_genre_list(s): genre_list = ['Family', 'Animation', 'History', 'Documentary', 'Adventure', 'Western', 'Crime', 'Drama', 'Horror', 'Science Fiction', 'Romance', 'War', 'Mystery', 'Fantasy', 'Action', 'TV Movie', 'Thriller', 'Comedy', 'Music'] gen = [] for g in genre_list: if s.loc[g] == 1: gen.append(g) return gen df['genre_list'] = df.apply(lambda row : make_genre_list(row), axis = 1) from sklearn.preprocessing import MultiLabelBinarizer multilabel_binarizer = MultiLabelBinarizer() multilabel_binarizer.fit(df['genre_list']) X = df['clean_overview'] y = multilabel_binarizer.transform(df['genre_list']) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42) tfidf_xtrain = tfidf_vectorizer.fit_transform(X_train) tfidf_xtest = tfidf_vectorizer.transform(X_test) model = OneVsRestClassifier(SVC(gamma = 'auto', kernel = 'linear')) model.fit(tfidf_xtrain, y_train) predictions = model.predict(tfidf_xtest) print(classification_report(predictions,y_test)) from sklearn.linear_model import LogisticRegression logovr = OneVsRestClassifier(LogisticRegression()) logovr.fit(tfidf_xtrain, y_train) predicted = logovr.predict(tfidf_xtest) print(classification_report(predicted, y_test)) mbi = multilabel_binarizer.inverse_transform(predicted) y_test_df = pd.DataFrame() y_test_df['genres'] = y_test.apply(lambda row : make_genre_list(row), axis = 1) ytgenres = list(y_test_df['genres']) for i in range(len(mbi)): print(f'{mbi[i]}\t\t\t\t{ytgenres[i]}') word_counts(movies['clean_overview'], 200) ###Output _____no_output_____
notebooks/political_entity.ipynb
###Markdown Create the Political Entity table We will use the unique countries in the USDA agricultural data and a list of US state and territory names borrowed from gist.github.com ###Code zip_url = "https://apps.fas.usda.gov/psdonline/downloads/psd_alldata_csv.zip" r = requests.get(zip_url) if r.ok: z = zipfile.ZipFile(io.BytesIO(r.content)) usda_data = pd.read_csv(z.open('psd_alldata.csv')) usda_data["Country_Name"].unique() pol_ent = pd.DataFrame(usda_data["Country_Name"].unique(), columns = ["name"]) pol_ent["is_country"] = 1 pol_ent["abbrev"] = '' pol_ent ###Output _____no_output_____ ###Markdown Add in the US political entity names List of names taken from https://gist.github.com/rogerallen/1583593 ###Code us_state_abbrev = { 'Alabama': 'AL', 'Alaska': 'AK', 'American Samoa': 'AS', 'Arizona': 'AZ', 'Arkansas': 'AR', 'California': 'CA', 'Colorado': 'CO', 'Connecticut': 'CT', 'Delaware': 'DE', 'District of Columbia': 'DC', 'Florida': 'FL', 'Georgia': 'GA', 'Guam': 'GU', 'Hawaii': 'HI', 'Idaho': 'ID', 'Illinois': 'IL', 'Indiana': 'IN', 'Iowa': 'IA', 'Kansas': 'KS', 'Kentucky': 'KY', 'Louisiana': 'LA', 'Maine': 'ME', 'Maryland': 'MD', 'Massachusetts': 'MA', 'Michigan': 'MI', 'Minnesota': 'MN', 'Mississippi': 'MS', 'Missouri': 'MO', 'Montana': 'MT', 'Nebraska': 'NE', 'Nevada': 'NV', 'New Hampshire': 'NH', 'New Jersey': 'NJ', 'New Mexico': 'NM', 'New York': 'NY', 'North Carolina': 'NC', 'North Dakota': 'ND', 'Northern Mariana Islands':'MP', 'Ohio': 'OH', 'Oklahoma': 'OK', 'Oregon': 'OR', 'Pennsylvania': 'PA', 'Puerto Rico': 'PR', 'Rhode Island': 'RI', 'South Carolina': 'SC', 'South Dakota': 'SD', 'Tennessee': 'TN', 'Texas': 'TX', 'Utah': 'UT', 'Vermont': 'VT', 'Virgin Islands': 'VI', 'Virginia': 'VA', 'Washington': 'WA', 'West Virginia': 'WV', 'Wisconsin': 'WI', 'Wyoming': 'WY' } states = np.array(list(us_state_abbrev.keys())) abbrev = np.array(list(us_state_abbrev.values())) us = pd.DataFrame(states, columns = ["name"]) us["abbrev"] = abbrev us["is_country"] = 0 us pol_ent = pol_ent.append(us) pol_ent ###Output _____no_output_____ ###Markdown Now create a unique ID just in case of name collisions between country names and US states/territories ###Code pol_ent = pol_ent.sort_values(by = "name") pol_ent["id"] = np.arange(0, pol_ent.shape[0]) pol_ent[["id", "name", "is_country", "abbrev"]] pol_ent[["id", "name", "is_country", "abbrev"]].to_csv(data_path + "political_entity.csv", index = False) ###Output _____no_output_____
Conversions/Number Conversions.ipynb
###Markdown Contents* [Binary number conversion](Binary-number-conversion)* [Hexadecimal number conversion](Hexadecimal-number-conversion)* [BCD conversions](BCD-conversions) * [Hex to BCD conversion](Hex-to-BCD-conversion) * [Decimal to BCD conversion](Decimal-to-BCD-conversion) Binary number conversion Convert specified decimal number to binary format. to_binary(NUMBER, LENGTH=8) - **NUMBER**: Decimal number to convert into binary format.- **LENGTH**: Length of the binary number. Default and minimum length is 8. ###Code import bu_convert bu_convert.to_binary(170, 8) ###Output 10101010 ###Markdown Hexadecimal number conversion Convert specified decimal number to hexadecimal format. to_hex(NUMBER, LENGTH=2) - **NUMBER**: Decimal number to convert into hexadecimal format.- **LENGTH**: Length of the hexadecimal number. Default and minimum length is 2. ###Code import bu_convert bu_convert.to_hex(78, 2) ###Output 0x4E ###Markdown BCD conversions Hex to BCD conversionConvert specified hexadecimal number to BCD. hex_to_bcd(NUMBER) - **NUMBER**: Number in hexadecimal format. ###Code import bu_convert bu_convert.hex_to_bcd("0x1D") ###Output 00101001 ###Markdown Decimal to BCD conversionConvert specified decimal number to BCD. int_to_bcd(NUMBER) - **NUMBER**: Number to convert into BCD. ###Code import bu_convert bu_convert.int_to_bcd(45) ###Output 01000101
Sessions/Session02/Day2/ModelSelection_ExerciseSolutions.ipynb
###Markdown Model Selection For Machine LearningIn this exercise, we will explore methods to do model selection in a machine learning context, in particular cross-validation and information criteria. At the same time, we'll learn about `scikit-learn`'s class structure and how to build a pipeline. Why Model Selection?There are several reasons why you might want to perform model selection:* You might not be sure which machine learning algorithm is most appropriate.* The algorithm you have chosen might have a regularization parameter whose value you want to determine.* The algorithm you have chosen might have other parameters (e.g. the depth of a decision tree, the number of clusters in `KMeans`, ...) you would like to determine.* You might not be sure which of your features are the most useful/predictive.**Question**: Can you think of other reasons and contexts in which model selection might be important?Your decisions for how to do model selection depend very strongly (like everything else in machine learning) on the purpose of your machine learning procedure. Is your main purpose to accurately **predict** outcomes for new samples? Or are you trying to **infer** something about the system? Inference generally restricts the number of algorithms you can reasonably use, and also the number of model selection procedures you can apply. In the following, assume that everything below works for prediction problems; I will point out methods for inference where appropriate. Additionally, assume that everything below works for *supervised machine learning*. We will cover *unsupervised* methods further below. ImportsLet's first import some stuff we're going to need. ###Code %matplotlib inline import matplotlib.pyplot as plt # comment out this line if you don't have seaborn installed import seaborn as sns sns.set_palette("colorblind") import numpy as np ###Output _____no_output_____ ###Markdown First, we're going to need some data. We'll work with the star-galaxy data from the first session. This uses the `astroquery` package and then queries the top 10000 observations from SDSS (see [this exercise](https://github.com/LSSTC-DSFP/LSSTC-DSFP-Sessions/blob/master/Session1/Day4/StarGalaxyRandomForest.ipynb) for more details): ###Code # execute this line: from astroquery.sdss import SDSS TSquery = """SELECT TOP 10000 p.psfMag_r, p.fiberMag_r, p.fiber2Mag_r, p.petroMag_r, p.deVMag_r, p.expMag_r, p.modelMag_r, p.cModelMag_r, s.class FROM PhotoObjAll AS p JOIN specObjAll s ON s.bestobjid = p.objid WHERE p.mode = 1 AND s.sciencePrimary = 1 AND p.clean = 1 AND s.class != 'QSO' ORDER BY p.objid ASC """ SDSSts = SDSS.query_sql(TSquery) SDSSts ###Output _____no_output_____ ###Markdown **Exercise 1**: Visualize this data set. What representation is most appropriate, do you think? **Exercise 2**: Let's now do some machine learning. In this exercise, you are going to use a random forest classifier to classify this data set. Here are the steps you'll need to perform:* Split the column with the classes (stars and galaxies) from the rest of the data* Cast the features and the classes to numpy arrays* Split the data into a *test* set and a *training* set. The training set will be used to train the classifier; the test set we'll reserve for the very end to test the final performance of the model (more on this on Friday). You can use the `scikit-learn` function `test_train_split` for this task* Define a `RandomForest` object from the `sklearn.ensemble` module. Note that the `RandomForest` class has three parameters: - `n_estimators`: The number of decision trees in the random forest - `max_features`: The maximum number of features to use for the decision trees - `min_samples_leaf`: The minimum number of samples that need to end up in a terminal leaf (this effectively limits the number of branchings each tree can make)* We'll want to use *cross-validation* to decide between parameters. You can do this with the `scikit-learn` class `GridSearchCV`. This class takes a classifier as an input, along with a dictionary of the parameter values to search over.In the earlier lecture, you learned about four different types of cross-validation:* hold-out cross validation, where you take a single validation set to compare your algorithm's performance to* k-fold cross validation, where you split your training set into k subsets, each of which holds out a different portion of the data* leave-one-out cross validation, where you have N different subsets, each of which leaves just one sample as a validation set* random subset cross validation, where you pick a random subset of your data points k times as your validation set.**Exercise 2a**: Which of the four algorithms is most appropriate here? And why?**Answer**: In this case, k-fold CV or random subset CV seem to be the most appropriate algorithms to use.* Using hold-out cross validation leads to a percentage of the data not being used for training at all. * Given that the data set is not too huge, using k-fold CV probably won't slow down the ML procedure too much.* LOO CV is particularly useful for small data sets, where even training on a subset of the training data is difficult (for example because there are only very few examples of a certain class). * Random subset CV could also yield good results, since there's no real ordering to the training data. Do not use this algorithm when the ordering matters (for example in Hidden Markov Models)**Important:** One important thing to remember that cross-validation crucially depends on your *samples* being **independent** from each other. Be sure that this is the case before using it. For example, say you want to classify images of galaxies, but your data set is small, and you're not sure whether your algorithm is rotation independent. So you might choose to use the same images multiple times in your training data set, but rotated by a random degree. In this case, you *have* to make sure all versions of the same image are included in the **same** data set (either the training, the validation or the test set), and not split across data sets! If you don't, your algorithm will be unreasonably confident in its accuracy (because you are training and validating essentially on the same data points). Note that `scikit-learn` can actually deal with that! The class [`GroupKFold`](http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GroupKFold.htmlsklearn.model_selection.GroupKFold) allows k-fold cross validation using an array of indices for your training data. Validation sets will only be split among samples with *different* indices. But this was just an aside. Last time, you used a random forest and used k-fold cross validation to effectively do model selection for the different parameters that the random forest classifier uses. **Exercise 2b**: Now follow the instructions above and implement your random forest classifier. ###Code from sklearn.cross_validation import train_test_split from sklearn.grid_search import GridSearchCV from sklearn.ensemble import RandomForestClassifier # set the random state rs = 23 # we are in Chicago after all # extract feature names, remove class feats = list(SDSSts.columns) feats.remove('class') # cast astropy table to pandas, remove classes X = np.array(SDSSts[feats].to_pandas()) # our classes are the outcomes to classify on y = np.array(SDSSts['class']) # let's do a split in training and test set: X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = rs) # we'll leave the test set for later. # instantiate the random forest classifier: RFmod = RandomForestClassifier() # do a grid search over the free random forest parameters: pars = {"n_estimators": [10, 100, 300], "max_features": [1, 3, 7], "min_samples_leaf": [1,10]} grid_results = GridSearchCV(RandomForestClassifier(), pars, cv = 5) grid_results.fit(X_train, y_train) ###Output _____no_output_____ ###Markdown **Exercise 2c**: Take a look at the different validation scores for the different parameter combinations. Are they very different or are they similar? ###Code grid_results.grid_scores_ ###Output _____no_output_____ ###Markdown It looks like the scores are very similar, and have very small variance between the different cross validation instances. It can be useful to do this kind of representation to see for example whether there is a large variance in the cross-validation results. Cross-validating Multiple Model ComponentsIn most machine learning applications, your machine learning algorithm might not be the only component having free parameters. You might not even be sure which machine learning algorithm to use! For demonstration purposes, imagine you have many features, but many of them might be correlated. A standard dimensionality reduction technique to use is [Principal Component Analysis](http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html). **Exercise 4**: The number of features in our present data set is pretty small, but let's nevertheless attempt to reduce dimensionality with PCA. Run a PCA decomposition in 2 dimensions and plot the results. Colour-code stars versus calaxies. How well do they separate along the principal components?*Hint*: Think about whether you can run PCA on training and test set separately, or whether you need to run it on both together *before* doing the train-test split? ###Code from sklearn.decomposition import PCA # instantiate the PCA object pca = PCA(n_components=2) # fit and transform the samples: X_pca = pca.fit_transform(X) # make a plot object fig, ax = plt.subplots(1, 1, figsize=(12,8)) # loop over number of classes: for i,l in enumerate(np.unique(y)): members = y == l plt.scatter(X_pca[members, 0], X_pca[members, 1], color=sns.color_palette("colorblind",8)[i], label=l) ax.set_xlabel("PCA Component 1") ax.set_ylabel("PCA Component 2") plt.legend() ###Output _____no_output_____ ###Markdown **Exercise 5**: Re-do the classification on the PCA components instead of the original features. ###Code # Train PCA on training data set X_pca_train = pca.fit_transform(X_train) # apply to test set X_pca_test = pca.transform(X_test) # we'll leave the test set for later. # instantiate the random forest classifier: RFmod = RandomForestClassifier() # do a grid search over the free random forest parameters: pars = {"n_estimators": [10, 100, 300], "max_features": [1, 2], "min_samples_leaf": [1,10]} grid_results = GridSearchCV(RandomForestClassifier(), pars, cv = 5) grid_results.fit(X_pca_train, y_train) grid_results.best_score_ ###Output _____no_output_____ ###Markdown **Note**: In general, you should (cross-)validate both your data transformations and your classifiers!But how do we know whether two components was really the right number to choose? perhaps it should have been three? Or four? Ideally, we would like to include the feature engineering in our cross validation procedure. In principle, you can do this by running a complicated for-loop. In practice, this is what `scikit-learn`s [Pipeline](http://scikit-learn.org/stable/modules/pipeline.html) is for! A `Pipeline` object takes a list of tuples of `("string", ScikitLearnObject)` pairs as input and strings them together (your feature vector `X` will be put first through the first object, then the second object and so on sequentially).**Note**: `scikit-learn` distinguishes between *transformers* (i.e. classes that transform the features into something else, like PCA, t-SNE, StandardScaler, ...) and *predictors* (i.e. classes that produce predictions, such as random forests, logistic regression, ...). In a pipeline, all but the last objects must be transformers; the last object can be either.**Exercise 6**: Make a pipeline including (1) a PCA object and (2) a random forest classifier. Cross-validate both the PCA components and the parameters of the random forest classifier. What is the best number of PCA components to use?*Hint*: You can also use the convenience function [`make_pipeline`](http://scikit-learn.org/stable/modules/generated/sklearn.pipeline.make_pipeline.htmlsklearn.pipeline.make_pipeline) to creatue your pipeline. *Hint*: Check the documentation for the precise notation to use for cross-validating parameters. ###Code from sklearn.pipeline import Pipeline # make a list of name-estimator tuples estimators = [('pca', PCA()), ('clf', RandomForestClassifier())] # instantiate the pipeline pipe = Pipeline(estimators) # make a dictionary of parameters params = dict(pca__n_components=[2, 4, 6, 8], clf__n_estimators=[10, 100, 300], clf__min_samples_leaf=[1,10]) # perform the grid search grid_search = GridSearchCV(pipe, param_grid=params) grid_search.fit(X_train, y_train) print(grid_search.best_score_) print(grid_search.best_params_) ###Output 0.970571428571 {'pca__n_components': 6, 'clf__min_samples_leaf': 1, 'clf__n_estimators': 300} ###Markdown It looks like `n_components=6` works best. Comparing AlgorithmsSo far, we've just picked PCA because it's common. But what if there's a better algorithm for dimensionality reduction out there for our problem? Or what if you'd want to compare random forests to other classifiers? In this case, your best option is to split off a separate validation set, perform cross-validation for each algorithm separately, and then compare the results using hold-out cross validation and your validation set (**Note**: Do *not* use your test set for this! Your test set is *only* used for your final error estimate!)Doing CV across algorithms is difficult, since the `KFoldCV` object needs to know which parameters belong to which algorithms, which is difficult to do. **Exercise 7**: Pick an algorithm from the [manifold learning](http://scikit-learn.org/stable/modules/manifold.htmlmanifold) library in `scikit-learn`, cross-validate a random forest for both, and compare the performance of both.**Important**: Do *not* choose t-SNE. The reason is that t-SNE does not generalize to new samples! This means while it's useful for data visualization, you cannot train a t-SNE transformation (in the `scikit-learn` implementation) on one part of your data and apply it to another! ###Code # First, let's redo the train-test split to split the training data # into training and hold-out validation set X_train_new, X_val, y_train_new, y_val = train_test_split(X_train, y_train, test_size = 0.2, random_state = rs) # Now we have to re-do the PCA pipeline: from sklearn.pipeline import Pipeline # make a list of name-estimator tuples estimators = [('pca', PCA()), ('clf', RandomForestClassifier())] # instantiate the pipeline pipe = Pipeline(estimators) # make a dictionary of parameters params = dict(pca__n_components=[2, 4, 6, 8], clf__n_estimators=[10, 100, 300], clf__min_samples_leaf=[1,10]) # perform the grid search grid_search = GridSearchCV(pipe, param_grid=params) grid_search.fit(X_train_new, y_train_new) print("Best score: " + str(grid_search.best_score_)) print("Best parameter set: " + str(grid_search.best_params_)) print("Validation score for model with PCA: " + str(grid_search.score(X_val, y_val))) # I'm going to pick locally linear embedding here: # LLE has two free parameters: # - the number of parameters to use `n_neighbors` # - the number of components in the output from sklearn.manifold import LocallyLinearEmbedding from sklearn.pipeline import Pipeline # make a list of name-estimator tuples estimators = [('lle', LocallyLinearEmbedding()), ('clf', RandomForestClassifier())] # instantiate the pipeline pipe2 = Pipeline(estimators) # make a dictionary of parameters params = dict(lle__n_components=[2, 4, 6, 8], lle__n_neighbors=[5, 10, 100], clf__n_estimators=[10, 100, 300], clf__min_samples_leaf=[1,10]) # perform the grid search grid_search2 = GridSearchCV(pipe2, param_grid=params) grid_search2.fit(X_train_new, y_train_new) print("Best score: " + str(grid_search2.best_score_)) print("Best parameter set: " + str(grid_search2.best_params_)) print("Validation score for model with LLE: " + str(grid_search2.score(X_val, y_val))) ###Output Best score: 0.971607142857 Best parameter set: {'pca__n_components': 4, 'clf__min_samples_leaf': 1, 'clf__n_estimators': 100} Validation score for model with PCA: 0.961428571429 Best score: 0.971428571429 Best parameter set: {'lle__n_components': 4, 'clf__min_samples_leaf': 10, 'clf__n_estimators': 10, 'lle__n_neighbors': 100} Validation score for model with PCA: 0.957142857143 ###Markdown Looks like PCA does slightly better as a dimensionality reduction method. Challenge Problem: Interpreting ResultsEarlier today, we talked about interpreting machine learning models. Let's see how you would go about this in practice.* Repeat your classification with a logistic regression model.* Is the logistic regression model easier or harder to interpret? Why?* Assume you're interested in which features are the most relevant to your classification (because they might have some bearing on the underlying physics). Would you do your classification on the original features or the PCA transformation? Why?* Change the subset of parameters used in the logistic regression models. Look at the weights. Do they change? How? Does that affect your interpretability? ###Code from sklearn.linear_model import LogisticRegressionCV lr = LogisticRegressionCV(penalty="l2", Cs=10, cv=10) lr.fit(X_train, y_train) lr.coef_ ###Output _____no_output_____ ###Markdown **Answer 1**: Whether the model is easier or harder to interpret depends on what type of interpretability is desired. If you are interested in how the **features** influence the classification, the logistic regression model is easier to interpret: because random forests is an ensemble method, it's very hard to understand in detail how a prediction comes about (since the individual decision trees may have very different structures). However, for very large feature spaces with complicated, engineered features, your linear model (the logistic regression model) loses interpretability in how the parameters affect the outcomes just as much.**Answer 2**: The more feature engineering you do, the harder it will be to interpret the results. The PCA features are a linear transformation of your original eight features. But what do they mean in physical terms? Who knows? ###Code # let's leave out the first parameter and see whether the coefficients change: lr.fit(X_train[:,1:], y_train) lr.coef_ ###Output _____no_output_____ ###Markdown **Answer 3**: Some of the coefficients just changed sign! This is one of the problems with directly interpreting linear models: they are quite sensitive to the structure of the feature space. If you took these parameters and interpreted them in a causal sense, you might get completely different causal inferences depending on which parameters you use so be careful to check how robust your model is to changes in the feature space! Even More Challenging Challenge Problem: Implementing Your Own EstimatorSometimes, you might want to use algorithms, for example for feature engineering, that are not implemented in scikit-learn. But perhaps these transformations still have free parameters to estimate. What to do? `scikit-learn` classes inherit from certain base classes that make it easy to implement your own objects. Below is an example I wrote for a machine learning model on time series, where I wanted to re-bin the time series in different ways and and optimize the rebinning factor with respect to the classification afterwards. ###Code from sklearn.base import BaseEstimator, TransformerMixin class RebinTimeseries(BaseEstimator, TransformerMixin): def __init__(self, n=4, method="average"): """ Initialize hyperparameters :param n: number of samples to bin :param method: "average" or "sum" the samples within a bin? :return: """ self.n = n ## save number of bins to average together self.method = method return def fit(self,X): """ I don't really need a fit method! """ ## set number of light curves (L) and ## number of samples per light curve (k) return self def transform(self, X): self.L, self.K = X.shape ## set the number of binned samples per light curve K_binned = int(self.K/self.n) ## if the number of samples in the original light curve ## is not divisible by n, then chop off the last few samples of ## the light curve to make it divisible #print("X shape: " + str(X.shape)) if K_binned*self.n < self.K: X = X[:,:self.n*K_binned] ## the array for the new, binned light curves X_binned = np.zeros((self.L, K_binned)) if self.method in ["average", "mean"]: method = np.mean elif self.method == "sum": method = np.sum else: raise Exception("Method not recognized!") #print("X shape: " + str(X.shape)) #print("L: " + str(self.L)) for i in xrange(self.L): t_reshape = X[i,:].reshape((K_binned, self.n)) X_binned[i,:] = method(t_reshape, axis=1) return X_binned def predict(self, X): pass def score(self, X): pass def fit_transform(self, X, y=None): self.fit(X) X_binned = self.transform(X) return X_binned ###Output _____no_output_____ ###Markdown Here are the important things about writing transformer objects for use in scikit-learn:* The class must have the following methods: - `fit`: fit your training data - `transform`: transform your training data into the new representation - `predict`: predict new examples - `score`: score predictions - `fit_transform` is optional (I think)* The `__init__` method *only* sets up parameters. Don't put any relevant code in there (this is convention more than anything else, but it's a good one to follow!)* The `fit` method is always called in a `Pipeline` object (either on its own or as part of `fit_transform`). It usually modifies the internal state of the object, so returning `self` (i.e. the object itself) is usually fine.* For transformer objects, which don't need scoring and prediction methods, you can just return `pass` as above.**Exercise 8**: Last time, you learned that the SDSS photometric classifier uses a single hard cut to separate stars and galaxies in imaging data:$$\mathtt{psfMag} - \mathtt{cmodelMag} \gt 0.145,$$sources that satisfy this criteria are considered galaxies.* Implement an object that takes $\mathtt{psfMag}$ and $\mathtt{cmodelMag}$ as inputs and has a free parameter `s` that sets the value above which a source is considered a galaxy. * Implement a `transform` methods that returns a single binary feature that is one if $$\mathtt{psfMag} - \mathtt{cmodelMag} \gt p$$ and zero otherwise. * Add this feature to your optimized set of features consisting of either the PCA or your alternative representation, and run a random forest classifier on both. Run a CV on all components involved.*Hint*: $\mathtt{psfMag}$ and $\mathtt{cmodelMag}$ are the first and the last column in your feature vector, respectively.*Hint*: You can use [`FeatureUnion`](http://scikit-learn.org/stable/modules/generated/sklearn.pipeline.FeatureUnion.htmlsklearn.pipeline.FeatureUnion) to combine the outputs of two transformers in a single data set. (Note that using pipeline with all three will *chain* them, rather than compute the feature union, followed by a classifier). You can input your `FeatureUnion` object into `Pipeline`. ###Code class PSFMagThreshold(BaseEstimator, TransformerMixin): def __init__(self, p=1.45,): """ Initialize hyperparameters Parameters ---------- p : float The threshold for the magnitude - model magnitude """ self.p = p # store parameter in object return def fit(self,X): """ I don't really need a fit method! """ return self def transform(self, X): # extract relevant columns psfmag = X[:,0] c_psfmag = X[:,-1] # compute difference d_psfmag = psfmag - c_psfmag # make a 1D array of length N X_new = np.zeros(X.shape[0]) X_new[d_psfmag > self.p] = 1.0 # IMPORTANT: Your output vector must be a COLUMN vector # You can achieve this with the numpy function atleast_2D() # and the numpy function transpose() return np.atleast_2d(X_new).T def predict(self, X): pass def score(self, X): pass def fit_transform(self, X, y=None): self.fit(X) X_new = self.transform(X) return X_new pt = PSFMagThreshold(p=1.45) X_pt = pt.fit_transform(X) ###Output _____no_output_____ ###Markdown Now let's make a feature set that combines this feature with the PCA features: ###Code from sklearn.pipeline import FeatureUnion transformers = [("pca", PCA(n_components=2)), ("pt", PSFMagThreshold(p=1.45))] feat_union = FeatureUnion(transformers) X_transformed = feat_union.fit_transform(X_train) ###Output _____no_output_____ ###Markdown Now we can build the pipeline: ###Code # combine the transformers = [("pca", PCA()), ("pt", PSFMagThreshold(p=1.45))] feat_union = FeatureUnion(transformers) estimators = [("feats", feat_union), ("clf", RandomForestClassifier())] pipe_c = Pipeline(estimators) # make the parameter set params = dict(feats__pca__n_components=[2, 4, 6, 8], feats__pt__p=[0.5, 0.9, 1.45, 2.0], clf__n_estimators=[10, 100, 300], clf__min_samples_leaf=[1,10]) # perform the grid search grid_search_c = GridSearchCV(pipe_c, param_grid=params) grid_search_c.fit(X_train_new, y_train_new) # print validation score print("Best score: " + str(grid_search_c.best_score_)) print("Best parameter set: " + str(grid_search_c.best_params_)) print("Validation score: " + str(grid_search_c.score(X_val, y_val))) ###Output Best score: 0.9725 Best parameter set: {'feats__pca__n_components': 4, 'clf__min_samples_leaf': 1, 'clf__n_estimators': 100, 'feats__pt__p': 0.5} Validation score: 0.961428571429 ###Markdown Choosing The Right Scoring FunctionAs a standard, the algorithms in `scikit-learn` use `accuracy` to score results. The accuracy is basically the raw fraction of correctly classified samples in your validation or test set. **Question**: Is this scoring function always the best method to use? Why (not)? Can you think of alternatives to use?Let's make a heavily biased data set: ###Code # all stars star_ind = np.argwhere(y == b"STAR").T[0] # all galaxies galaxy_ind = np.argwhere(y == b"GALAXY").T[0] np.random.seed(100) # new array with much fewer stars star_ind_new = np.random.choice(star_ind, replace=False, size=int(len(star_ind)/80.0)) X_new = np.vstack((X[galaxy_ind], X[star_ind_new])) y_new = np.hstack((y[galaxy_ind], y[star_ind_new])) ###Output _____no_output_____ ###Markdown We have now made a really imbalanced data set with many galaxies and only a few stars: ###Code print(len(y_new[y_new == b"GALAXY"])) print(len(y_new[y_new == b"STAR"])) ###Output 4652 66 ###Markdown **Exercise 10**: Run a logistic regression classifier on this data, for a very low regularization (0.0001) and a very large regularization (10000) parameter. Print the accuracy and a confusion matrix of the results for each run. How many mis-classified samples are in each? Where do the mis-classifications end up? If you were to run a cross validation on this, could you be sure to get a good model? Why (not)?*Hint*: Our imbalanced class, the one we're interested in, is the ###Code from sklearn.linear_model import LogisticRegression from sklearn.metrics import confusion_matrix, accuracy_score X_train2, X_test2, y_train2, y_test2 = train_test_split(X_new, y_new, test_size = 0.3, random_state = 20) C_all = [0.0001, 10000] for C in C_all: lr = LogisticRegression(penalty='l2', C=C) lr.fit(X_train2, y_train2) y_pred = lr.predict(X_test2) print("The accuracy score for C = %i is %.4f"%(C, accuracy_score(y_test2, y_pred))) cm = confusion_matrix(y_test2, y_pred, labels=np.unique(y)) print(cm) ###Output The accuracy score for C = 0 is 0.9866 [[1397 0] [ 19 0]] The accuracy score for C = 10000 is 0.9859 [[1392 5] [ 15 4]] ###Markdown **Exercise 11**: Take a look at the [metrics](http://scikit-learn.org/stable/modules/model_evaluation.html) implemented for model evaluation in `scikit-learn`, in particular the different versions of the [F1 score](http://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.htmlsklearn.metrics.f1_score). Is there a metric that may be more suited to the task above? Which one? ###Code for C in C_all: lr = LogisticRegression(penalty='l2', C=C) lr.fit(X_train2, y_train2) y_pred = lr.predict(X_test2) print("The accuracy score for C = %i is %.4f"%(C, accuracy_score(y_test2, y_pred))) print("The F1 score for C = %.5f is %.4f"%(C, f1_score(y_test2, y_pred, pos_label=b"STAR", average="binary"))) cm = confusion_matrix(y_test2, y_pred, labels=np.unique(y)) print(cm) ###Output The accuracy score for C = 0 is 0.9866 The F1 score for C = 0.00010 is 0.0000 [[1397 0] [ 19 0]] The accuracy score for C = 10000 is 0.9859 The F1 score for C = 10000.00000 is 0.2857 [[1392 5] [ 15 4]]
notebook/13t-efficientnet_b3-cutout.ipynb.ipynb
###Markdown GPU ###Code gpu_info = !nvidia-smi gpu_info = '\n'.join(gpu_info) print(gpu_info) ###Output Sun Jan 17 00:43:14 2021 +-----------------------------------------------------------------------------+ | NVIDIA-SMI 460.27.04 Driver Version: 418.67 CUDA Version: 10.1 | |-------------------------------+----------------------+----------------------+ | GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC | | Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. | | | | MIG M. | |===============================+======================+======================| | 0 Tesla T4 Off | 00000000:00:04.0 Off | 0 | | N/A 46C P8 9W / 70W | 0MiB / 15079MiB | 0% Default | | | | ERR! | +-------------------------------+----------------------+----------------------+ +-----------------------------------------------------------------------------+ | Processes: | | GPU GI CI PID Type Process name GPU Memory | | ID ID Usage | |=============================================================================| | No running processes found | +-----------------------------------------------------------------------------+ ###Markdown CFG ###Code CONFIG_NAME = 'config13.yml' from requests import get filename = get('http://172.28.0.2:9000/api/sessions').json()[0]['name'] TITLE = filename.split('.')[0] ! rm -r cassava ! git clone https://github.com/raijin0704/cassava.git # ==================================================== # CFG # ==================================================== import yaml CONFIG_PATH = f'./cassava/config/{CONFIG_NAME}' with open(CONFIG_PATH) as f: config = yaml.load(f) INFO = config['info'] TAG = config['tag'] CFG = config['cfg'] CFG['train'] = True CFG['inference'] = False # CFG['debug'] = True if CFG['debug']: CFG['epochs'] = 1 assert INFO['TITLE'] == TITLE ###Output Cloning into 'cassava'... remote: Enumerating objects: 116, done. remote: Counting objects: 100% (116/116), done. remote: Compressing objects: 100% (109/109), done. remote: Total 116 (delta 78), reused 10 (delta 5), pack-reused 0 Receiving objects: 100% (116/116), 20.25 KiB | 6.75 MiB/s, done. Resolving deltas: 100% (78/78), done. ###Markdown colab & kaggle notebookでの環境面の処理 colab ###Code def _colab_kaggle_authority(): from googleapiclient.discovery import build import io, os from googleapiclient.http import MediaIoBaseDownload drive_service = build('drive', 'v3') results = drive_service.files().list( q="name = 'kaggle.json'", fields="files(id)").execute() kaggle_api_key = results.get('files', []) filename = "/root/.kaggle/kaggle.json" os.makedirs(os.path.dirname(filename), exist_ok=True) request = drive_service.files().get_media(fileId=kaggle_api_key[0]['id']) fh = io.FileIO(filename, 'wb') downloader = MediaIoBaseDownload(fh, request) done = False while done is False: status, done = downloader.next_chunk() print("Download %d%%." % int(status.progress() * 100)) os.chmod(filename, 600) def _install_apex(): import os import subprocess import sys # import time subprocess.run('git clone https://github.com/NVIDIA/apex'.split(' ')) # time.sleep(10) os.chdir('apex') subprocess.run('pip install -v --no-cache-dir --global-option="--cpp_ext" --global-option="--cuda_ext" .'.split(' ')) os.chdir('..') def process_colab(): import subprocess # ドライブのマウント from google.colab import drive drive.mount('/content/drive') # Google Cloudの権限設定 from google.colab import auth auth.authenticate_user() # kaggle設定 # _colab_kaggle_authority() # subprocess.run('pip install --upgrade --force-reinstall --no-deps kaggle'.split(' ')) # ライブラリ関係 subprocess.run('pip install --upgrade opencv-python'.split(' ')) subprocess.run('pip install --upgrade albumentations'.split(' ')) subprocess.run('pip install timm'.split(' ')) # if CFG['apex']: # print('installing apex') # _install_apex() # print('done') # 各種pathの設定 # DATA_PATH = '/content/drive/Shareddrives/便利用/kaggle/cassava/input/' DATA_PATH = '/content/input' OUTPUT_DIR = './output/' NOTEBOOK_PATH = f'/content/drive/Shareddrives/便利用/kaggle/cassava/notebook/{TITLE}.ipynb' return DATA_PATH, OUTPUT_DIR, NOTEBOOK_PATH ###Output _____no_output_____ ###Markdown kaggle notebook ###Code def _kaggle_gcp_authority(): from kaggle_secrets import UserSecretsClient user_secrets = UserSecretsClient() user_credential = user_secrets.get_gcloud_credential() user_secrets.set_tensorflow_credential(user_credential) def process_kaggle(): # GCP設定 _kaggle_gcp_authority() # 各種pathの設定 DATA_PATH = '../input/cassava-leaf-disease-classification/' ! mkdir output OUTPUT_DIR = './output/' NOTEBOOK_PATH = './__notebook__.ipynb' # system path import sys sys.path.append('../input/pytorch-image-models/pytorch-image-models-master') return DATA_PATH, OUTPUT_DIR, NOTEBOOK_PATH ###Output _____no_output_____ ###Markdown 共通 ###Code def process_common(): # ライブラリ関係 import subprocess subprocess.run('pip install mlflow'.split(' ')) # 環境変数 import os os.environ["GCLOUD_PROJECT"] = INFO['PROJECT_ID'] try: from google.colab import auth except ImportError: DATA_PATH, OUTPUT_DIR, NOTEBOOK_PATH = process_kaggle() env = 'kaggle' else: DATA_PATH, OUTPUT_DIR, NOTEBOOK_PATH = process_colab() env = 'colab' finally: process_common() !rm -r /content/input import os if env=='colab': ! cp /content/drive/Shareddrives/便利用/kaggle/cassava/input.zip /content/input.zip ! unzip input.zip ! rm input.zip train_num = len(os.listdir(DATA_PATH+"/train_images")) assert train_num == 21397 ###Output ストリーミング出力は最後の 5000 行に切り捨てられました。 inflating: input/train_images/1137739472.jpg inflating: input/train_images/441313044.jpg inflating: input/train_images/982733151.jpg inflating: input/train_images/3643480526.jpg inflating: input/train_images/2440664696.jpg inflating: input/train_images/370523815.jpg inflating: input/train_images/1125560878.jpg inflating: input/train_images/3303165486.jpg inflating: input/train_images/510873412.jpg inflating: input/train_images/550429661.jpg inflating: input/train_images/1127352598.jpg inflating: input/train_images/3767196717.jpg inflating: input/train_images/25671501.jpg inflating: input/train_images/2296550892.jpg inflating: input/train_images/754482252.jpg inflating: input/train_images/3714169299.jpg inflating: input/train_images/127776052.jpg inflating: input/train_images/3761357668.jpg inflating: input/train_images/996534381.jpg inflating: input/train_images/255701322.jpg inflating: input/train_images/1448397186.jpg inflating: input/train_images/2531944838.jpg inflating: input/train_images/3700174408.jpg inflating: input/train_images/1026177105.jpg inflating: input/train_images/600110842.jpg inflating: input/train_images/3937975751.jpg inflating: input/train_images/3461803618.jpg inflating: input/train_images/1426179564.jpg inflating: input/train_images/1010855776.jpg inflating: input/train_images/1475296121.jpg inflating: input/train_images/3298093070.jpg inflating: input/train_images/1620970351.jpg inflating: input/train_images/1488733138.jpg inflating: input/train_images/1333419699.jpg inflating: input/train_images/360076327.jpg inflating: input/train_images/3009647475.jpg inflating: input/train_images/2234089477.jpg inflating: input/train_images/2609118194.jpg inflating: input/train_images/410890316.jpg inflating: input/train_images/4184062100.jpg inflating: input/train_images/2963247427.jpg inflating: input/train_images/3178512733.jpg inflating: input/train_images/1353797925.jpg inflating: input/train_images/2177911442.jpg inflating: input/train_images/4065072100.jpg inflating: input/train_images/1058428683.jpg inflating: input/train_images/3400218369.jpg inflating: input/train_images/1815863009.jpg inflating: input/train_images/1233926167.jpg inflating: input/train_images/1916594362.jpg inflating: input/train_images/3095137637.jpg inflating: input/train_images/3028047509.jpg inflating: input/train_images/2857325941.jpg inflating: input/train_images/3224710052.jpg inflating: input/train_images/3214705014.jpg inflating: input/train_images/2625055972.jpg inflating: input/train_images/2041267183.jpg inflating: input/train_images/2763501516.jpg inflating: input/train_images/3808267926.jpg inflating: input/train_images/1978570472.jpg inflating: input/train_images/2866106633.jpg inflating: input/train_images/1924914.jpg inflating: input/train_images/607627857.jpg inflating: input/train_images/3815389777.jpg inflating: input/train_images/29157816.jpg inflating: input/train_images/1472883908.jpg inflating: input/train_images/716814677.jpg inflating: input/train_images/1803483476.jpg inflating: input/train_images/514040790.jpg inflating: input/train_images/1559511598.jpg inflating: input/train_images/3791164400.jpg inflating: input/train_images/3612093736.jpg inflating: input/train_images/1899940648.jpg inflating: input/train_images/4017689394.jpg inflating: input/train_images/2628143794.jpg inflating: input/train_images/1960927003.jpg inflating: input/train_images/987080644.jpg inflating: input/train_images/1290734565.jpg inflating: input/train_images/3914399588.jpg inflating: input/train_images/2896221561.jpg inflating: input/train_images/3319706331.jpg inflating: input/train_images/960648391.jpg inflating: input/train_images/2776899438.jpg inflating: input/train_images/1367181542.jpg inflating: input/train_images/634618230.jpg inflating: input/train_images/1093539112.jpg inflating: input/train_images/1757605463.jpg inflating: input/train_images/3727402157.jpg inflating: input/train_images/1331106068.jpg inflating: input/train_images/2569150875.jpg inflating: input/train_images/63578884.jpg inflating: input/train_images/2351347259.jpg inflating: input/train_images/2515648929.jpg inflating: input/train_images/489859226.jpg inflating: input/train_images/1096302814.jpg inflating: input/train_images/1894282232.jpg inflating: input/train_images/3009725992.jpg inflating: input/train_images/4091446019.jpg inflating: input/train_images/4218379987.jpg inflating: input/train_images/721201325.jpg inflating: input/train_images/3164729248.jpg inflating: input/train_images/2190893097.jpg inflating: input/train_images/3451525469.jpg inflating: input/train_images/3014758416.jpg inflating: input/train_images/3540255449.jpg inflating: input/train_images/3048875200.jpg inflating: input/train_images/3158777284.jpg inflating: input/train_images/525960141.jpg inflating: input/train_images/2171124892.jpg inflating: input/train_images/3013885002.jpg inflating: input/train_images/3136739059.jpg inflating: input/train_images/113115280.jpg inflating: input/train_images/3473193669.jpg inflating: input/train_images/149926175.jpg inflating: input/train_images/69869891.jpg inflating: input/train_images/2618549388.jpg inflating: input/train_images/3645775098.jpg inflating: input/train_images/2534943188.jpg inflating: input/train_images/1881585879.jpg inflating: input/train_images/378056459.jpg inflating: input/train_images/1943423929.jpg inflating: input/train_images/2495248330.jpg inflating: input/train_images/2348415590.jpg inflating: input/train_images/1908552116.jpg inflating: input/train_images/1834449995.jpg inflating: input/train_images/3363323405.jpg inflating: input/train_images/1100049957.jpg inflating: input/train_images/4102423093.jpg inflating: input/train_images/3699866059.jpg inflating: input/train_images/4040452479.jpg inflating: input/train_images/27989539.jpg inflating: input/train_images/1998118528.jpg inflating: input/train_images/2446149894.jpg inflating: input/train_images/3446250532.jpg inflating: input/train_images/484161659.jpg inflating: input/train_images/913261951.jpg inflating: input/train_images/469774939.jpg inflating: input/train_images/979088794.jpg inflating: input/train_images/640668148.jpg inflating: input/train_images/2095404633.jpg inflating: input/train_images/744371772.jpg inflating: input/train_images/707347112.jpg inflating: input/train_images/405406521.jpg inflating: input/train_images/1696348486.jpg inflating: input/train_images/1364063429.jpg inflating: input/train_images/2468021699.jpg inflating: input/train_images/3968384941.jpg inflating: input/train_images/621642656.jpg inflating: input/train_images/1935476091.jpg inflating: input/train_images/1850804110.jpg inflating: input/train_images/3106298633.jpg inflating: input/train_images/1224284456.jpg inflating: input/train_images/592236552.jpg inflating: input/train_images/4145595052.jpg inflating: input/train_images/3719586023.jpg inflating: input/train_images/4089978663.jpg inflating: input/train_images/1832863930.jpg inflating: input/train_images/708059328.jpg inflating: input/train_images/2265275376.jpg inflating: input/train_images/2817027058.jpg inflating: input/train_images/36663927.jpg inflating: input/train_images/1524470833.jpg inflating: input/train_images/4075436598.jpg inflating: input/train_images/507089312.jpg inflating: input/train_images/4210825389.jpg inflating: input/train_images/151796855.jpg inflating: input/train_images/3631281208.jpg inflating: input/train_images/1931114133.jpg inflating: input/train_images/2717987423.jpg inflating: input/train_images/595567358.jpg inflating: input/train_images/2424084146.jpg inflating: input/train_images/3105887434.jpg inflating: input/train_images/3619174521.jpg inflating: input/train_images/643613398.jpg inflating: input/train_images/2411688047.jpg inflating: input/train_images/2753146306.jpg inflating: input/train_images/2970713601.jpg inflating: input/train_images/7145099.jpg inflating: input/train_images/217559821.jpg inflating: input/train_images/3117750908.jpg inflating: input/train_images/466809222.jpg inflating: input/train_images/3715474986.jpg inflating: input/train_images/3914861285.jpg inflating: input/train_images/1728159331.jpg inflating: input/train_images/423373963.jpg inflating: input/train_images/58667011.jpg inflating: input/train_images/2412789448.jpg inflating: input/train_images/1220026240.jpg inflating: input/train_images/3191274160.jpg inflating: input/train_images/1837614598.jpg inflating: input/train_images/722430028.jpg inflating: input/train_images/2667091366.jpg inflating: input/train_images/515448717.jpg inflating: input/train_images/4200872179.jpg inflating: input/train_images/951654457.jpg inflating: input/train_images/2708697487.jpg inflating: input/train_images/3081150280.jpg inflating: input/train_images/3490066061.jpg inflating: input/train_images/2588147420.jpg inflating: input/train_images/3988625744.jpg inflating: input/train_images/3203815975.jpg inflating: input/train_images/1295166151.jpg inflating: input/train_images/2209303439.jpg inflating: input/train_images/3973846840.jpg inflating: input/train_images/860380969.jpg inflating: input/train_images/427669101.jpg inflating: input/train_images/2963468821.jpg inflating: input/train_images/980911264.jpg inflating: input/train_images/958551982.jpg inflating: input/train_images/1971179233.jpg inflating: input/train_images/1839467462.jpg inflating: input/train_images/1652379583.jpg inflating: input/train_images/3175363969.jpg inflating: input/train_images/3369678617.jpg inflating: input/train_images/2145478515.jpg inflating: input/train_images/3156981020.jpg inflating: input/train_images/3708133019.jpg inflating: input/train_images/3274661195.jpg inflating: input/train_images/4133329748.jpg inflating: input/train_images/400079356.jpg inflating: input/train_images/2963358758.jpg inflating: input/train_images/3304481536.jpg inflating: input/train_images/95121846.jpg inflating: input/train_images/3589093765.jpg inflating: input/train_images/3482378150.jpg inflating: input/train_images/152558595.jpg inflating: input/train_images/366838317.jpg inflating: input/train_images/3255212212.jpg inflating: input/train_images/2885001903.jpg inflating: input/train_images/2779441922.jpg inflating: input/train_images/827007782.jpg inflating: input/train_images/2124797374.jpg inflating: input/train_images/2056096028.jpg inflating: input/train_images/3784730051.jpg inflating: input/train_images/3045897535.jpg inflating: input/train_images/2123719792.jpg inflating: input/train_images/3674280452.jpg inflating: input/train_images/1194287929.jpg inflating: input/train_images/1489659706.jpg inflating: input/train_images/3758912402.jpg inflating: input/train_images/1022008227.jpg inflating: input/train_images/2052899282.jpg inflating: input/train_images/1501891629.jpg inflating: input/train_images/2508483326.jpg inflating: input/train_images/1466509745.jpg inflating: input/train_images/1250400468.jpg inflating: input/train_images/3567077195.jpg inflating: input/train_images/726377415.jpg inflating: input/train_images/4089766352.jpg inflating: input/train_images/2981404650.jpg inflating: input/train_images/1690276814.jpg inflating: input/train_images/2323359188.jpg inflating: input/train_images/237807134.jpg inflating: input/train_images/4134468341.jpg inflating: input/train_images/1401539761.jpg inflating: input/train_images/579336785.jpg inflating: input/train_images/2321958432.jpg inflating: input/train_images/2481954386.jpg inflating: input/train_images/3653286071.jpg inflating: input/train_images/3192745866.jpg inflating: input/train_images/2690225028.jpg inflating: input/train_images/1678515454.jpg inflating: input/train_images/321774948.jpg inflating: input/train_images/3085864631.jpg inflating: input/train_images/91815905.jpg inflating: input/train_images/1689265715.jpg inflating: input/train_images/1266654234.jpg inflating: input/train_images/840889363.jpg inflating: input/train_images/237348353.jpg inflating: input/train_images/1230729035.jpg inflating: input/train_images/3308221091.jpg inflating: input/train_images/3391710930.jpg inflating: input/train_images/4210262767.jpg inflating: input/train_images/1833189586.jpg inflating: input/train_images/1635220625.jpg inflating: input/train_images/795796251.jpg inflating: input/train_images/296895333.jpg inflating: input/train_images/2868211687.jpg inflating: input/train_images/3251764098.jpg inflating: input/train_images/3997854029.jpg inflating: input/train_images/1379566830.jpg inflating: input/train_images/4254533142.jpg inflating: input/train_images/958879588.jpg inflating: input/train_images/3999057498.jpg inflating: input/train_images/3371952476.jpg inflating: input/train_images/830812751.jpg inflating: input/train_images/2159189425.jpg inflating: input/train_images/1175579707.jpg inflating: input/train_images/3258960112.jpg inflating: input/train_images/4075412353.jpg inflating: input/train_images/1118381273.jpg inflating: input/train_images/285685903.jpg inflating: input/train_images/1569295973.jpg inflating: input/train_images/2238956267.jpg inflating: input/train_images/2877381868.jpg inflating: input/train_images/3937938312.jpg inflating: input/train_images/483199386.jpg inflating: input/train_images/1648069139.jpg inflating: input/train_images/3664608014.jpg inflating: input/train_images/3694686793.jpg inflating: input/train_images/511654743.jpg inflating: input/train_images/2593776626.jpg inflating: input/train_images/3169385678.jpg inflating: input/train_images/2532945082.jpg inflating: input/train_images/3208365182.jpg inflating: input/train_images/3532098475.jpg inflating: input/train_images/3426267905.jpg inflating: input/train_images/3809163419.jpg inflating: input/train_images/2921818611.jpg inflating: input/train_images/1671701546.jpg inflating: input/train_images/4168645136.jpg inflating: input/train_images/336032005.jpg inflating: input/train_images/193173270.jpg inflating: input/train_images/3874600835.jpg inflating: input/train_images/625159901.jpg inflating: input/train_images/96246425.jpg inflating: input/train_images/635511735.jpg inflating: input/train_images/3868235977.jpg inflating: input/train_images/4250554784.jpg inflating: input/train_images/3122760139.jpg inflating: input/train_images/269761139.jpg inflating: input/train_images/3402053246.jpg inflating: input/train_images/328474315.jpg inflating: input/train_images/500317925.jpg inflating: input/train_images/1101262562.jpg inflating: input/train_images/3696122433.jpg inflating: input/train_images/1070151605.jpg inflating: input/train_images/1957341134.jpg inflating: input/train_images/1502339292.jpg inflating: input/train_images/2962131870.jpg inflating: input/train_images/3377872611.jpg inflating: input/train_images/4009415549.jpg inflating: input/train_images/3203913963.jpg inflating: input/train_images/3267041557.jpg inflating: input/train_images/2602649407.jpg inflating: input/train_images/2934273784.jpg inflating: input/train_images/2828195136.jpg inflating: input/train_images/2035935927.jpg inflating: input/train_images/2943837219.jpg inflating: input/train_images/1553303103.jpg inflating: input/train_images/4162370694.jpg inflating: input/train_images/596706595.jpg inflating: input/train_images/1769025995.jpg inflating: input/train_images/1415940915.jpg inflating: input/train_images/3196320591.jpg inflating: input/train_images/3381316827.jpg inflating: input/train_images/1395866975.jpg inflating: input/train_images/2539540333.jpg inflating: input/train_images/3548816902.jpg inflating: input/train_images/758001650.jpg inflating: input/train_images/2543681056.jpg inflating: input/train_images/810720134.jpg inflating: input/train_images/2751784473.jpg inflating: input/train_images/718245684.jpg inflating: input/train_images/3241980938.jpg inflating: input/train_images/622599265.jpg inflating: input/train_images/3127706145.jpg inflating: input/train_images/370935703.jpg inflating: input/train_images/980401006.jpg inflating: input/train_images/4269208386.jpg inflating: input/train_images/3176028684.jpg inflating: input/train_images/3190970408.jpg inflating: input/train_images/3407973340.jpg inflating: input/train_images/3238638493.jpg inflating: input/train_images/2411669233.jpg inflating: input/train_images/2644006691.jpg inflating: input/train_images/4282894767.jpg inflating: input/train_images/1523038784.jpg inflating: input/train_images/4116414929.jpg inflating: input/train_images/2819461837.jpg inflating: input/train_images/289082000.jpg inflating: input/train_images/3687904505.jpg inflating: input/train_images/3635870628.jpg inflating: input/train_images/497624056.jpg inflating: input/train_images/409358481.jpg inflating: input/train_images/3128583938.jpg inflating: input/train_images/1305780999.jpg inflating: input/train_images/1036697361.jpg inflating: input/train_images/1611948994.jpg inflating: input/train_images/3928789907.jpg inflating: input/train_images/2264163141.jpg inflating: input/train_images/744348515.jpg inflating: input/train_images/3971401456.jpg inflating: input/train_images/4197924159.jpg inflating: input/train_images/197102142.jpg inflating: input/train_images/1879473722.jpg inflating: input/train_images/2645759543.jpg inflating: input/train_images/2736151353.jpg inflating: input/train_images/1091450292.jpg inflating: input/train_images/274875938.jpg inflating: input/train_images/1436413250.jpg inflating: input/train_images/227401382.jpg inflating: input/train_images/2555433348.jpg inflating: input/train_images/2980417090.jpg inflating: input/train_images/3875484369.jpg inflating: input/train_images/3825520782.jpg inflating: input/train_images/3194152028.jpg inflating: input/train_images/612426444.jpg inflating: input/train_images/385038415.jpg inflating: input/train_images/4113678968.jpg inflating: input/train_images/2800121117.jpg inflating: input/train_images/3580388018.jpg inflating: input/train_images/3218303848.jpg inflating: input/train_images/1799253944.jpg inflating: input/train_images/636816861.jpg inflating: input/train_images/1521518831.jpg inflating: input/train_images/504400425.jpg inflating: input/train_images/4222936048.jpg inflating: input/train_images/2620149411.jpg inflating: input/train_images/362517802.jpg inflating: input/train_images/1557580898.jpg inflating: input/train_images/287239456.jpg inflating: input/train_images/1094294460.jpg inflating: input/train_images/887146964.jpg inflating: input/train_images/2079122441.jpg inflating: input/train_images/1556262944.jpg inflating: input/train_images/3424618786.jpg inflating: input/train_images/2446013457.jpg inflating: input/train_images/2038601042.jpg inflating: input/train_images/3003520736.jpg inflating: input/train_images/140350208.jpg inflating: input/train_images/100731318.jpg inflating: input/train_images/1311435294.jpg inflating: input/train_images/2290545459.jpg inflating: input/train_images/3255912771.jpg inflating: input/train_images/113596289.jpg inflating: input/train_images/3894758285.jpg inflating: input/train_images/375724523.jpg inflating: input/train_images/1355611441.jpg inflating: input/train_images/1418341223.jpg inflating: input/train_images/860103938.jpg inflating: input/train_images/1657954384.jpg inflating: input/train_images/3205640765.jpg inflating: input/train_images/1368162685.jpg inflating: input/train_images/756009491.jpg inflating: input/train_images/3845529950.jpg inflating: input/train_images/342704060.jpg inflating: input/train_images/3899800621.jpg inflating: input/train_images/339933006.jpg inflating: input/train_images/1082822990.jpg inflating: input/train_images/1493949319.jpg inflating: input/train_images/4246986532.jpg inflating: input/train_images/3943448361.jpg inflating: input/train_images/2396550881.jpg inflating: input/train_images/402280669.jpg inflating: input/train_images/360723691.jpg inflating: input/train_images/570889595.jpg inflating: input/train_images/1873822026.jpg inflating: input/train_images/4124205703.jpg inflating: input/train_images/3717454916.jpg inflating: input/train_images/1549198414.jpg inflating: input/train_images/2926455089.jpg inflating: input/train_images/2279252876.jpg inflating: input/train_images/2966597475.jpg inflating: input/train_images/838106879.jpg inflating: input/train_images/1824287001.jpg inflating: input/train_images/2080103817.jpg inflating: input/train_images/2761443259.jpg inflating: input/train_images/1426902714.jpg inflating: input/train_images/3929739835.jpg inflating: input/train_images/2040710303.jpg inflating: input/train_images/1753621875.jpg inflating: input/train_images/959863341.jpg inflating: input/train_images/4149019611.jpg inflating: input/train_images/2178418518.jpg inflating: input/train_images/1009462599.jpg inflating: input/train_images/2361087670.jpg inflating: input/train_images/2534559127.jpg inflating: input/train_images/2489987245.jpg inflating: input/train_images/2598422574.jpg inflating: input/train_images/1983607439.jpg inflating: input/train_images/1351460531.jpg inflating: input/train_images/3899742169.jpg inflating: input/train_images/618654809.jpg inflating: input/train_images/3386180554.jpg inflating: input/train_images/2048322812.jpg inflating: input/train_images/3994869632.jpg inflating: input/train_images/902300140.jpg inflating: input/train_images/1171170982.jpg inflating: input/train_images/1047272845.jpg inflating: input/train_images/1823946129.jpg inflating: input/train_images/3608399345.jpg inflating: input/train_images/2043193612.jpg inflating: input/train_images/3115512885.jpg inflating: input/train_images/1936058467.jpg inflating: input/train_images/2408092711.jpg inflating: input/train_images/963790461.jpg inflating: input/train_images/3621100767.jpg inflating: input/train_images/1672251151.jpg inflating: input/train_images/3571158096.jpg inflating: input/train_images/1398447903.jpg inflating: input/train_images/2287557968.jpg inflating: input/train_images/1905776137.jpg inflating: input/train_images/3762841948.jpg inflating: input/train_images/2901825019.jpg inflating: input/train_images/2062422141.jpg inflating: input/train_images/3201631268.jpg inflating: input/train_images/3591651493.jpg inflating: input/train_images/301667071.jpg inflating: input/train_images/3738526203.jpg inflating: input/train_images/291050311.jpg inflating: input/train_images/442397332.jpg inflating: input/train_images/2987650848.jpg inflating: input/train_images/3753049842.jpg inflating: input/train_images/1616207760.jpg inflating: input/train_images/2636602591.jpg inflating: input/train_images/1036692910.jpg inflating: input/train_images/4064710747.jpg inflating: input/train_images/3918869320.jpg inflating: input/train_images/2542872391.jpg inflating: input/train_images/2091719066.jpg inflating: input/train_images/2085248098.jpg inflating: input/train_images/1617838083.jpg inflating: input/train_images/2488940657.jpg inflating: input/train_images/165934128.jpg inflating: input/train_images/1286828340.jpg inflating: input/train_images/4119520540.jpg inflating: input/train_images/358823158.jpg inflating: input/train_images/1497417417.jpg inflating: input/train_images/3409314423.jpg inflating: input/train_images/3999758372.jpg inflating: input/train_images/759532134.jpg inflating: input/train_images/2069885945.jpg inflating: input/train_images/3745339060.jpg inflating: input/train_images/2872638305.jpg inflating: input/train_images/2643505151.jpg inflating: input/train_images/3926636513.jpg inflating: input/train_images/1186498322.jpg inflating: input/train_images/2343109986.jpg inflating: input/train_images/2559119042.jpg inflating: input/train_images/1418463220.jpg inflating: input/train_images/2584392391.jpg inflating: input/train_images/3668890746.jpg inflating: input/train_images/2285830070.jpg inflating: input/train_images/3049440979.jpg inflating: input/train_images/1108862699.jpg inflating: input/train_images/3144595150.jpg inflating: input/train_images/3690342005.jpg inflating: input/train_images/4286169099.jpg inflating: input/train_images/2718731433.jpg inflating: input/train_images/591802054.jpg inflating: input/train_images/1351485568.jpg inflating: input/train_images/76382862.jpg inflating: input/train_images/2356134016.jpg inflating: input/train_images/3153277814.jpg inflating: input/train_images/3304610004.jpg inflating: input/train_images/1629406213.jpg inflating: input/train_images/64287317.jpg inflating: input/train_images/2085011211.jpg inflating: input/train_images/1465491965.jpg inflating: input/train_images/1704973107.jpg inflating: input/train_images/1574353431.jpg inflating: input/train_images/2758510429.jpg inflating: input/train_images/2606217713.jpg inflating: input/train_images/1724697986.jpg inflating: input/train_images/3114033989.jpg inflating: input/train_images/2321688265.jpg inflating: input/train_images/1502155213.jpg inflating: input/train_images/2804918430.jpg inflating: input/train_images/1391087542.jpg inflating: input/train_images/3806166801.jpg inflating: input/train_images/4278686402.jpg inflating: input/train_images/2751510981.jpg inflating: input/train_images/396528848.jpg inflating: input/train_images/1534499442.jpg inflating: input/train_images/3535670903.jpg inflating: input/train_images/1133271450.jpg inflating: input/train_images/1499115422.jpg inflating: input/train_images/1866368464.jpg inflating: input/train_images/1463552704.jpg inflating: input/train_images/762558370.jpg inflating: input/train_images/2385678651.jpg inflating: input/train_images/4248695502.jpg inflating: input/train_images/1521850100.jpg inflating: input/train_images/2935458232.jpg inflating: input/train_images/3786378837.jpg inflating: input/train_images/2329535405.jpg inflating: input/train_images/4247400003.jpg inflating: input/train_images/956343434.jpg inflating: input/train_images/2591792455.jpg inflating: input/train_images/865733342.jpg inflating: input/train_images/479659706.jpg inflating: input/train_images/927454705.jpg inflating: input/train_images/1021758544.jpg inflating: input/train_images/1418640499.jpg inflating: input/train_images/3050652741.jpg inflating: input/train_images/1179255874.jpg inflating: input/train_images/1785801012.jpg inflating: input/train_images/434128804.jpg inflating: input/train_images/3369247693.jpg inflating: input/train_images/334288239.jpg inflating: input/train_images/2768458456.jpg inflating: input/train_images/1423993986.jpg inflating: input/train_images/1541217230.jpg inflating: input/train_images/3514164612.jpg inflating: input/train_images/3859819303.jpg inflating: input/train_images/1609127882.jpg inflating: input/train_images/2614282441.jpg inflating: input/train_images/4215606048.jpg inflating: input/train_images/3980819954.jpg inflating: input/train_images/2870340497.jpg inflating: input/train_images/2446621407.jpg inflating: input/train_images/2206925602.jpg inflating: input/train_images/3654524052.jpg inflating: input/train_images/475756576.jpg inflating: input/train_images/1855684239.jpg inflating: input/train_images/1677019415.jpg inflating: input/train_images/3377004222.jpg inflating: input/train_images/2108674538.jpg inflating: input/train_images/4069208912.jpg inflating: input/train_images/340885349.jpg inflating: input/train_images/689108493.jpg inflating: input/train_images/690578148.jpg inflating: input/train_images/4247295410.jpg inflating: input/train_images/2147728293.jpg inflating: input/train_images/330459705.jpg inflating: input/train_images/1835826214.jpg inflating: input/train_images/3564085262.jpg inflating: input/train_images/3304054356.jpg inflating: input/train_images/1855493278.jpg inflating: input/train_images/2112871300.jpg inflating: input/train_images/2190536713.jpg inflating: input/train_images/2917202983.jpg inflating: input/train_images/2473152942.jpg inflating: input/train_images/932990043.jpg inflating: input/train_images/2699152924.jpg inflating: input/train_images/3608836660.jpg inflating: input/train_images/4240281500.jpg inflating: input/train_images/2154958086.jpg inflating: input/train_images/435952255.jpg inflating: input/train_images/340248030.jpg inflating: input/train_images/2282200395.jpg inflating: input/train_images/755073612.jpg inflating: input/train_images/812408252.jpg inflating: input/train_images/2492550594.jpg inflating: input/train_images/292859382.jpg inflating: input/train_images/1710665856.jpg inflating: input/train_images/2148458142.jpg inflating: input/train_images/1858309623.jpg inflating: input/train_images/2443920111.jpg inflating: input/train_images/487175432.jpg inflating: input/train_images/2154826831.jpg inflating: input/train_images/3097661849.jpg inflating: input/train_images/1304731693.jpg inflating: input/train_images/1041588404.jpg inflating: input/train_images/1332894133.jpg inflating: input/train_images/1424184391.jpg inflating: input/train_images/2556137627.jpg inflating: input/train_images/2600531939.jpg inflating: input/train_images/1365114577.jpg inflating: input/train_images/3453865390.jpg inflating: input/train_images/2297731997.jpg inflating: input/train_images/336962626.jpg inflating: input/train_images/1965932647.jpg inflating: input/train_images/3896618890.jpg inflating: input/train_images/350684447.jpg inflating: input/train_images/472839300.jpg inflating: input/train_images/983014273.jpg inflating: input/train_images/2392144549.jpg inflating: input/train_images/2206285676.jpg inflating: input/train_images/1359200021.jpg inflating: input/train_images/1224742642.jpg inflating: input/train_images/3009386931.jpg inflating: input/train_images/2503151412.jpg inflating: input/train_images/2516082759.jpg inflating: input/train_images/1942589536.jpg inflating: input/train_images/3914258603.jpg inflating: input/train_images/1149189284.jpg inflating: input/train_images/3037767592.jpg inflating: input/train_images/2268584645.jpg inflating: input/train_images/2760525879.jpg inflating: input/train_images/3048278043.jpg inflating: input/train_images/1338751464.jpg inflating: input/train_images/1696364421.jpg inflating: input/train_images/1667294993.jpg inflating: input/train_images/3692342611.jpg inflating: input/train_images/4113877744.jpg inflating: input/train_images/3388412714.jpg inflating: input/train_images/3227590908.jpg inflating: input/train_images/3731977760.jpg inflating: input/train_images/3102877932.jpg inflating: input/train_images/1242176689.jpg inflating: input/train_images/3678773878.jpg inflating: input/train_images/4288249349.jpg inflating: input/train_images/2510540586.jpg inflating: input/train_images/1866826606.jpg inflating: input/train_images/435404397.jpg inflating: input/train_images/3904989683.jpg inflating: input/train_images/2325685392.jpg inflating: input/train_images/3926359515.jpg inflating: input/train_images/1933911755.jpg inflating: input/train_images/1129442307.jpg inflating: input/train_images/737753256.jpg inflating: input/train_images/2338213285.jpg inflating: input/train_images/526842311.jpg inflating: input/train_images/719562902.jpg inflating: input/train_images/1890285082.jpg inflating: input/train_images/2761769890.jpg inflating: input/train_images/2635668715.jpg inflating: input/train_images/395071544.jpg inflating: input/train_images/933311576.jpg inflating: input/train_images/1214320013.jpg inflating: input/train_images/1340939411.jpg inflating: input/train_images/4019472268.jpg inflating: input/train_images/3166562991.jpg inflating: input/train_images/3934432993.jpg inflating: input/train_images/907434734.jpg inflating: input/train_images/3977934674.jpg inflating: input/train_images/2010268546.jpg inflating: input/train_images/518284284.jpg inflating: input/train_images/1753499945.jpg inflating: input/train_images/1916496572.jpg inflating: input/train_images/1272495783.jpg inflating: input/train_images/408144068.jpg inflating: input/train_images/3773184372.jpg inflating: input/train_images/3251960666.jpg inflating: input/train_images/605794963.jpg inflating: input/train_images/2491752039.jpg inflating: input/train_images/2157497391.jpg inflating: input/train_images/3525137356.jpg inflating: input/train_images/1428569100.jpg inflating: input/train_images/376083914.jpg inflating: input/train_images/2215986164.jpg inflating: input/train_images/166688569.jpg inflating: input/train_images/1600111988.jpg inflating: input/train_images/2436214521.jpg inflating: input/train_images/1129668095.jpg inflating: input/train_images/3909366564.jpg inflating: input/train_images/2466474683.jpg inflating: input/train_images/571328280.jpg inflating: input/train_images/2757749488.jpg inflating: input/train_images/2733805167.jpg inflating: input/train_images/4007199956.jpg inflating: input/train_images/1239119385.jpg inflating: input/train_images/184462493.jpg inflating: input/train_images/2329257679.jpg inflating: input/train_images/442989383.jpg inflating: input/train_images/136815898.jpg inflating: input/train_images/585209164.jpg inflating: input/train_images/488438522.jpg inflating: input/train_images/987159645.jpg inflating: input/train_images/813509621.jpg inflating: input/train_images/463752462.jpg inflating: input/train_images/2324804154.jpg inflating: input/train_images/1660278504.jpg inflating: input/train_images/2100448540.jpg inflating: input/train_images/410863155.jpg inflating: input/train_images/3598509491.jpg inflating: input/train_images/1067302519.jpg inflating: input/train_images/1245945074.jpg inflating: input/train_images/2928220238.jpg inflating: input/train_images/2998191298.jpg inflating: input/train_images/3717608172.jpg inflating: input/train_images/2194319348.jpg inflating: input/train_images/3269286573.jpg inflating: input/train_images/261186049.jpg inflating: input/train_images/3289401619.jpg inflating: input/train_images/3968048683.jpg inflating: input/train_images/187887606.jpg inflating: input/train_images/1683556923.jpg inflating: input/train_images/1989483426.jpg inflating: input/train_images/549854027.jpg inflating: input/train_images/3244462441.jpg inflating: input/train_images/2276395594.jpg inflating: input/train_images/4156138691.jpg inflating: input/train_images/4044829046.jpg inflating: input/train_images/2377043047.jpg inflating: input/train_images/1145084928.jpg inflating: input/train_images/2554260896.jpg inflating: input/train_images/1424905982.jpg inflating: input/train_images/2178037336.jpg inflating: input/train_images/2318645335.jpg inflating: input/train_images/2297472102.jpg inflating: input/train_images/206432986.jpg inflating: input/train_images/1971427379.jpg inflating: input/train_images/1212460226.jpg inflating: input/train_images/940939729.jpg inflating: input/train_images/972649867.jpg inflating: input/train_images/1912329791.jpg inflating: input/train_images/2115543310.jpg inflating: input/train_images/2544507899.jpg inflating: input/train_images/3478417480.jpg inflating: input/train_images/3564855382.jpg inflating: input/train_images/743850893.jpg inflating: input/train_images/4179630738.jpg inflating: input/train_images/1808921036.jpg inflating: input/train_images/2781831798.jpg inflating: input/train_images/2761141056.jpg inflating: input/train_images/3838540238.jpg inflating: input/train_images/2406694792.jpg inflating: input/train_images/2653833670.jpg inflating: input/train_images/1440401494.jpg inflating: input/train_images/2522202499.jpg inflating: input/train_images/3974455402.jpg inflating: input/train_images/439049574.jpg inflating: input/train_images/3378967649.jpg inflating: input/train_images/1962020298.jpg inflating: input/train_images/2744104425.jpg inflating: input/train_images/2937855140.jpg inflating: input/train_images/3237815335.jpg inflating: input/train_images/4060450564.jpg inflating: input/train_images/847847826.jpg inflating: input/train_images/3741168853.jpg inflating: input/train_images/3444851887.jpg inflating: input/train_images/424246187.jpg inflating: input/train_images/887272418.jpg inflating: input/train_images/1269646820.jpg inflating: input/train_images/3927154512.jpg inflating: input/train_images/227631164.jpg inflating: input/train_images/1096438409.jpg inflating: input/train_images/4130960215.jpg inflating: input/train_images/2589571181.jpg inflating: input/train_images/2936101260.jpg inflating: input/train_images/744968127.jpg inflating: input/train_images/2182855809.jpg inflating: input/train_images/2484471054.jpg inflating: input/train_images/2198789414.jpg inflating: input/train_images/1277679675.jpg inflating: input/train_images/1981710530.jpg inflating: input/train_images/2687625618.jpg inflating: input/train_images/15175683.jpg inflating: input/train_images/1025060651.jpg inflating: input/train_images/147082706.jpg inflating: input/train_images/879360102.jpg inflating: input/train_images/3138454359.jpg inflating: input/train_images/1853237353.jpg inflating: input/train_images/1156963169.jpg inflating: input/train_images/4252058382.jpg inflating: input/train_images/3672574295.jpg inflating: input/train_images/3602124236.jpg inflating: input/train_images/3044653418.jpg inflating: input/train_images/2527606306.jpg inflating: input/train_images/3254091350.jpg inflating: input/train_images/306210288.jpg inflating: input/train_images/336083586.jpg inflating: input/train_images/3570056225.jpg inflating: input/train_images/4281504647.jpg inflating: input/train_images/1974290297.jpg inflating: input/train_images/2587436758.jpg inflating: input/train_images/1017670009.jpg inflating: input/train_images/4290827656.jpg inflating: input/train_images/3814975148.jpg inflating: input/train_images/3704210007.jpg inflating: input/train_images/1398282852.jpg inflating: input/train_images/278898129.jpg inflating: input/train_images/1859307222.jpg inflating: input/train_images/72925791.jpg inflating: input/train_images/806702626.jpg inflating: input/train_images/2509495518.jpg inflating: input/train_images/3529355178.jpg inflating: input/train_images/2497160011.jpg inflating: input/train_images/3649285117.jpg inflating: input/train_images/1675758805.jpg inflating: input/train_images/3889376143.jpg inflating: input/train_images/1811483991.jpg inflating: input/train_images/2935901261.jpg inflating: input/train_images/3156591589.jpg inflating: input/train_images/1136746572.jpg inflating: input/train_images/2801545272.jpg inflating: input/train_images/2590675849.jpg inflating: input/train_images/4091333216.jpg inflating: input/train_images/830380663.jpg inflating: input/train_images/1495222609.jpg inflating: input/train_images/2684560144.jpg inflating: input/train_images/2442826642.jpg inflating: input/train_images/2431603043.jpg inflating: input/train_images/1148219268.jpg inflating: input/train_images/3398807044.jpg inflating: input/train_images/2271308515.jpg inflating: input/train_images/720776367.jpg inflating: input/train_images/2377974845.jpg inflating: input/train_images/3829413649.jpg inflating: input/train_images/3518069486.jpg inflating: input/train_images/1359893940.jpg inflating: input/train_images/3295623672.jpg inflating: input/train_images/3948333262.jpg inflating: input/train_images/472370398.jpg inflating: input/train_images/995221528.jpg inflating: input/train_images/2663709463.jpg inflating: input/train_images/2032736928.jpg inflating: input/train_images/2642446422.jpg inflating: input/train_images/577090506.jpg inflating: input/train_images/208832652.jpg inflating: input/train_images/2377945699.jpg inflating: input/train_images/3870800967.jpg inflating: input/train_images/2807877356.jpg inflating: input/train_images/690565188.jpg inflating: input/train_images/1839152868.jpg inflating: input/train_images/630407730.jpg inflating: input/train_images/2426854829.jpg inflating: input/train_images/3968955392.jpg inflating: input/train_images/105741284.jpg inflating: input/train_images/591335475.jpg inflating: input/train_images/358985142.jpg inflating: input/train_images/2199231317.jpg inflating: input/train_images/667282886.jpg inflating: input/train_images/542560691.jpg inflating: input/train_images/2734892772.jpg inflating: input/train_images/2097195239.jpg inflating: input/train_images/1090116806.jpg inflating: input/train_images/2372500857.jpg inflating: input/train_images/874878736.jpg inflating: input/train_images/3332684410.jpg inflating: input/train_images/2107489867.jpg inflating: input/train_images/1127545108.jpg inflating: input/train_images/3964970132.jpg inflating: input/train_images/986888785.jpg inflating: input/train_images/3419923779.jpg inflating: input/train_images/802266352.jpg inflating: input/train_images/3882109848.jpg inflating: input/train_images/2320107173.jpg inflating: input/train_images/1435727833.jpg inflating: input/train_images/1535887769.jpg inflating: input/train_images/4029027750.jpg inflating: input/train_images/212573449.jpg inflating: input/train_images/2721767282.jpg inflating: input/train_images/3585245374.jpg inflating: input/train_images/2650131569.jpg inflating: input/train_images/1012804587.jpg inflating: input/train_images/1909520119.jpg inflating: input/train_images/1375245484.jpg inflating: input/train_images/1323997328.jpg inflating: input/train_images/1538926850.jpg inflating: input/train_images/52883488.jpg inflating: input/train_images/1758003075.jpg inflating: input/train_images/2342455447.jpg inflating: input/train_images/3058038323.jpg inflating: input/train_images/3625017880.jpg inflating: input/train_images/2278938430.jpg inflating: input/train_images/1351433725.jpg inflating: input/train_images/1553995001.jpg inflating: input/train_images/2936687909.jpg inflating: input/train_images/522209459.jpg inflating: input/train_images/252899909.jpg inflating: input/train_images/3489514020.jpg inflating: input/train_images/206053415.jpg inflating: input/train_images/84024270.jpg inflating: input/train_images/4175172679.jpg inflating: input/train_images/2607316834.jpg inflating: input/train_images/743721638.jpg inflating: input/train_images/3542289007.jpg inflating: input/train_images/955346673.jpg inflating: input/train_images/3221754335.jpg inflating: input/train_images/1135103288.jpg inflating: input/train_images/1364435251.jpg inflating: input/train_images/192970946.jpg inflating: input/train_images/1583439213.jpg inflating: input/train_images/3362457506.jpg inflating: input/train_images/3516286553.jpg inflating: input/train_images/3211556241.jpg inflating: input/train_images/2764717089.jpg inflating: input/train_images/1052881053.jpg inflating: input/train_images/1770197152.jpg inflating: input/train_images/525742373.jpg inflating: input/train_images/1348307468.jpg inflating: input/train_images/2418850424.jpg inflating: input/train_images/663810012.jpg inflating: input/train_images/1558058751.jpg inflating: input/train_images/1405323651.jpg inflating: input/train_images/1785877990.jpg inflating: input/train_images/560888503.jpg inflating: input/train_images/65344468.jpg inflating: input/train_images/1244124878.jpg inflating: input/train_images/781931652.jpg inflating: input/train_images/2091943364.jpg inflating: input/train_images/3031817409.jpg inflating: input/train_images/2066965759.jpg inflating: input/train_images/1403068754.jpg inflating: input/train_images/3501100214.jpg inflating: input/train_images/2473268326.jpg inflating: input/train_images/3992628804.jpg inflating: input/train_images/2170455392.jpg inflating: input/train_images/3038549667.jpg inflating: input/train_images/2491179665.jpg inflating: input/train_images/1211187400.jpg inflating: input/train_images/3909952620.jpg inflating: input/train_images/2445684335.jpg inflating: input/train_images/2847670157.jpg inflating: input/train_images/307148103.jpg inflating: input/train_images/3800475083.jpg inflating: input/train_images/1201690046.jpg inflating: input/train_images/1179237425.jpg inflating: input/train_images/2703475066.jpg inflating: input/train_images/370481129.jpg inflating: input/train_images/1873204876.jpg inflating: input/train_images/1354380890.jpg inflating: input/train_images/1822627582.jpg inflating: input/train_images/2486584885.jpg inflating: input/train_images/1535057791.jpg inflating: input/train_images/4284057693.jpg inflating: input/train_images/3606325619.jpg inflating: input/train_images/3947205646.jpg inflating: input/train_images/1352603733.jpg inflating: input/train_images/2642951848.jpg inflating: input/train_images/645991519.jpg inflating: input/train_images/1101409116.jpg inflating: input/train_images/1995180992.jpg inflating: input/train_images/4149439273.jpg inflating: input/train_images/1086549590.jpg inflating: input/train_images/2428748411.jpg inflating: input/train_images/3493232417.jpg inflating: input/train_images/1581083088.jpg inflating: input/train_images/2410206880.jpg inflating: input/train_images/2178737885.jpg inflating: input/train_images/3189838386.jpg inflating: input/train_images/466665230.jpg inflating: input/train_images/4111579304.jpg inflating: input/train_images/2757717680.jpg inflating: input/train_images/634724499.jpg inflating: input/train_images/3219226576.jpg inflating: input/train_images/747761920.jpg inflating: input/train_images/2275462714.jpg inflating: input/train_images/335204978.jpg inflating: input/train_images/1024067372.jpg inflating: input/train_images/2396049466.jpg inflating: input/train_images/3688162570.jpg inflating: input/train_images/1201158169.jpg inflating: input/train_images/785251696.jpg inflating: input/train_images/4212381540.jpg inflating: input/train_images/3909502094.jpg inflating: input/train_images/1963744346.jpg inflating: input/train_images/4205544766.jpg inflating: input/train_images/368507715.jpg inflating: input/train_images/2797119560.jpg inflating: input/train_images/1557398186.jpg inflating: input/train_images/2820350.jpg inflating: input/train_images/3339979490.jpg inflating: input/train_images/1445721278.jpg inflating: input/train_images/1782735402.jpg inflating: input/train_images/2768992642.jpg inflating: input/train_images/3174117407.jpg inflating: input/train_images/2850943526.jpg inflating: input/train_images/3058839740.jpg inflating: input/train_images/1775924817.jpg inflating: input/train_images/3788064831.jpg inflating: input/train_images/1979663030.jpg inflating: input/train_images/1829820794.jpg inflating: input/train_images/2932123995.jpg inflating: input/train_images/866496354.jpg inflating: input/train_images/2783143835.jpg inflating: input/train_images/338055646.jpg inflating: input/train_images/936438569.jpg inflating: input/train_images/460888118.jpg inflating: input/train_images/2806775485.jpg inflating: input/train_images/4037829966.jpg inflating: input/train_images/3205038032.jpg inflating: input/train_images/3381060071.jpg inflating: input/train_images/2662418280.jpg inflating: input/train_images/1685008458.jpg inflating: input/train_images/4265846658.jpg inflating: input/train_images/414229694.jpg inflating: input/train_images/2111097529.jpg inflating: input/train_images/3645245816.jpg inflating: input/train_images/4010091989.jpg inflating: input/train_images/1518858149.jpg inflating: input/train_images/1993626674.jpg inflating: input/train_images/51063556.jpg inflating: input/train_images/4049843068.jpg inflating: input/train_images/2175002388.jpg inflating: input/train_images/3250432393.jpg inflating: input/train_images/3904531265.jpg inflating: input/train_images/3660846961.jpg inflating: input/train_images/1602453903.jpg inflating: input/train_images/1285287595.jpg inflating: input/train_images/1496786758.jpg inflating: input/train_images/2348020586.jpg inflating: input/train_images/3001133912.jpg inflating: input/train_images/2249767695.jpg inflating: input/train_images/1776919078.jpg inflating: input/train_images/175816110.jpg inflating: input/train_images/24632378.jpg inflating: input/train_images/3778551901.jpg inflating: input/train_images/2457010245.jpg inflating: input/train_images/3057848148.jpg inflating: input/train_images/867025399.jpg inflating: input/train_images/1823796412.jpg inflating: input/train_images/1290043327.jpg inflating: input/train_images/3949530220.jpg inflating: input/train_images/2424770024.jpg inflating: input/train_images/3537938630.jpg inflating: input/train_images/2615629258.jpg inflating: input/train_images/3053608144.jpg inflating: input/train_images/2458565094.jpg inflating: input/train_images/1434278080.jpg inflating: input/train_images/4180192243.jpg inflating: input/train_images/2349165022.jpg inflating: input/train_images/4099004871.jpg inflating: input/train_images/323293221.jpg inflating: input/train_images/334748709.jpg inflating: input/train_images/2265305065.jpg inflating: input/train_images/2511157697.jpg inflating: input/train_images/2681562878.jpg inflating: input/train_images/2326806135.jpg inflating: input/train_images/1380110739.jpg inflating: input/train_images/1110421964.jpg inflating: input/train_images/1059986462.jpg inflating: input/train_images/3743195625.jpg inflating: input/train_images/1001320321.jpg inflating: input/train_images/1234375577.jpg inflating: input/train_images/2553757426.jpg inflating: input/train_images/554189180.jpg inflating: input/train_images/3628996963.jpg inflating: input/train_images/1445369057.jpg inflating: input/train_images/2363265177.jpg inflating: input/train_images/1098184586.jpg inflating: input/train_images/1351337979.jpg inflating: input/train_images/2659141611.jpg inflating: input/train_images/3920121408.jpg inflating: input/train_images/2447086641.jpg inflating: input/train_images/137038681.jpg inflating: input/train_images/130685384.jpg inflating: input/train_images/4182626844.jpg inflating: input/train_images/2705031352.jpg inflating: input/train_images/2583781568.jpg inflating: input/train_images/98151706.jpg inflating: input/train_images/1902806995.jpg inflating: input/train_images/3760730104.jpg inflating: input/train_images/3504669411.jpg inflating: input/train_images/641947553.jpg inflating: input/train_images/4056070889.jpg inflating: input/train_images/2903629810.jpg inflating: input/train_images/1450741896.jpg inflating: input/train_images/1837284696.jpg inflating: input/train_images/3114522519.jpg inflating: input/train_images/3272750945.jpg inflating: input/train_images/1659403875.jpg inflating: input/train_images/2904671058.jpg inflating: input/train_images/3993617081.jpg inflating: input/train_images/1047894047.jpg inflating: input/train_images/1178307457.jpg inflating: input/train_images/489369440.jpg inflating: input/train_images/2344592304.jpg inflating: input/train_images/422632532.jpg inflating: input/train_images/2021239499.jpg inflating: input/train_images/1268162819.jpg inflating: input/train_images/2254310915.jpg inflating: input/train_images/737157935.jpg inflating: input/train_images/2473286391.jpg inflating: input/train_images/2952187496.jpg inflating: input/train_images/2859464940.jpg inflating: input/train_images/1991065222.jpg inflating: input/train_images/748154559.jpg inflating: input/train_images/2077965062.jpg inflating: input/train_images/15383908.jpg inflating: input/train_images/1637611911.jpg inflating: input/train_images/1456881000.jpg inflating: input/train_images/3889601162.jpg inflating: input/train_images/107458529.jpg inflating: input/train_images/726108789.jpg inflating: input/train_images/2978135052.jpg inflating: input/train_images/3467700084.jpg inflating: input/train_images/1558263812.jpg inflating: input/train_images/2009674442.jpg inflating: input/train_images/1079107547.jpg inflating: input/train_images/2722340963.jpg inflating: input/train_images/2469652661.jpg inflating: input/train_images/219505342.jpg inflating: input/train_images/2091547987.jpg inflating: input/train_images/3119699604.jpg inflating: input/train_images/1016415263.jpg inflating: input/train_images/1286002720.jpg inflating: input/train_images/745112623.jpg inflating: input/train_images/1251319553.jpg inflating: input/train_images/2080055302.jpg inflating: input/train_images/4084600785.jpg inflating: input/train_images/146247693.jpg inflating: input/train_images/214207820.jpg inflating: input/train_images/1899678596.jpg inflating: input/train_images/3718347785.jpg inflating: input/train_images/3735709482.jpg inflating: input/train_images/2401581385.jpg inflating: input/train_images/2338923245.jpg inflating: input/train_images/2969200705.jpg inflating: input/train_images/2888341148.jpg inflating: input/train_images/4282908664.jpg inflating: input/train_images/3443567177.jpg inflating: input/train_images/227245436.jpg inflating: input/train_images/1060214168.jpg inflating: input/train_images/2447025051.jpg inflating: input/train_images/3030726237.jpg inflating: input/train_images/1193388066.jpg inflating: input/train_images/1226905166.jpg inflating: input/train_images/1025466430.jpg inflating: input/train_images/4054194563.jpg inflating: input/train_images/769509727.jpg inflating: input/train_images/446547261.jpg inflating: input/train_images/1551517348.jpg inflating: input/train_images/2754223528.jpg inflating: input/train_images/2765109909.jpg inflating: input/train_images/714060321.jpg inflating: input/train_images/1007700625.jpg inflating: input/train_images/2059180039.jpg inflating: input/train_images/4213471018.jpg inflating: input/train_images/3934403227.jpg inflating: input/train_images/3241444808.jpg inflating: input/train_images/1751949402.jpg inflating: input/train_images/3833349143.jpg inflating: input/train_images/1747286543.jpg inflating: input/train_images/587829607.jpg inflating: input/train_images/287967918.jpg inflating: input/train_images/1315703561.jpg inflating: input/train_images/3438538629.jpg inflating: input/train_images/3848359159.jpg inflating: input/train_images/1624580117.jpg inflating: input/train_images/3357188995.jpg inflating: input/train_images/4199549961.jpg inflating: input/train_images/359920987.jpg inflating: input/train_images/1970622259.jpg inflating: input/train_images/43727066.jpg inflating: input/train_images/1040876350.jpg inflating: input/train_images/1579937444.jpg inflating: input/train_images/1903746269.jpg inflating: input/train_images/2306385345.jpg inflating: input/train_images/4084470563.jpg inflating: input/train_images/2789524005.jpg inflating: input/train_images/897745173.jpg inflating: input/train_images/2848007232.jpg inflating: input/train_images/339595487.jpg inflating: input/train_images/913436788.jpg inflating: input/train_images/1234294272.jpg inflating: input/train_images/1159573446.jpg inflating: input/train_images/3203849568.jpg inflating: input/train_images/3597887012.jpg inflating: input/train_images/3666469133.jpg inflating: input/train_images/2412773929.jpg inflating: input/train_images/1625527821.jpg inflating: input/train_images/3218262834.jpg inflating: input/train_images/944920581.jpg inflating: input/train_images/822120250.jpg inflating: input/train_images/3395914437.jpg inflating: input/train_images/2323936.jpg inflating: input/train_images/2386253796.jpg inflating: input/train_images/1116229616.jpg inflating: input/train_images/365554294.jpg inflating: input/train_images/546528869.jpg inflating: input/train_images/1452430816.jpg inflating: input/train_images/3645241295.jpg inflating: input/train_images/3506364620.jpg inflating: input/train_images/2557965026.jpg inflating: input/train_images/3853081007.jpg inflating: input/train_images/1658205752.jpg inflating: input/train_images/222568522.jpg inflating: input/train_images/3930678824.jpg inflating: input/train_images/278959446.jpg inflating: input/train_images/2478018732.jpg inflating: input/train_images/1889980641.jpg inflating: input/train_images/1807049681.jpg inflating: input/train_images/490262929.jpg inflating: input/train_images/1363877858.jpg inflating: input/train_images/3829488807.jpg inflating: input/train_images/1427193776.jpg inflating: input/train_images/140387888.jpg inflating: input/train_images/467965750.jpg inflating: input/train_images/3744017930.jpg inflating: input/train_images/1160106089.jpg inflating: input/train_images/372067852.jpg inflating: input/train_images/2992093777.jpg inflating: input/train_images/9548002.jpg inflating: input/train_images/456278844.jpg inflating: input/train_images/1734343224.jpg inflating: input/train_images/2020174786.jpg inflating: input/train_images/1849667123.jpg inflating: input/train_images/3063789590.jpg inflating: input/train_images/1973726786.jpg inflating: input/train_images/602912992.jpg inflating: input/train_images/3793330900.jpg inflating: input/train_images/1037337861.jpg inflating: input/train_images/2427032578.jpg inflating: input/train_images/2466948945.jpg inflating: input/train_images/91285032.jpg inflating: input/train_images/1480404336.jpg inflating: input/train_images/1436106170.jpg inflating: input/train_images/2998271425.jpg inflating: input/train_images/3381014274.jpg inflating: input/train_images/2240905108.jpg inflating: input/train_images/1398249475.jpg inflating: input/train_images/3126169965.jpg inflating: input/train_images/3132897283.jpg inflating: input/train_images/488165307.jpg inflating: input/train_images/3402601721.jpg inflating: input/train_images/4288369732.jpg inflating: input/train_images/1437341132.jpg inflating: input/train_images/1713705590.jpg inflating: input/train_images/1285436512.jpg inflating: input/train_images/2406905705.jpg inflating: input/train_images/2067363667.jpg inflating: input/train_images/2333065966.jpg inflating: input/train_images/4060346776.jpg inflating: input/train_images/3664478040.jpg inflating: input/train_images/3643749616.jpg inflating: input/train_images/2819697442.jpg inflating: input/train_images/2142361151.jpg inflating: input/train_images/3438550828.jpg inflating: input/train_images/99645916.jpg inflating: input/train_images/710791285.jpg inflating: input/train_images/4192503187.jpg inflating: input/train_images/2652514070.jpg inflating: input/train_images/1416607824.jpg inflating: input/train_images/1679630111.jpg inflating: input/train_images/851594010.jpg inflating: input/train_images/2085823072.jpg inflating: input/train_images/2313023027.jpg inflating: input/train_images/1894712729.jpg inflating: input/train_images/3637416250.jpg inflating: input/train_images/972959733.jpg inflating: input/train_images/1532691436.jpg inflating: input/train_images/2865082132.jpg inflating: input/train_images/489343827.jpg inflating: input/train_images/3805200386.jpg inflating: input/train_images/2154740842.jpg inflating: input/train_images/2038191789.jpg inflating: input/train_images/454771505.jpg inflating: input/train_images/1238597078.jpg inflating: input/train_images/675325967.jpg inflating: input/train_images/1198530356.jpg inflating: input/train_images/1417446398.jpg inflating: input/train_images/3987800643.jpg inflating: input/train_images/1147036458.jpg inflating: input/train_images/873205488.jpg inflating: input/train_images/3237097482.jpg inflating: input/train_images/1490907378.jpg inflating: input/train_images/2811772992.jpg inflating: input/train_images/906773049.jpg inflating: input/train_images/243732361.jpg inflating: input/train_images/1480331459.jpg inflating: input/train_images/2911274899.jpg inflating: input/train_images/1550668897.jpg inflating: input/train_images/3458185025.jpg inflating: input/train_images/1202852313.jpg inflating: input/train_images/1896975057.jpg inflating: input/train_images/2090381650.jpg inflating: input/train_images/3171724304.jpg inflating: input/train_images/4243068188.jpg inflating: input/train_images/977709534.jpg inflating: input/train_images/622186063.jpg inflating: input/train_images/1840189288.jpg inflating: input/train_images/3311389928.jpg inflating: input/train_images/2450978537.jpg inflating: input/train_images/3066421395.jpg inflating: input/train_images/3468766688.jpg inflating: input/train_images/686316627.jpg inflating: input/train_images/1500571663.jpg inflating: input/train_images/2398447662.jpg inflating: input/train_images/1926938373.jpg inflating: input/train_images/3735941988.jpg inflating: input/train_images/914090622.jpg inflating: input/train_images/2223402762.jpg inflating: input/train_images/1461335818.jpg inflating: input/train_images/1950825631.jpg inflating: input/train_images/1459667255.jpg inflating: input/train_images/4183847559.jpg inflating: input/train_images/193958679.jpg inflating: input/train_images/3416552356.jpg inflating: input/train_images/3477094015.jpg inflating: input/train_images/683136495.jpg inflating: input/train_images/4168975711.jpg inflating: input/train_images/952303505.jpg inflating: input/train_images/4173960352.jpg inflating: input/train_images/2891633468.jpg inflating: input/train_images/3532319788.jpg inflating: input/train_images/305323841.jpg inflating: input/train_images/4041427827.jpg inflating: input/train_images/2266653294.jpg inflating: input/train_images/1198438913.jpg inflating: input/train_images/2287369071.jpg inflating: input/train_images/1154479394.jpg inflating: input/train_images/384265557.jpg inflating: input/train_images/833082515.jpg inflating: input/train_images/1454074626.jpg inflating: input/train_images/3313811273.jpg inflating: input/train_images/2857145632.jpg inflating: input/train_images/3686283354.jpg inflating: input/train_images/3376933694.jpg inflating: input/train_images/1216982810.jpg inflating: input/train_images/1060543398.jpg inflating: input/train_images/3775506887.jpg inflating: input/train_images/3481431708.jpg inflating: input/train_images/3750069048.jpg inflating: input/train_images/1468414187.jpg inflating: input/train_images/2846400209.jpg inflating: input/train_images/1143548479.jpg inflating: input/train_images/3734410646.jpg inflating: input/train_images/4230970262.jpg inflating: input/train_images/357924077.jpg inflating: input/train_images/1690581200.jpg inflating: input/train_images/1099450301.jpg inflating: input/train_images/3634822711.jpg inflating: input/train_images/2646206273.jpg inflating: input/train_images/1951284903.jpg inflating: input/train_images/2129589240.jpg inflating: input/train_images/3468802020.jpg inflating: input/train_images/3173958806.jpg inflating: input/train_images/1367013120.jpg inflating: input/train_images/1184986094.jpg inflating: input/train_images/3938349285.jpg inflating: input/train_images/3751724682.jpg inflating: input/train_images/186788126.jpg inflating: input/train_images/645203852.jpg inflating: input/train_images/440065824.jpg inflating: input/train_images/2241165356.jpg inflating: input/train_images/2740797987.jpg inflating: input/train_images/4282727554.jpg inflating: input/train_images/704485270.jpg inflating: input/train_images/5511383.jpg inflating: input/train_images/2673087220.jpg inflating: input/train_images/281173602.jpg inflating: input/train_images/2260521441.jpg inflating: input/train_images/1284343377.jpg inflating: input/train_images/3231064987.jpg inflating: input/train_images/427529521.jpg inflating: input/train_images/543499151.jpg inflating: input/train_images/3667636603.jpg inflating: input/train_images/1304015285.jpg inflating: input/train_images/751463025.jpg inflating: input/train_images/3562133791.jpg inflating: input/train_images/2019819944.jpg inflating: input/train_images/3770389028.jpg inflating: input/train_images/2436369739.jpg inflating: input/train_images/296813400.jpg inflating: input/train_images/1520590067.jpg inflating: input/train_images/3483612153.jpg inflating: input/train_images/1929151368.jpg inflating: input/train_images/860926146.jpg inflating: input/train_images/2762258439.jpg inflating: input/train_images/1100677588.jpg inflating: input/train_images/2682587481.jpg inflating: input/train_images/2753152635.jpg inflating: input/train_images/3877043596.jpg inflating: input/train_images/3694251978.jpg inflating: input/train_images/3916184464.jpg inflating: input/train_images/2534822734.jpg inflating: input/train_images/3479436986.jpg inflating: input/train_images/2828604531.jpg inflating: input/train_images/3635783291.jpg inflating: input/train_images/108944327.jpg inflating: input/train_images/2669158036.jpg inflating: input/train_images/972419188.jpg inflating: input/train_images/4109440762.jpg inflating: input/train_images/3199430859.jpg inflating: input/train_images/1742921296.jpg inflating: input/train_images/466394178.jpg inflating: input/train_images/3171101040.jpg inflating: input/train_images/1315280013.jpg inflating: input/train_images/208823391.jpg inflating: input/train_images/1035014017.jpg inflating: input/train_images/3481763546.jpg inflating: input/train_images/3892421662.jpg inflating: input/train_images/454246300.jpg inflating: input/train_images/278030958.jpg inflating: input/train_images/4211828884.jpg inflating: input/train_images/883429890.jpg inflating: input/train_images/1590211674.jpg inflating: input/train_images/932643551.jpg inflating: input/train_images/2787710566.jpg inflating: input/train_images/3456541997.jpg inflating: input/train_images/4173133461.jpg inflating: input/train_images/2869773815.jpg inflating: input/train_images/1913067109.jpg inflating: input/train_images/1352630748.jpg inflating: input/train_images/391259058.jpg inflating: input/train_images/1882080819.jpg inflating: input/train_images/4098383673.jpg inflating: input/train_images/2740053023.jpg inflating: input/train_images/4034547314.jpg inflating: input/train_images/33354579.jpg inflating: input/train_images/1256672551.jpg inflating: input/train_images/1277358374.jpg inflating: input/train_images/4012105605.jpg inflating: input/train_images/1889645110.jpg inflating: input/train_images/1965467529.jpg inflating: input/train_images/1693341190.jpg inflating: input/train_images/148206427.jpg inflating: input/train_images/3299285879.jpg inflating: input/train_images/1797773732.jpg inflating: input/train_images/3413647138.jpg inflating: input/train_images/346540685.jpg inflating: input/train_images/1851497737.jpg inflating: input/train_images/1637819435.jpg inflating: input/train_images/3756317968.jpg inflating: input/train_images/1019366633.jpg inflating: input/train_images/1280298978.jpg inflating: input/train_images/1301053588.jpg inflating: input/train_images/1290024042.jpg inflating: input/train_images/2753540167.jpg inflating: input/train_images/144778428.jpg inflating: input/train_images/1005200906.jpg inflating: input/train_images/219949624.jpg inflating: input/train_images/64732457.jpg inflating: input/train_images/1254294690.jpg inflating: input/train_images/3779645691.jpg inflating: input/train_images/118428727.jpg inflating: input/train_images/441501298.jpg inflating: input/train_images/2868197011.jpg inflating: input/train_images/4111582298.jpg inflating: input/train_images/3345325515.jpg inflating: input/train_images/2115118532.jpg inflating: input/train_images/2490398752.jpg inflating: input/train_images/3671009734.jpg inflating: input/train_images/2511355520.jpg inflating: input/train_images/1875040493.jpg inflating: input/train_images/838734529.jpg inflating: input/train_images/1191019000.jpg inflating: input/train_images/2561181055.jpg inflating: input/train_images/1291552662.jpg inflating: input/train_images/2747276655.jpg inflating: input/train_images/3765800503.jpg inflating: input/train_images/1386339986.jpg inflating: input/train_images/3388533190.jpg inflating: input/train_images/4146743223.jpg inflating: input/train_images/1797305477.jpg inflating: input/train_images/4030129065.jpg inflating: input/train_images/4000198689.jpg inflating: input/train_images/699330995.jpg inflating: input/train_images/3769308751.jpg inflating: input/train_images/4001352115.jpg inflating: input/train_images/3795376798.jpg inflating: input/train_images/3644516431.jpg inflating: input/train_images/3368561907.jpg inflating: input/train_images/2515485322.jpg inflating: input/train_images/2350967286.jpg inflating: input/train_images/966306135.jpg inflating: input/train_images/3784570453.jpg inflating: input/train_images/2174425139.jpg inflating: input/train_images/739320335.jpg inflating: input/train_images/2663655952.jpg inflating: input/train_images/2477858047.jpg inflating: input/train_images/1165503053.jpg inflating: input/train_images/255319476.jpg inflating: input/train_images/4209232605.jpg inflating: input/train_images/709663348.jpg inflating: input/train_images/1061287420.jpg inflating: input/train_images/3772745803.jpg inflating: input/train_images/3193568902.jpg inflating: input/train_images/2680198267.jpg inflating: input/train_images/1539957701.jpg inflating: input/train_images/1666732950.jpg inflating: input/train_images/554118057.jpg inflating: input/train_images/3792024125.jpg inflating: input/train_images/2499785298.jpg inflating: input/train_images/2166936841.jpg inflating: input/train_images/2816524205.jpg inflating: input/train_images/2668114223.jpg inflating: input/train_images/3498150363.jpg inflating: input/train_images/2922394453.jpg inflating: input/train_images/873637313.jpg inflating: input/train_images/1834269542.jpg inflating: input/train_images/1383027450.jpg inflating: input/train_images/3349562972.jpg inflating: input/train_images/2544185952.jpg inflating: input/train_images/137474940.jpg inflating: input/train_images/1998622752.jpg inflating: input/train_images/3035140922.jpg inflating: input/train_images/1182679440.jpg inflating: input/train_images/1910208633.jpg inflating: input/train_images/3082722756.jpg inflating: input/train_images/811732946.jpg inflating: input/train_images/3101248126.jpg inflating: input/train_images/4096774182.jpg inflating: input/train_images/1694570941.jpg inflating: input/train_images/569842713.jpg inflating: input/train_images/3275448678.jpg inflating: input/train_images/708802382.jpg inflating: input/train_images/1712961040.jpg inflating: input/train_images/2269945499.jpg inflating: input/train_images/3061935906.jpg inflating: input/train_images/319553064.jpg inflating: input/train_images/123780103.jpg inflating: input/train_images/3265165430.jpg inflating: input/train_images/2202131582.jpg inflating: input/train_images/2537957417.jpg inflating: input/train_images/278460610.jpg inflating: input/train_images/1966999074.jpg inflating: input/train_images/471647021.jpg inflating: input/train_images/3533779400.jpg inflating: input/train_images/2322601993.jpg inflating: input/train_images/1442310291.jpg inflating: input/train_images/296929664.jpg inflating: input/train_images/3120171714.jpg inflating: input/train_images/1352386013.jpg inflating: input/train_images/423272178.jpg inflating: input/train_images/1637055528.jpg inflating: input/train_images/3806787164.jpg inflating: input/train_images/1520672258.jpg inflating: input/train_images/574000840.jpg inflating: input/train_images/1655898941.jpg inflating: input/train_images/84787134.jpg inflating: input/train_images/1048581072.jpg inflating: input/train_images/4064456640.jpg inflating: input/train_images/2352335642.jpg inflating: input/train_images/3127022829.jpg inflating: input/train_images/1127286868.jpg inflating: input/train_images/2339596137.jpg inflating: input/train_images/348338717.jpg inflating: input/train_images/4183926297.jpg inflating: input/train_images/805519444.jpg inflating: input/train_images/595787428.jpg inflating: input/train_images/1835317288.jpg inflating: input/train_images/3471469388.jpg inflating: input/train_images/3391958379.jpg inflating: input/train_images/3303796327.jpg inflating: input/train_images/1948078849.jpg inflating: input/train_images/764628702.jpg inflating: input/train_images/2808447158.jpg inflating: input/train_images/2900494721.jpg inflating: input/train_images/25169920.jpg inflating: input/train_images/285610834.jpg inflating: input/train_images/2344567219.jpg inflating: input/train_images/632357010.jpg inflating: input/train_images/2705839002.jpg inflating: input/train_images/2620141958.jpg inflating: input/train_images/1077647851.jpg inflating: input/train_images/2815272486.jpg inflating: input/train_images/3271104064.jpg inflating: input/train_images/3966618744.jpg inflating: input/train_images/3453138674.jpg inflating: input/train_images/2794995428.jpg inflating: input/train_images/3330498442.jpg inflating: input/train_images/1411799307.jpg inflating: input/train_images/3795291687.jpg inflating: input/train_images/1620003976.jpg inflating: input/train_images/3670288988.jpg inflating: input/train_images/1656709823.jpg inflating: input/train_images/728084630.jpg inflating: input/train_images/2904271426.jpg inflating: input/train_images/2779488398.jpg inflating: input/train_images/2915436940.jpg inflating: input/train_images/2065453840.jpg inflating: input/train_images/3635315825.jpg inflating: input/train_images/3303116849.jpg inflating: input/train_images/68141141.jpg inflating: input/train_images/333968590.jpg inflating: input/train_images/247720048.jpg inflating: input/train_images/3484015955.jpg inflating: input/train_images/1719831117.jpg inflating: input/train_images/2310639649.jpg inflating: input/train_images/2859716069.jpg inflating: input/train_images/1447330096.jpg inflating: input/train_images/347680492.jpg inflating: input/train_images/2143249620.jpg inflating: input/train_images/2556134164.jpg inflating: input/train_images/2838277856.jpg inflating: input/train_images/2256445671.jpg inflating: input/train_images/2270423003.jpg inflating: input/train_images/3762101778.jpg inflating: input/train_images/2382793101.jpg inflating: input/train_images/2984109922.jpg inflating: input/train_images/2829084377.jpg inflating: input/train_images/3168669941.jpg inflating: input/train_images/194265941.jpg inflating: input/train_images/89450181.jpg inflating: input/train_images/194223136.jpg inflating: input/train_images/2339196209.jpg inflating: input/train_images/387670192.jpg inflating: input/train_images/3739341345.jpg inflating: input/train_images/2908562046.jpg inflating: input/train_images/3731008076.jpg inflating: input/train_images/2140295414.jpg inflating: input/train_images/3862819448.jpg inflating: input/train_images/1637773657.jpg inflating: input/train_images/370235390.jpg inflating: input/train_images/1342351547.jpg inflating: input/train_images/756993867.jpg inflating: input/train_images/343786903.jpg inflating: input/train_images/3956407201.jpg inflating: input/train_images/3213310104.jpg inflating: input/train_images/4024436293.jpg inflating: input/train_images/3637314147.jpg inflating: input/train_images/2078711421.jpg inflating: input/train_images/265078969.jpg inflating: input/train_images/653790605.jpg inflating: input/train_images/2127776934.jpg inflating: input/train_images/715597792.jpg inflating: input/train_images/2505719500.jpg inflating: input/train_images/1589860418.jpg inflating: input/train_images/2510221236.jpg inflating: input/train_images/2088351120.jpg inflating: input/train_images/2462343820.jpg inflating: input/train_images/1903634061.jpg inflating: input/train_images/3504608499.jpg inflating: input/train_images/569345273.jpg inflating: input/train_images/2820596794.jpg inflating: input/train_images/1195706216.jpg inflating: input/train_images/2066754199.jpg inflating: input/train_images/3105818725.jpg inflating: input/train_images/3856210949.jpg inflating: input/train_images/519080705.jpg inflating: input/train_images/3533209606.jpg inflating: input/train_images/1344397550.jpg inflating: input/train_images/2377060677.jpg inflating: input/train_images/4177958446.jpg inflating: input/train_images/3589688329.jpg inflating: input/train_images/2496275543.jpg inflating: input/train_images/2858707596.jpg inflating: input/train_images/3644947505.jpg inflating: input/train_images/3953331047.jpg inflating: input/train_images/2036966083.jpg inflating: input/train_images/2710925690.jpg inflating: input/train_images/4061646597.jpg inflating: input/train_images/4102442898.jpg inflating: input/train_images/779647083.jpg inflating: input/train_images/1166973570.jpg inflating: input/train_images/119785295.jpg inflating: input/train_images/793206643.jpg inflating: input/train_images/4049425598.jpg inflating: input/train_images/473806024.jpg inflating: input/train_images/3871053042.jpg inflating: input/train_images/4256882986.jpg inflating: input/train_images/1618933538.jpg inflating: input/train_images/3927374351.jpg inflating: input/train_images/3510536964.jpg inflating: input/train_images/549591801.jpg inflating: input/train_images/1840408344.jpg inflating: input/train_images/1017890227.jpg inflating: input/train_images/2220363674.jpg inflating: input/train_images/748035819.jpg inflating: input/train_images/3135277056.jpg inflating: input/train_images/847288162.jpg inflating: input/train_images/263932822.jpg inflating: input/train_images/1562342410.jpg inflating: input/train_images/1485335587.jpg inflating: input/train_images/1236840149.jpg inflating: input/train_images/3213974381.jpg inflating: input/train_images/1393783706.jpg inflating: input/train_images/2993551637.jpg inflating: input/train_images/4267819868.jpg inflating: input/train_images/260241921.jpg inflating: input/train_images/2457404086.jpg inflating: input/train_images/2202750916.jpg inflating: input/train_images/3817099479.jpg inflating: input/train_images/1462467319.jpg inflating: input/train_images/4137525990.jpg inflating: input/train_images/2826533790.jpg inflating: input/train_images/2324073630.jpg inflating: input/train_images/762372916.jpg inflating: input/train_images/2448969787.jpg inflating: input/train_images/2944420316.jpg inflating: input/train_images/1150800852.jpg inflating: input/train_images/2873763227.jpg inflating: input/train_images/807322814.jpg inflating: input/train_images/3120878969.jpg inflating: input/train_images/3044677012.jpg inflating: input/train_images/3774494718.jpg inflating: input/train_images/4092211517.jpg inflating: input/train_images/3346966351.jpg inflating: input/train_images/1434474334.jpg inflating: input/train_images/1923898414.jpg inflating: input/train_images/3845401101.jpg inflating: input/train_images/4248003612.jpg inflating: input/train_images/4182987199.jpg inflating: input/train_images/900587637.jpg inflating: input/train_images/768948562.jpg inflating: input/train_images/4091571824.jpg inflating: input/train_images/266070647.jpg inflating: input/train_images/3689465564.jpg inflating: input/train_images/88427493.jpg inflating: input/train_images/1009845426.jpg inflating: input/train_images/3344007463.jpg inflating: input/train_images/1774675464.jpg inflating: input/train_images/2049291369.jpg inflating: input/train_images/16033842.jpg inflating: input/train_images/2318257216.jpg inflating: input/train_images/3315504598.jpg inflating: input/train_images/844432443.jpg inflating: input/train_images/617446207.jpg inflating: input/train_images/2053738846.jpg inflating: input/train_images/266548434.jpg inflating: input/train_images/3604608395.jpg inflating: input/train_images/1145076372.jpg inflating: input/train_images/2051265559.jpg inflating: input/train_images/3198115498.jpg inflating: input/train_images/936942979.jpg inflating: input/train_images/56813625.jpg inflating: input/train_images/3881936041.jpg inflating: input/train_images/470266437.jpg inflating: input/train_images/1788934648.jpg inflating: input/train_images/1776704317.jpg inflating: input/train_images/2312874930.jpg inflating: input/train_images/2716413618.jpg inflating: input/train_images/1773757795.jpg inflating: input/train_images/2731692092.jpg inflating: input/train_images/1028446573.jpg inflating: input/train_images/4127820008.jpg inflating: input/train_images/3369247230.jpg inflating: input/train_images/2933959901.jpg inflating: input/train_images/1951683874.jpg inflating: input/train_images/2035009601.jpg inflating: input/train_images/469514672.jpg inflating: input/train_images/1097202105.jpg inflating: input/train_images/1919668160.jpg inflating: input/train_images/999068805.jpg inflating: input/train_images/2803131903.jpg inflating: input/train_images/4283277874.jpg inflating: input/train_images/3278834779.jpg inflating: input/train_images/3491458662.jpg inflating: input/train_images/4152969433.jpg inflating: input/train_images/262767997.jpg inflating: input/train_images/2865479509.jpg inflating: input/train_images/1284398426.jpg inflating: input/train_images/2927616574.jpg inflating: input/train_images/3515249327.jpg inflating: input/train_images/2289892824.jpg inflating: input/train_images/788479472.jpg inflating: input/train_images/2092002351.jpg inflating: input/train_images/104769172.jpg inflating: input/train_images/3174632328.jpg inflating: input/train_images/2928426348.jpg inflating: input/train_images/522854384.jpg inflating: input/train_images/2588915537.jpg inflating: input/train_images/3750697954.jpg inflating: input/train_images/3324977995.jpg inflating: input/train_images/456963939.jpg inflating: input/train_images/1120933008.jpg inflating: input/train_images/1497437475.jpg inflating: input/train_images/3911564125.jpg inflating: input/train_images/2454175142.jpg inflating: input/train_images/1870627097.jpg inflating: input/train_images/2538957278.jpg inflating: input/train_images/3676798253.jpg inflating: input/train_images/444416814.jpg inflating: input/train_images/4052560823.jpg inflating: input/train_images/3020362387.jpg inflating: input/train_images/16980960.jpg inflating: input/train_images/1761893158.jpg inflating: input/train_images/2638158691.jpg inflating: input/train_images/1391150010.jpg inflating: input/train_images/544530143.jpg inflating: input/train_images/881681381.jpg inflating: input/train_images/3610667873.jpg inflating: input/train_images/437673562.jpg inflating: input/train_images/4282010677.jpg inflating: input/train_images/328706922.jpg inflating: input/train_images/566542293.jpg inflating: input/train_images/194035212.jpg inflating: input/train_images/3981449307.jpg inflating: input/train_images/1952723516.jpg inflating: input/train_images/3816048744.jpg inflating: input/train_images/2914654588.jpg inflating: input/train_images/1947066099.jpg inflating: input/train_images/1325098159.jpg inflating: input/train_images/458083471.jpg inflating: input/train_images/901274607.jpg inflating: input/train_images/3395591441.jpg inflating: input/train_images/4242296013.jpg inflating: input/train_images/1589092032.jpg inflating: input/train_images/177523271.jpg inflating: input/train_images/2665505446.jpg inflating: input/train_images/2745720901.jpg inflating: input/train_images/1711244110.jpg inflating: input/train_images/2763304605.jpg inflating: input/train_images/2143925311.jpg inflating: input/train_images/2535169951.jpg inflating: input/train_images/2152368754.jpg inflating: input/train_images/3115158095.jpg inflating: input/train_images/1731777849.jpg inflating: input/train_images/277811844.jpg inflating: input/train_images/3977320696.jpg inflating: input/train_images/3257812988.jpg inflating: input/train_images/2424570451.jpg inflating: input/train_images/1033283646.jpg inflating: input/train_images/1533215166.jpg inflating: input/train_images/3912926258.jpg inflating: input/train_images/3356448488.jpg inflating: input/train_images/728369192.jpg inflating: input/train_images/1600900862.jpg inflating: input/train_images/2691672185.jpg inflating: input/train_images/3193368098.jpg inflating: input/train_images/1849151787.jpg inflating: input/train_images/4209668687.jpg inflating: input/train_images/1642673136.jpg inflating: input/train_images/4065788460.jpg inflating: input/train_images/2028087473.jpg inflating: input/train_images/3123906243.jpg inflating: input/train_images/2124724718.jpg inflating: input/train_images/4138481373.jpg inflating: input/train_images/631607680.jpg inflating: input/train_images/2589663236.jpg inflating: input/train_images/890004895.jpg inflating: input/train_images/3856935048.jpg inflating: input/train_images/1676416724.jpg inflating: input/train_images/1338159402.jpg inflating: input/train_images/328383026.jpg inflating: input/train_images/1557930579.jpg inflating: input/train_images/2260280582.jpg inflating: input/train_images/326251894.jpg inflating: input/train_images/2411595422.jpg inflating: input/train_images/1052028548.jpg inflating: input/train_images/238134855.jpg inflating: input/train_images/967831491.jpg inflating: input/train_images/2038741619.jpg inflating: input/train_images/443817384.jpg inflating: input/train_images/491341032.jpg inflating: input/train_images/426501539.jpg inflating: input/train_images/1667487311.jpg inflating: input/train_images/724059503.jpg inflating: input/train_images/1434200283.jpg inflating: input/train_images/2941744909.jpg inflating: input/train_images/90333661.jpg inflating: input/train_images/3073813239.jpg inflating: input/train_images/2744352830.jpg inflating: input/train_images/1078779441.jpg inflating: input/train_images/2731257282.jpg inflating: input/train_images/872917593.jpg inflating: input/train_images/2025224084.jpg inflating: input/train_images/3837215772.jpg inflating: input/train_images/1367319512.jpg inflating: input/train_images/1757442303.jpg inflating: input/train_images/1088104223.jpg inflating: input/train_images/2073687427.jpg inflating: input/train_images/3636948632.jpg inflating: input/train_images/451612458.jpg inflating: input/train_images/1029779424.jpg inflating: input/train_images/1469167700.jpg inflating: input/train_images/3377176469.jpg inflating: input/train_images/2763380810.jpg inflating: input/train_images/1823886562.jpg inflating: input/train_images/3984046455.jpg inflating: input/train_images/3598862913.jpg inflating: input/train_images/3992333811.jpg inflating: input/train_images/272796178.jpg inflating: input/train_images/303061561.jpg inflating: input/train_images/1651072461.jpg inflating: input/train_images/1592499949.jpg inflating: input/train_images/2676338923.jpg inflating: input/train_images/3118120871.jpg inflating: input/train_images/1050263382.jpg inflating: input/train_images/280102344.jpg inflating: input/train_images/2328106144.jpg inflating: input/train_images/964482896.jpg inflating: input/train_images/2883462081.jpg inflating: input/train_images/2214549486.jpg inflating: input/train_images/1080179563.jpg inflating: input/train_images/1754481092.jpg inflating: input/train_images/3855303383.jpg inflating: input/train_images/3383545626.jpg inflating: input/train_images/1761634229.jpg inflating: input/train_images/2872140019.jpg inflating: input/train_images/1735911943.jpg inflating: input/train_images/3416705012.jpg inflating: input/train_images/3810809174.jpg inflating: input/train_images/1292034909.jpg inflating: input/train_images/981211210.jpg inflating: input/train_images/2722971247.jpg inflating: input/train_images/1524527135.jpg inflating: input/train_images/2384802478.jpg inflating: input/train_images/133119904.jpg inflating: input/train_images/3612391519.jpg inflating: input/train_images/1509149905.jpg inflating: input/train_images/2314978790.jpg inflating: input/train_images/217699633.jpg inflating: input/train_images/4130557422.jpg inflating: input/train_images/1408250223.jpg inflating: input/train_images/2195289519.jpg inflating: input/train_images/1635358503.jpg inflating: input/train_images/3706939010.jpg inflating: input/train_images/291024116.jpg inflating: input/train_images/3815754295.jpg inflating: input/train_images/2776053424.jpg inflating: input/train_images/1483622893.jpg inflating: input/train_images/354915584.jpg inflating: input/train_images/2220656958.jpg inflating: input/train_images/2490802199.jpg inflating: input/train_images/3480744448.jpg inflating: input/train_images/965026603.jpg inflating: input/train_images/1458457293.jpg inflating: input/train_images/1309857132.jpg inflating: input/train_images/3390815225.jpg inflating: input/train_images/836589560.jpg inflating: input/train_images/2399308727.jpg inflating: input/train_images/1105255922.jpg inflating: input/train_images/1263787016.jpg inflating: input/train_images/2495474828.jpg inflating: input/train_images/2642374600.jpg inflating: input/train_images/3709091678.jpg inflating: input/train_images/486182898.jpg inflating: input/train_images/898753077.jpg inflating: input/train_images/805005298.jpg inflating: input/train_images/87170987.jpg inflating: input/train_images/2425385872.jpg inflating: input/train_images/94882276.jpg inflating: input/train_images/2771194672.jpg inflating: input/train_images/223648042.jpg inflating: input/train_images/2237962396.jpg inflating: input/train_images/2342505190.jpg inflating: input/train_images/1423442291.jpg inflating: input/train_images/3516603497.jpg inflating: input/train_images/347892415.jpg inflating: input/train_images/3054703946.jpg inflating: input/train_images/1866388418.jpg inflating: input/train_images/1938614393.jpg inflating: input/train_images/1117006363.jpg inflating: input/train_images/783533670.jpg inflating: input/train_images/3497832029.jpg inflating: input/train_images/4089661162.jpg inflating: input/train_images/4165290692.jpg inflating: input/train_images/3637370040.jpg inflating: input/train_images/701496880.jpg inflating: input/train_images/2496742167.jpg inflating: input/train_images/1818510196.jpg inflating: input/train_images/1531777334.jpg inflating: input/train_images/2201343641.jpg inflating: input/train_images/3327540813.jpg inflating: input/train_images/1010648150.jpg inflating: input/train_images/3360732633.jpg inflating: input/train_images/2780229634.jpg inflating: input/train_images/2141638054.jpg inflating: input/train_images/435059376.jpg inflating: input/train_images/2217792341.jpg inflating: input/train_images/316988889.jpg inflating: input/train_images/3937810828.jpg inflating: input/train_images/3084656957.jpg inflating: input/train_images/2933784082.jpg inflating: input/train_images/3140588188.jpg inflating: input/train_images/2597005911.jpg inflating: input/train_images/2775889321.jpg inflating: input/train_images/1781932612.jpg inflating: input/train_images/1230982659.jpg inflating: input/train_images/3804966425.jpg inflating: input/train_images/4233314988.jpg inflating: input/train_images/1404393856.jpg inflating: input/train_images/2565638908.jpg inflating: input/train_images/1950600545.jpg inflating: input/train_images/3173423403.jpg inflating: input/train_images/512811593.jpg inflating: input/train_images/1352878479.jpg inflating: input/train_images/282061991.jpg inflating: input/train_images/1700324452.jpg inflating: input/train_images/110588438.jpg inflating: input/train_images/732588563.jpg inflating: input/train_images/1421969879.jpg inflating: input/train_images/1606458459.jpg inflating: input/train_images/1540809571.jpg inflating: input/train_images/2323474464.jpg inflating: input/train_images/3371718731.jpg inflating: input/train_images/3021499033.jpg inflating: input/train_images/3964876844.jpg inflating: input/train_images/1476011675.jpg inflating: input/train_images/2241031313.jpg inflating: input/train_images/2509010515.jpg inflating: input/train_images/2888618344.jpg inflating: input/train_images/3812383679.jpg inflating: input/train_images/1896468303.jpg inflating: input/train_images/190439528.jpg inflating: input/train_images/4003954623.jpg inflating: input/train_images/2156160232.jpg inflating: input/train_images/755729450.jpg inflating: input/train_images/3956075690.jpg inflating: input/train_images/4232654944.jpg inflating: input/train_images/3178167371.jpg inflating: input/train_images/1687247558.jpg inflating: input/train_images/1446406888.jpg inflating: input/train_images/2655340809.jpg inflating: input/train_images/737556184.jpg inflating: input/train_images/1319853450.jpg inflating: input/train_images/1397843043.jpg inflating: input/train_images/817459754.jpg inflating: input/train_images/768729652.jpg inflating: input/train_images/3681935423.jpg inflating: input/train_images/478400081.jpg inflating: input/train_images/1689108113.jpg inflating: input/train_images/3059461197.jpg inflating: input/train_images/196618228.jpg inflating: input/train_images/3172430646.jpg inflating: input/train_images/3626400961.jpg inflating: input/train_images/54600142.jpg inflating: input/train_images/4046154865.jpg inflating: input/train_images/1002394761.jpg inflating: input/train_images/756826989.jpg inflating: input/train_images/1807238206.jpg inflating: input/train_images/553826173.jpg inflating: input/train_images/1456612395.jpg inflating: input/train_images/1845160585.jpg inflating: input/train_images/1094811132.jpg inflating: input/train_images/1653502098.jpg inflating: input/train_images/274723853.jpg inflating: input/train_images/527287896.jpg inflating: input/train_images/2359291077.jpg inflating: input/train_images/705886704.jpg inflating: input/train_images/442164564.jpg inflating: input/train_images/4279471194.jpg inflating: input/train_images/2245464938.jpg inflating: input/train_images/3461945356.jpg inflating: input/train_images/1919914.jpg inflating: input/train_images/3557979582.jpg inflating: input/train_images/456001532.jpg inflating: input/train_images/2321343793.jpg inflating: input/train_images/1528313299.jpg inflating: input/train_images/3838519719.jpg inflating: input/train_images/2330158228.jpg inflating: input/train_images/1643328543.jpg inflating: input/train_images/1685786396.jpg inflating: input/train_images/4144515023.jpg inflating: input/train_images/2727099306.jpg inflating: input/train_images/1927309377.jpg inflating: input/train_images/1473359901.jpg inflating: input/train_images/2193438012.jpg inflating: input/train_images/705789219.jpg inflating: input/train_images/3540543335.jpg inflating: input/train_images/2771179588.jpg inflating: input/train_images/1569385189.jpg inflating: input/train_images/1114918862.jpg inflating: input/train_images/1339614738.jpg inflating: input/train_images/2202498219.jpg inflating: input/train_images/1367959908.jpg inflating: input/train_images/2330997994.jpg inflating: input/train_images/1388871610.jpg inflating: input/train_images/1688398046.jpg inflating: input/train_images/506664858.jpg inflating: input/train_images/1225597955.jpg inflating: input/train_images/222987451.jpg inflating: input/train_images/84635797.jpg inflating: input/train_images/1005739807.jpg inflating: input/train_images/2326873533.jpg inflating: input/train_images/2916689767.jpg inflating: input/train_images/4275645735.jpg inflating: input/train_images/320516441.jpg inflating: input/train_images/1620023854.jpg inflating: input/train_images/2782292505.jpg inflating: input/train_images/2779684221.jpg inflating: input/train_images/616718743.jpg inflating: input/train_images/115829780.jpg inflating: input/train_images/1106608031.jpg inflating: input/train_images/4271963761.jpg inflating: input/train_images/4064049916.jpg inflating: input/train_images/1598187662.jpg inflating: input/train_images/3601015067.jpg inflating: input/train_images/1564717497.jpg inflating: input/train_images/2631757503.jpg inflating: input/train_images/4181351157.jpg inflating: input/train_images/1858613258.jpg inflating: input/train_images/2359855528.jpg inflating: input/train_images/1465359996.jpg inflating: input/train_images/293469170.jpg inflating: input/train_images/2766931963.jpg inflating: input/train_images/3458199144.jpg inflating: input/train_images/1733285805.jpg inflating: input/train_images/4094696582.jpg inflating: input/train_images/608264330.jpg inflating: input/train_images/1880623255.jpg inflating: input/train_images/3773164943.jpg inflating: input/train_images/4011855023.jpg inflating: input/train_images/1138036719.jpg inflating: input/train_images/579333790.jpg inflating: input/train_images/4123656006.jpg inflating: input/train_images/4024636592.jpg inflating: input/train_images/1850235748.jpg inflating: input/train_images/7635457.jpg inflating: input/train_images/2927026832.jpg inflating: input/train_images/747646454.jpg inflating: input/train_images/2225851641.jpg inflating: input/train_images/323035134.jpg inflating: input/train_images/1452755583.jpg inflating: input/train_images/1871382569.jpg inflating: input/train_images/454183787.jpg inflating: input/train_images/3125296469.jpg inflating: input/train_images/846734911.jpg inflating: input/train_images/2115661859.jpg inflating: input/train_images/3852927202.jpg inflating: input/train_images/1344420041.jpg inflating: input/train_images/2175527708.jpg inflating: input/train_images/489562516.jpg inflating: input/train_images/610968546.jpg inflating: input/train_images/2609479763.jpg inflating: input/train_images/3774493586.jpg inflating: input/train_images/674072472.jpg inflating: input/train_images/876588489.jpg inflating: input/train_images/2195653841.jpg inflating: input/train_images/2276075918.jpg inflating: input/train_images/4196953609.jpg inflating: input/train_images/2824711941.jpg inflating: input/train_images/238076770.jpg inflating: input/train_images/1179385123.jpg inflating: input/train_images/3088205156.jpg inflating: input/train_images/451500275.jpg inflating: input/train_images/2358788534.jpg inflating: input/train_images/1890479595.jpg inflating: input/train_images/2472587506.jpg inflating: input/train_images/1172216777.jpg inflating: input/train_images/2097640981.jpg inflating: input/train_images/815952257.jpg inflating: input/train_images/3192117887.jpg inflating: input/train_images/4239262882.jpg inflating: input/train_images/1831712346.jpg inflating: input/train_images/533613162.jpg inflating: input/train_images/3373453090.jpg inflating: input/train_images/1774341872.jpg inflating: input/train_images/3502675900.jpg inflating: input/train_images/3483686543.jpg inflating: input/train_images/2672675899.jpg inflating: input/train_images/1977466275.jpg inflating: input/train_images/1858241102.jpg inflating: input/train_images/670519295.jpg inflating: input/train_images/1306087922.jpg inflating: input/train_images/3461250443.jpg inflating: input/train_images/957970680.jpg inflating: input/train_images/2386536448.jpg inflating: input/train_images/845926406.jpg inflating: input/train_images/2485317187.jpg inflating: input/train_images/2434587882.jpg inflating: input/train_images/1841093794.jpg inflating: input/train_images/2481971712.jpg inflating: input/train_images/2948143920.jpg inflating: input/train_images/1832233045.jpg inflating: input/train_images/1536954784.jpg inflating: input/train_images/3292967761.jpg inflating: input/train_images/2030421746.jpg inflating: input/train_images/2269881726.jpg inflating: input/train_images/3472250799.jpg inflating: input/train_images/4224616597.jpg inflating: input/train_images/1650753377.jpg inflating: input/train_images/26942115.jpg inflating: input/train_images/783577117.jpg inflating: input/train_images/2931187107.jpg inflating: input/train_images/4136137862.jpg inflating: input/train_images/3852956252.jpg inflating: input/train_images/597527186.jpg inflating: input/train_images/3054525360.jpg inflating: input/train_images/2302696132.jpg inflating: input/train_images/3662625055.jpg inflating: input/train_images/4071806046.jpg inflating: input/train_images/1058438877.jpg inflating: input/train_images/1541989559.jpg inflating: input/train_images/3335580523.jpg inflating: input/train_images/3589106075.jpg inflating: input/train_images/270386050.jpg inflating: input/train_images/1958784721.jpg inflating: input/train_images/2174381903.jpg inflating: input/train_images/2425540175.jpg inflating: input/train_images/1292573857.jpg inflating: input/train_images/976801924.jpg inflating: input/train_images/3212562477.jpg inflating: input/train_images/381118833.jpg inflating: input/train_images/4522938.jpg inflating: input/train_images/3003859169.jpg inflating: input/train_images/518891556.jpg inflating: input/train_images/1635619978.jpg inflating: input/train_images/1709443342.jpg inflating: input/train_images/1378444906.jpg inflating: input/train_images/2486212637.jpg inflating: input/train_images/2660643626.jpg inflating: input/train_images/2125666901.jpg inflating: input/train_images/3325640914.jpg inflating: input/train_images/1617179127.jpg inflating: input/train_images/2623830395.jpg inflating: input/train_images/336319648.jpg inflating: input/train_images/3899344477.jpg inflating: input/train_images/4167185859.jpg inflating: input/train_images/1680873912.jpg inflating: input/train_images/3401409874.jpg inflating: input/train_images/3403726678.jpg inflating: input/train_images/3308428199.jpg inflating: input/train_images/165028458.jpg inflating: input/train_images/4124651871.jpg inflating: input/train_images/1152100841.jpg inflating: input/train_images/2448657590.jpg inflating: input/train_images/1812865076.jpg inflating: input/train_images/1695222619.jpg inflating: input/train_images/3449220829.jpg inflating: input/train_images/653958117.jpg inflating: input/train_images/1858722965.jpg inflating: input/train_images/3053713467.jpg inflating: input/train_images/2217598381.jpg inflating: input/train_images/2956539470.jpg inflating: input/train_images/4184461961.jpg inflating: input/train_images/2704051333.jpg inflating: input/train_images/830055343.jpg inflating: input/train_images/2886723600.jpg inflating: input/train_images/78946276.jpg inflating: input/train_images/2320602332.jpg inflating: input/train_images/279831330.jpg inflating: input/train_images/918823473.jpg inflating: input/train_images/3953857113.jpg inflating: input/train_images/1861027492.jpg inflating: input/train_images/2373129151.jpg inflating: input/train_images/3633249375.jpg inflating: input/train_images/1014087087.jpg inflating: input/train_images/1115186514.jpg inflating: input/train_images/1236036550.jpg inflating: input/train_images/2711827024.jpg inflating: input/train_images/1514398511.jpg inflating: input/train_images/3819082104.jpg inflating: input/train_images/82105739.jpg inflating: input/train_images/1349523638.jpg inflating: input/train_images/4177148396.jpg inflating: input/train_images/3644380116.jpg inflating: input/train_images/3699200152.jpg inflating: input/train_images/2674690912.jpg inflating: input/train_images/50223703.jpg inflating: input/train_images/4205256960.jpg inflating: input/train_images/1690647938.jpg inflating: input/train_images/2502748604.jpg inflating: input/train_images/2093487029.jpg inflating: input/train_images/1918288357.jpg inflating: input/train_images/1012305013.jpg inflating: input/train_images/1415036837.jpg inflating: input/train_images/1077343678.jpg inflating: input/train_images/2016298412.jpg inflating: input/train_images/215124252.jpg inflating: input/train_images/1168108889.jpg inflating: input/train_images/3788552221.jpg inflating: input/train_images/1643954108.jpg inflating: input/train_images/3885885091.jpg inflating: input/train_images/843004516.jpg inflating: input/train_images/1190206557.jpg inflating: input/train_images/4288246700.jpg inflating: input/train_images/4013482004.jpg inflating: input/train_images/4173729579.jpg inflating: input/train_images/1465663375.jpg inflating: input/train_images/803715275.jpg inflating: input/train_images/2745895551.jpg inflating: input/train_images/1213570538.jpg inflating: input/train_images/2202135584.jpg inflating: input/train_images/3962941156.jpg inflating: input/train_images/1022850256.jpg inflating: input/train_images/2983992918.jpg inflating: input/train_images/4193627922.jpg inflating: input/train_images/3899499666.jpg inflating: input/train_images/1146811684.jpg inflating: input/train_images/155869794.jpg inflating: input/train_images/4037044151.jpg inflating: input/train_images/1612215855.jpg inflating: input/train_images/1527271851.jpg inflating: input/train_images/3910372860.jpg inflating: input/train_images/2753696681.jpg inflating: input/train_images/3655511142.jpg inflating: input/train_images/226962956.jpg inflating: input/train_images/3647735432.jpg inflating: input/train_images/3791342812.jpg inflating: input/train_images/3072539565.jpg inflating: input/train_images/3365043679.jpg inflating: input/train_images/3052037743.jpg inflating: input/train_images/3164095616.jpg inflating: input/train_images/3331601570.jpg inflating: input/train_images/3044146032.jpg inflating: input/train_images/2454437891.jpg inflating: input/train_images/2238900239.jpg inflating: input/train_images/2993271745.jpg inflating: input/train_images/2110727627.jpg inflating: input/train_images/1176023935.jpg inflating: input/train_images/1760414048.jpg inflating: input/train_images/149376158.jpg inflating: input/train_images/1802754219.jpg inflating: input/train_images/4210199349.jpg inflating: input/train_images/245276230.jpg inflating: input/train_images/2498500935.jpg inflating: input/train_images/4200249723.jpg inflating: input/train_images/2524827545.jpg inflating: input/train_images/1765947311.jpg inflating: input/train_images/292361837.jpg inflating: input/train_images/232064940.jpg inflating: input/train_images/2870914313.jpg inflating: input/train_images/790756634.jpg inflating: input/train_images/65235972.jpg inflating: input/train_images/174674584.jpg inflating: input/train_images/1685873117.jpg inflating: input/train_images/510749381.jpg inflating: input/train_images/1307113448.jpg inflating: input/train_images/3904937505.jpg inflating: input/train_images/2604878350.jpg inflating: input/train_images/2110903174.jpg inflating: input/train_images/2641912037.jpg inflating: input/train_images/2704366062.jpg inflating: input/train_images/1400362797.jpg inflating: input/train_images/2857397632.jpg inflating: input/train_images/2939402823.jpg inflating: input/train_images/2595712013.jpg inflating: input/train_images/933957288.jpg inflating: input/train_images/1550184448.jpg inflating: input/train_images/1658025063.jpg inflating: input/train_images/3524748781.jpg inflating: input/train_images/868625768.jpg inflating: input/train_images/2347718160.jpg inflating: input/train_images/3399701289.jpg inflating: input/train_images/282573788.jpg inflating: input/train_images/3605605369.jpg inflating: input/train_images/2252494012.jpg inflating: input/train_images/2110760303.jpg inflating: input/train_images/2881921977.jpg inflating: input/train_images/779905140.jpg inflating: input/train_images/2031835632.jpg inflating: input/train_images/2146338076.jpg inflating: input/train_images/2186658480.jpg inflating: input/train_images/1222123820.jpg inflating: input/train_images/2735914869.jpg inflating: input/train_images/3921597155.jpg inflating: input/train_images/2290881666.jpg inflating: input/train_images/2026260632.jpg inflating: input/train_images/3809986981.jpg inflating: input/train_images/3749019108.jpg inflating: input/train_images/1142064548.jpg inflating: input/train_images/473737593.jpg inflating: input/train_images/510338633.jpg inflating: input/train_images/4227613635.jpg inflating: input/train_images/1989388407.jpg inflating: input/train_images/3493597952.jpg inflating: input/train_images/529641068.jpg inflating: input/train_images/3092828212.jpg inflating: input/train_images/1998676158.jpg inflating: input/train_images/2913981436.jpg inflating: input/train_images/2033316556.jpg inflating: input/train_images/1314320713.jpg inflating: input/train_images/917153346.jpg inflating: input/train_images/3797193100.jpg inflating: input/train_images/618242268.jpg inflating: input/train_images/839823259.jpg inflating: input/train_images/1381532581.jpg inflating: input/train_images/3712630265.jpg inflating: input/train_images/888332390.jpg inflating: input/train_images/2225869087.jpg inflating: input/train_images/4260532551.jpg inflating: input/train_images/2907262343.jpg inflating: input/train_images/3188371437.jpg inflating: input/train_images/3373743927.jpg inflating: input/train_images/4214126617.jpg inflating: input/train_images/1769895706.jpg inflating: input/train_images/1168027605.jpg inflating: input/train_images/532103360.jpg inflating: input/train_images/2112497230.jpg inflating: input/train_images/1417032569.jpg inflating: input/train_images/2356810303.jpg inflating: input/train_images/2276911457.jpg inflating: input/train_images/3606039415.jpg inflating: input/train_images/3855806697.jpg inflating: input/train_images/2369607903.jpg inflating: input/train_images/598746218.jpg inflating: input/train_images/3533539817.jpg inflating: input/train_images/4261141445.jpg inflating: input/train_images/797009430.jpg inflating: input/train_images/1748255784.jpg inflating: input/train_images/1931683048.jpg inflating: input/train_images/3465620541.jpg inflating: input/train_images/4070109402.jpg inflating: input/train_images/2337801831.jpg inflating: input/train_images/3151004531.jpg inflating: input/train_images/1921012349.jpg inflating: input/train_images/3748130169.jpg inflating: input/train_images/435094576.jpg inflating: input/train_images/2407217275.jpg inflating: input/train_images/975110881.jpg inflating: input/train_images/3651348948.jpg inflating: input/train_images/378058032.jpg inflating: input/train_images/4219528096.jpg inflating: input/train_images/742519691.jpg inflating: input/train_images/2517495253.jpg inflating: input/train_images/1838219986.jpg inflating: input/train_images/1955905129.jpg inflating: input/train_images/1009495847.jpg inflating: input/train_images/1264109301.jpg inflating: input/train_images/1311772076.jpg inflating: input/train_images/1721767789.jpg inflating: input/train_images/210014333.jpg inflating: input/train_images/1122970967.jpg inflating: input/train_images/3470341002.jpg inflating: input/train_images/3096568582.jpg inflating: input/train_images/2620708986.jpg inflating: input/train_images/1318419572.jpg inflating: input/train_images/3084221499.jpg inflating: input/train_images/2302395970.jpg inflating: input/train_images/809330872.jpg inflating: input/train_images/1989543996.jpg inflating: input/train_images/1648200070.jpg inflating: input/train_images/1425588144.jpg inflating: input/train_images/1834175690.jpg inflating: input/train_images/3079739464.jpg inflating: input/train_images/201703584.jpg inflating: input/train_images/2368100826.jpg inflating: input/train_images/1149596528.jpg inflating: input/train_images/1719304067.jpg inflating: input/train_images/1086538376.jpg inflating: input/train_images/1081331009.jpg inflating: input/train_images/2639026926.jpg inflating: input/train_images/1123847730.jpg inflating: input/train_images/4221079095.jpg inflating: input/train_images/2801308538.jpg inflating: input/train_images/3685314761.jpg inflating: input/train_images/2154562670.jpg inflating: input/train_images/2286580738.jpg inflating: input/train_images/801531661.jpg inflating: input/train_images/1269638182.jpg inflating: input/train_images/2392729768.jpg inflating: input/train_images/9255514.jpg inflating: input/train_images/2425193162.jpg inflating: input/train_images/3686939079.jpg inflating: input/train_images/1093908406.jpg inflating: input/train_images/1231822734.jpg inflating: input/train_images/3345225500.jpg inflating: input/train_images/3615856215.jpg inflating: input/train_images/2930198832.jpg inflating: input/train_images/3949525313.jpg inflating: input/train_images/953218056.jpg inflating: input/train_images/3943832883.jpg inflating: input/train_images/364035626.jpg inflating: input/train_images/1307759125.jpg inflating: input/train_images/3665306245.jpg inflating: input/train_images/2614224221.jpg inflating: input/train_images/1396847821.jpg inflating: input/train_images/1373520804.jpg inflating: input/train_images/4017896312.jpg inflating: input/train_images/1100532272.jpg inflating: input/train_images/2069068462.jpg inflating: input/train_images/1304829719.jpg inflating: input/train_images/515391369.jpg inflating: input/train_images/271969032.jpg inflating: input/train_images/3237441683.jpg inflating: input/train_images/862706097.jpg inflating: input/train_images/1636356850.jpg inflating: input/train_images/3514373354.jpg inflating: input/train_images/2575015649.jpg inflating: input/train_images/2714131195.jpg inflating: input/train_images/670541081.jpg inflating: input/train_images/1546993885.jpg inflating: input/train_images/596124693.jpg inflating: input/train_images/1234924764.jpg inflating: input/train_images/1669079665.jpg inflating: input/train_images/1412766908.jpg inflating: input/train_images/2740084860.jpg inflating: input/train_images/3548238505.jpg inflating: input/train_images/1276561660.jpg inflating: input/train_images/2186042272.jpg inflating: input/train_images/918535914.jpg inflating: input/train_images/1586567598.jpg inflating: input/train_images/3444356227.jpg inflating: input/train_images/1279878525.jpg inflating: input/train_images/2282888474.jpg inflating: input/train_images/4235664377.jpg inflating: input/train_images/4165541319.jpg inflating: input/train_images/4129857747.jpg inflating: input/train_images/2174562681.jpg inflating: input/train_images/2334618381.jpg inflating: input/train_images/1763486772.jpg inflating: input/train_images/4271000778.jpg inflating: input/train_images/1851671093.jpg inflating: input/train_images/2414261693.jpg inflating: input/train_images/3413855723.jpg inflating: input/train_images/185826608.jpg inflating: input/train_images/1083149527.jpg inflating: input/train_images/2134446650.jpg inflating: input/train_images/2596091150.jpg inflating: input/train_images/3221707185.jpg inflating: input/train_images/3073993044.jpg inflating: input/train_images/2759256201.jpg inflating: input/train_images/19905959.jpg inflating: input/train_images/836320036.jpg inflating: input/train_images/4175366577.jpg inflating: input/train_images/3123083708.jpg inflating: input/train_images/3496923861.jpg inflating: input/train_images/1466391339.jpg inflating: input/train_images/1796327295.jpg inflating: input/train_images/2698452187.jpg inflating: input/train_images/3481276167.jpg inflating: input/train_images/1884379874.jpg inflating: input/train_images/322175078.jpg inflating: input/train_images/2837017211.jpg inflating: input/train_images/4044063310.jpg inflating: input/train_images/3586284239.jpg inflating: input/train_images/1148629594.jpg inflating: input/train_images/588169966.jpg inflating: input/train_images/1371946692.jpg inflating: input/train_images/4136963668.jpg inflating: input/train_images/1431172246.jpg inflating: input/train_images/1640860200.jpg inflating: input/train_images/1713497934.jpg inflating: input/train_images/3786394001.jpg inflating: input/train_images/4004655752.jpg inflating: input/train_images/4279337211.jpg inflating: input/train_images/2662609508.jpg inflating: input/train_images/4104529237.jpg inflating: input/train_images/3619447229.jpg inflating: input/train_images/1428048289.jpg inflating: input/train_images/3253079818.jpg inflating: input/train_images/3568424320.jpg inflating: input/train_images/3958714206.jpg inflating: input/train_images/1969270538.jpg inflating: input/train_images/1772264324.jpg inflating: input/train_images/3036226090.jpg inflating: input/train_images/2149893988.jpg inflating: input/train_images/1589160306.jpg inflating: input/train_images/4068103331.jpg inflating: input/train_images/128820265.jpg inflating: input/train_images/3307346645.jpg inflating: input/train_images/2011886920.jpg inflating: input/train_images/735041254.jpg inflating: input/train_images/1552927795.jpg inflating: input/train_images/4132381633.jpg inflating: input/train_images/1708792236.jpg inflating: input/train_images/400686072.jpg inflating: input/train_images/1347999958.jpg inflating: input/train_images/1164550544.jpg inflating: input/train_images/711824069.jpg inflating: input/train_images/1513772475.jpg inflating: input/train_images/3720322849.jpg inflating: input/train_images/812733394.jpg inflating: input/train_images/2298308938.jpg inflating: input/train_images/1475290962.jpg inflating: input/train_images/2241828969.jpg inflating: input/train_images/733701690.jpg inflating: input/train_images/530632304.jpg inflating: input/train_images/17774752.jpg inflating: input/train_images/3099133132.jpg inflating: input/train_images/2597280377.jpg inflating: input/train_images/2828211930.jpg inflating: input/train_images/2845047042.jpg inflating: input/train_images/1548749021.jpg inflating: input/train_images/1907189508.jpg inflating: input/train_images/3500044378.jpg inflating: input/train_images/1211842242.jpg inflating: input/train_images/2898481085.jpg inflating: input/train_images/3479082158.jpg inflating: input/train_images/4013991367.jpg inflating: input/train_images/2953610226.jpg inflating: input/train_images/3594749275.jpg inflating: input/train_images/127130878.jpg inflating: input/train_images/1430955699.jpg inflating: input/train_images/3046878913.jpg inflating: input/train_images/3957612771.jpg inflating: input/train_images/351175754.jpg inflating: input/train_images/3346048761.jpg inflating: input/train_images/1334904382.jpg inflating: input/train_images/2312856534.jpg inflating: input/train_images/3399565382.jpg inflating: input/train_images/3189720932.jpg inflating: input/train_images/3183016038.jpg inflating: input/train_images/910008110.jpg inflating: input/train_images/3370367169.jpg inflating: input/train_images/792105357.jpg inflating: input/train_images/4149719008.jpg inflating: input/train_images/4278349650.jpg inflating: input/train_images/1736753003.jpg inflating: input/train_images/2491061027.jpg inflating: input/train_images/1633926971.jpg inflating: input/train_images/1781156420.jpg inflating: input/train_images/3708222016.jpg inflating: input/train_images/3106475684.jpg inflating: input/train_images/405521670.jpg inflating: input/train_images/1084779411.jpg inflating: input/train_images/800593866.jpg inflating: input/train_images/1417496054.jpg inflating: input/train_images/1942233808.jpg inflating: input/train_images/3877698675.jpg inflating: input/train_images/3441715093.jpg inflating: input/train_images/2319938868.jpg inflating: input/train_images/1688388949.jpg inflating: input/train_images/1336010975.jpg inflating: input/train_images/1780364325.jpg inflating: input/train_images/4282530176.jpg inflating: input/train_images/1115273193.jpg inflating: input/train_images/3057793137.jpg inflating: input/train_images/313266547.jpg inflating: input/train_images/2685117981.jpg inflating: input/train_images/3872024623.jpg inflating: input/train_images/193330948.jpg inflating: input/train_images/1499416552.jpg inflating: input/train_images/270924529.jpg inflating: input/train_images/2799223634.jpg inflating: input/train_images/3047486589.jpg inflating: input/train_images/2890583988.jpg inflating: input/train_images/3670635448.jpg inflating: input/train_images/3161586140.jpg inflating: input/train_images/4012035359.jpg inflating: input/train_images/1884499886.jpg inflating: input/train_images/437121347.jpg inflating: input/train_images/1883239637.jpg inflating: input/train_images/2130031461.jpg inflating: input/train_images/1036959902.jpg inflating: input/train_images/923965406.jpg inflating: input/train_images/544308898.jpg inflating: input/train_images/1539533561.jpg inflating: input/train_images/2218894352.jpg inflating: input/train_images/1320401376.jpg inflating: input/train_images/3931679914.jpg inflating: input/train_images/1402748825.jpg inflating: input/train_images/3855509491.jpg inflating: input/train_images/2907707282.jpg inflating: input/train_images/3022337655.jpg inflating: input/train_images/2380213593.jpg inflating: input/train_images/2429941129.jpg inflating: input/train_images/4230605387.jpg inflating: input/train_images/832593154.jpg inflating: input/train_images/4032326580.jpg inflating: input/train_images/3089200900.jpg inflating: input/train_images/42150813.jpg inflating: input/train_images/956840852.jpg inflating: input/train_images/4067721259.jpg inflating: input/train_images/1423035983.jpg inflating: input/train_images/2883512033.jpg inflating: input/train_images/3739148870.jpg inflating: input/train_images/3395212339.jpg inflating: input/train_images/3196140306.jpg inflating: input/train_images/1022475063.jpg inflating: input/train_images/2458161037.jpg inflating: input/train_images/2880080736.jpg inflating: input/train_images/3102842348.jpg inflating: input/train_images/2250996072.jpg inflating: input/train_images/3584346239.jpg inflating: input/train_images/3713723345.jpg inflating: input/train_images/4037648479.jpg inflating: input/train_images/2960433265.jpg inflating: input/train_images/3795035520.jpg inflating: input/train_images/969719974.jpg inflating: input/train_images/3435954655.jpg inflating: input/train_images/3714240352.jpg inflating: input/train_images/2978748370.jpg inflating: input/train_images/1529906734.jpg inflating: input/train_images/3358566810.jpg inflating: input/train_images/175398874.jpg inflating: input/train_images/2646565423.jpg inflating: input/train_images/4207507257.jpg inflating: input/train_images/2082657173.jpg inflating: input/train_images/1888617839.jpg inflating: input/train_images/2509869422.jpg inflating: input/train_images/3259817213.jpg inflating: input/train_images/2390982435.jpg inflating: input/train_images/4140207015.jpg inflating: input/train_images/282134948.jpg inflating: input/train_images/2265583516.jpg inflating: input/train_images/3275923788.jpg inflating: input/train_images/588893932.jpg inflating: input/train_images/1666313319.jpg inflating: input/train_images/84598209.jpg inflating: input/train_images/2022032014.jpg inflating: input/train_images/2191616657.jpg inflating: input/train_images/4047167362.jpg inflating: input/train_images/1477310762.jpg inflating: input/train_images/3420596297.jpg inflating: input/train_images/318991539.jpg inflating: input/train_images/1835637370.jpg inflating: input/train_images/619095657.jpg inflating: input/train_images/379836605.jpg inflating: input/train_images/1406654897.jpg inflating: input/train_images/2842496003.jpg inflating: input/train_images/3495162607.jpg inflating: input/train_images/11162952.jpg inflating: input/train_images/4210272961.jpg inflating: input/train_images/3928671875.jpg inflating: input/train_images/960202242.jpg inflating: input/train_images/1703598406.jpg inflating: input/train_images/396152951.jpg inflating: input/train_images/1768669927.jpg inflating: input/train_images/1761652043.jpg inflating: input/train_images/88884986.jpg inflating: input/train_images/773722195.jpg inflating: input/train_images/1885492446.jpg inflating: input/train_images/846824837.jpg inflating: input/train_images/780812090.jpg inflating: input/train_images/1363807985.jpg inflating: input/train_images/1712805260.jpg inflating: input/train_images/555028236.jpg inflating: input/train_images/3111312039.jpg inflating: input/train_images/1425848299.jpg inflating: input/train_images/1361425698.jpg inflating: input/train_images/3469950332.jpg inflating: input/train_images/2293304630.jpg inflating: input/train_images/1855416267.jpg inflating: input/train_images/3615317579.jpg inflating: input/train_images/1126189127.jpg inflating: input/train_images/2493815329.jpg inflating: input/train_images/4010033110.jpg inflating: input/train_images/87567596.jpg inflating: input/train_images/2241498976.jpg inflating: input/train_images/3126227969.jpg inflating: input/train_images/2571739382.jpg inflating: input/train_images/1731652110.jpg inflating: input/train_images/354223592.jpg inflating: input/train_images/1555288170.jpg inflating: input/train_images/269106077.jpg inflating: input/train_images/2397652699.jpg inflating: input/train_images/3662919995.jpg inflating: input/train_images/148573246.jpg inflating: input/train_images/1730472510.jpg inflating: input/train_images/1829924843.jpg inflating: input/train_images/1359844717.jpg inflating: input/train_images/3163683583.jpg inflating: input/train_images/2309955110.jpg inflating: input/train_images/3794607673.jpg inflating: input/train_images/1695184578.jpg inflating: input/train_images/255823836.jpg inflating: input/train_images/1232148732.jpg inflating: input/train_images/464335035.jpg inflating: input/train_images/3006942372.jpg inflating: input/train_images/1516455512.jpg inflating: input/train_images/618285041.jpg inflating: input/train_images/842889608.jpg inflating: input/train_images/2623778604.jpg inflating: input/train_images/2495865690.jpg inflating: input/train_images/1985492850.jpg inflating: input/train_images/3689984405.jpg inflating: input/train_images/1634815405.jpg inflating: input/train_images/1286864317.jpg inflating: input/train_images/49856658.jpg inflating: input/train_images/4189636250.jpg inflating: input/train_images/2365362415.jpg inflating: input/train_images/345359010.jpg inflating: input/train_images/206885369.jpg inflating: input/train_images/753470251.jpg inflating: input/train_images/439346642.jpg inflating: input/train_images/3751819618.jpg inflating: input/train_images/4076823454.jpg inflating: input/train_images/3651930392.jpg inflating: input/train_images/1626054782.jpg inflating: input/train_images/2963992338.jpg inflating: input/train_images/3380981345.jpg inflating: input/train_images/2707943069.jpg inflating: input/train_images/1726694302.jpg inflating: input/train_images/1879407752.jpg inflating: input/train_images/578646228.jpg inflating: input/train_images/3837243300.jpg inflating: input/train_images/3412345556.jpg inflating: input/train_images/3034682689.jpg inflating: input/train_images/1492204596.jpg inflating: input/train_images/1143022454.jpg inflating: input/train_images/2371511733.jpg inflating: input/train_images/2011205362.jpg inflating: input/train_images/2477268412.jpg inflating: input/train_images/1713720885.jpg inflating: input/train_images/1086221210.jpg inflating: input/train_images/1110776878.jpg inflating: input/train_images/3117191836.jpg inflating: input/train_images/3078675372.jpg inflating: input/train_images/986854149.jpg inflating: input/train_images/1524705787.jpg inflating: input/train_images/328272253.jpg inflating: input/train_images/513364056.jpg inflating: input/train_images/1365352690.jpg inflating: input/train_images/1462318476.jpg inflating: input/train_images/458279026.jpg inflating: input/train_images/3230535852.jpg inflating: input/train_images/1027766963.jpg inflating: input/train_images/2523038081.jpg inflating: input/train_images/2241795551.jpg inflating: input/train_images/3778585395.jpg inflating: input/train_images/2279465716.jpg inflating: input/train_images/31199469.jpg inflating: input/train_images/62771226.jpg inflating: input/train_images/91850516.jpg inflating: input/train_images/3392605234.jpg inflating: input/train_images/4237501920.jpg inflating: input/train_images/2892098824.jpg inflating: input/train_images/3031973712.jpg inflating: input/train_images/2632579053.jpg inflating: input/train_images/3677086623.jpg inflating: input/train_images/3600838809.jpg inflating: input/train_images/1430503629.jpg inflating: input/train_images/3606832271.jpg inflating: input/train_images/3225508752.jpg inflating: input/train_images/3196066673.jpg inflating: input/train_images/2305707140.jpg inflating: input/train_images/2191768604.jpg inflating: input/train_images/3633084327.jpg inflating: input/train_images/1481899695.jpg inflating: input/train_images/1938616867.jpg inflating: input/train_images/3068094202.jpg inflating: input/train_images/1250607039.jpg inflating: input/train_images/3384036560.jpg inflating: input/train_images/1414812251.jpg inflating: input/train_images/1498323364.jpg inflating: input/train_images/2479508913.jpg inflating: input/train_images/4092575256.jpg inflating: input/train_images/629896725.jpg inflating: input/train_images/2177099962.jpg inflating: input/train_images/2605464541.jpg inflating: input/train_images/1158328538.jpg inflating: input/train_images/434025087.jpg inflating: input/train_images/3969288877.jpg inflating: input/train_images/2601426667.jpg inflating: input/train_images/2250892724.jpg inflating: input/train_images/1654084150.jpg inflating: input/train_images/427226135.jpg inflating: input/train_images/1416108002.jpg inflating: input/train_images/2426488262.jpg inflating: input/train_images/759934720.jpg inflating: input/train_images/290569488.jpg inflating: input/train_images/1121950922.jpg inflating: input/train_images/2489474149.jpg inflating: input/train_images/3867608934.jpg inflating: input/train_images/75207996.jpg inflating: input/train_images/1469568121.jpg inflating: input/train_images/2024328143.jpg inflating: input/train_images/3787937736.jpg inflating: input/train_images/631859689.jpg inflating: input/train_images/701052546.jpg inflating: input/train_images/1355746136.jpg inflating: input/train_images/3055699105.jpg inflating: input/train_images/2649681680.jpg inflating: input/train_images/2733686258.jpg inflating: input/train_images/1419674728.jpg inflating: input/train_images/3766160086.jpg inflating: input/train_images/2530320825.jpg inflating: input/train_images/1640455749.jpg inflating: input/train_images/222017409.jpg inflating: input/train_images/990558315.jpg inflating: input/train_images/250907427.jpg inflating: input/train_images/1451915901.jpg inflating: input/train_images/3630824057.jpg inflating: input/train_images/2594433845.jpg inflating: input/train_images/1510309183.jpg inflating: input/train_images/1182950503.jpg inflating: input/train_images/3251176884.jpg inflating: input/train_images/1905665106.jpg inflating: input/train_images/342641109.jpg inflating: input/train_images/241750365.jpg inflating: input/train_images/4222984856.jpg inflating: input/train_images/2498170494.jpg inflating: input/train_images/2231502538.jpg inflating: input/train_images/1742176204.jpg inflating: input/train_images/442386946.jpg inflating: input/train_images/3594319135.jpg inflating: input/train_images/2658482776.jpg inflating: input/train_images/4233694735.jpg inflating: input/train_images/1673670656.jpg inflating: input/train_images/464299112.jpg inflating: input/train_images/2551622966.jpg inflating: input/train_images/4261671268.jpg inflating: input/train_images/1226235183.jpg inflating: input/train_images/2386556017.jpg inflating: input/train_images/3241593592.jpg inflating: input/train_images/706808191.jpg inflating: input/train_images/527474755.jpg inflating: input/train_images/3149481755.jpg inflating: input/train_images/1364643330.jpg inflating: input/train_images/2715574572.jpg inflating: input/train_images/2698895843.jpg inflating: input/train_images/743105570.jpg inflating: input/train_images/1760489108.jpg inflating: input/train_images/1850537552.jpg inflating: input/train_images/840541858.jpg inflating: input/train_images/4012298941.jpg inflating: input/train_images/66116561.jpg inflating: input/train_images/2655654600.jpg inflating: input/train_images/1645164318.jpg inflating: input/train_images/3132128369.jpg inflating: input/train_images/2707769947.jpg inflating: input/train_images/3924533072.jpg inflating: input/train_images/1597577379.jpg inflating: input/train_images/3979826725.jpg inflating: input/train_images/989119004.jpg inflating: input/train_images/2953075261.jpg inflating: input/train_images/3854724979.jpg inflating: input/train_images/4279868467.jpg inflating: input/train_images/3144413913.jpg inflating: input/train_images/2946668981.jpg inflating: input/train_images/1981073260.jpg inflating: input/train_images/2344357016.jpg inflating: input/train_images/1348163694.jpg inflating: input/train_images/2062577716.jpg inflating: input/train_images/3966975834.jpg inflating: input/train_images/2435302600.jpg inflating: input/train_images/944255811.jpg inflating: input/train_images/2536030910.jpg inflating: input/train_images/1813497241.jpg inflating: input/train_images/1073105435.jpg inflating: input/train_images/1443356256.jpg inflating: input/train_images/1151941049.jpg inflating: input/train_images/44779769.jpg inflating: input/train_images/1946961119.jpg inflating: input/train_images/1621074094.jpg inflating: input/train_images/4287286739.jpg inflating: input/train_images/58390189.jpg inflating: input/train_images/3621162819.jpg inflating: input/train_images/27376313.jpg inflating: input/train_images/120478478.jpg inflating: input/train_images/164144958.jpg inflating: input/train_images/2313851666.jpg inflating: input/train_images/3992168079.jpg inflating: input/train_images/1203777682.jpg inflating: input/train_images/2375799345.jpg inflating: input/train_images/2905887778.jpg inflating: input/train_images/122390799.jpg inflating: input/train_images/212727951.jpg inflating: input/train_images/3195057988.jpg inflating: input/train_images/2117372627.jpg inflating: input/train_images/2343661462.jpg inflating: input/train_images/374285455.jpg inflating: input/train_images/2904534563.jpg inflating: input/train_images/4252535713.jpg inflating: input/train_images/3873234052.jpg inflating: input/train_images/645764425.jpg inflating: input/train_images/1265114019.jpg inflating: input/train_images/102968016.jpg inflating: input/train_images/32222018.jpg inflating: input/train_images/3898690121.jpg inflating: input/train_images/3923893955.jpg inflating: input/train_images/1841364017.jpg inflating: input/train_images/3365603380.jpg inflating: input/train_images/284280039.jpg inflating: input/train_images/3943961452.jpg inflating: input/train_images/1865176608.jpg inflating: input/train_images/929286178.jpg inflating: input/train_images/498242244.jpg inflating: input/train_images/2605912286.jpg inflating: input/train_images/2076206920.jpg inflating: input/train_images/2055902363.jpg inflating: input/train_images/3103401623.jpg inflating: input/train_images/4058647833.jpg inflating: input/train_images/733543752.jpg inflating: input/train_images/4059169921.jpg inflating: input/train_images/2606569889.jpg inflating: input/train_images/786703663.jpg inflating: input/train_images/1974451313.jpg inflating: input/train_images/3303422256.jpg inflating: input/train_images/4206587190.jpg inflating: input/train_images/175320441.jpg inflating: input/train_images/414320641.jpg inflating: input/train_images/3082518263.jpg inflating: input/train_images/173970359.jpg inflating: input/train_images/902007589.jpg inflating: input/train_images/3878214050.jpg inflating: input/train_images/954778743.jpg inflating: input/train_images/1775680225.jpg inflating: input/train_images/3137997905.jpg inflating: input/train_images/3947465350.jpg inflating: input/train_images/351468773.jpg inflating: input/train_images/1742301779.jpg inflating: input/train_images/2291266654.jpg inflating: input/train_images/2221240763.jpg inflating: input/train_images/1287334854.jpg inflating: input/train_images/2722977827.jpg inflating: input/train_images/2535943246.jpg inflating: input/train_images/3041790402.jpg inflating: input/train_images/1424400038.jpg inflating: input/train_images/771092021.jpg inflating: input/train_images/3792671862.jpg inflating: input/train_images/424257956.jpg inflating: input/train_images/722155866.jpg inflating: input/train_images/3314830802.jpg inflating: input/train_images/4199179186.jpg inflating: input/train_images/1276467932.jpg inflating: input/train_images/3285778653.jpg inflating: input/train_images/577275229.jpg inflating: input/train_images/4046239145.jpg inflating: input/train_images/375323961.jpg inflating: input/train_images/1290727489.jpg inflating: input/train_images/2421789568.jpg inflating: input/train_images/3809607157.jpg inflating: input/train_images/2159674288.jpg inflating: input/train_images/2812234258.jpg inflating: input/train_images/1231866114.jpg inflating: input/train_images/2319594231.jpg inflating: input/train_images/4211652237.jpg inflating: input/train_images/2201881693.jpg inflating: input/train_images/169839003.jpg inflating: input/train_images/1398685050.jpg inflating: input/train_images/415504810.jpg inflating: input/train_images/3419381051.jpg inflating: input/train_images/143092286.jpg inflating: input/train_images/720072964.jpg inflating: input/train_images/2387502649.jpg inflating: input/train_images/2640239935.jpg inflating: input/train_images/1057579024.jpg inflating: input/train_images/1336103427.jpg inflating: input/train_images/2421154857.jpg inflating: input/train_images/4144297967.jpg inflating: input/train_images/902139572.jpg inflating: input/train_images/1759297979.jpg inflating: input/train_images/3594689734.jpg inflating: input/train_images/486827297.jpg inflating: input/train_images/3107856880.jpg inflating: input/train_images/1009268848.jpg inflating: input/train_images/3014952608.jpg inflating: input/train_images/2884532990.jpg inflating: input/train_images/860744310.jpg inflating: input/train_images/729514787.jpg inflating: input/train_images/2694336156.jpg inflating: input/train_images/1252288895.jpg inflating: input/train_images/1654777863.jpg inflating: input/train_images/2609452359.jpg inflating: input/train_images/1009704586.jpg inflating: input/train_images/2635255297.jpg inflating: input/train_images/1882997044.jpg inflating: input/train_images/404883957.jpg inflating: input/train_images/4147695010.jpg inflating: input/train_images/1864517626.jpg inflating: input/train_images/538938122.jpg inflating: input/train_images/927713688.jpg inflating: input/train_images/3233669266.jpg inflating: input/train_images/2654948784.jpg inflating: input/train_images/2926655687.jpg inflating: input/train_images/1628979950.jpg inflating: input/train_images/1247154727.jpg inflating: input/train_images/1011139244.jpg inflating: input/train_images/912860596.jpg inflating: input/train_images/1598087640.jpg inflating: input/train_images/1127322697.jpg inflating: input/train_images/3271812673.jpg inflating: input/train_images/547866885.jpg inflating: input/train_images/3669617106.jpg inflating: input/train_images/1741376467.jpg inflating: input/train_images/964570288.jpg inflating: input/train_images/352468512.jpg inflating: input/train_images/3061295375.jpg inflating: input/train_images/2186949019.jpg inflating: input/train_images/2772545038.jpg inflating: input/train_images/1944764485.jpg inflating: input/train_images/1383484107.jpg inflating: input/train_images/1887341048.jpg inflating: input/train_images/3543872440.jpg inflating: input/train_images/3084391599.jpg inflating: input/train_images/2708373940.jpg inflating: input/train_images/1418080132.jpg inflating: input/train_images/3987029837.jpg inflating: input/train_images/2822052779.jpg inflating: input/train_images/4024425381.jpg inflating: input/train_images/4247839780.jpg inflating: input/train_images/1952120040.jpg inflating: input/train_images/3263657130.jpg inflating: input/train_images/4131260506.jpg inflating: input/train_images/53025412.jpg inflating: input/train_images/822444900.jpg inflating: input/train_images/814020712.jpg inflating: input/train_images/3255287642.jpg inflating: input/train_images/4171475132.jpg inflating: input/train_images/3205007771.jpg inflating: input/train_images/673868311.jpg inflating: input/train_images/429982747.jpg inflating: input/train_images/3615381155.jpg inflating: input/train_images/3874354035.jpg inflating: input/train_images/1423702741.jpg inflating: input/train_images/2449191784.jpg inflating: input/train_images/4182646483.jpg inflating: input/train_images/2317789476.jpg inflating: input/train_images/3740367572.jpg inflating: input/train_images/2822226984.jpg inflating: input/train_images/2064730340.jpg inflating: input/train_images/2398068893.jpg inflating: input/train_images/2651900879.jpg inflating: input/train_images/3751355008.jpg inflating: input/train_images/2002906625.jpg inflating: input/train_images/2227639831.jpg inflating: input/train_images/3881028757.jpg inflating: input/train_images/3627502987.jpg inflating: input/train_images/2388202129.jpg inflating: input/train_images/4268211199.jpg inflating: input/train_images/1934046551.jpg inflating: input/train_images/2090702902.jpg inflating: input/train_images/3985416531.jpg inflating: input/train_images/1210950494.jpg inflating: input/train_images/2411989112.jpg inflating: input/train_images/208431523.jpg inflating: input/train_images/1907583116.jpg inflating: input/train_images/3285918057.jpg inflating: input/train_images/884573629.jpg inflating: input/train_images/1866140496.jpg inflating: input/train_images/3676238683.jpg inflating: input/train_images/782115033.jpg inflating: input/train_images/2523850258.jpg inflating: input/train_images/2571102489.jpg inflating: input/train_images/3935356318.jpg inflating: input/train_images/640157848.jpg inflating: input/train_images/4274564396.jpg inflating: input/train_images/1064213029.jpg inflating: input/train_images/870659549.jpg inflating: input/train_images/1265234988.jpg inflating: input/train_images/1909072265.jpg inflating: input/train_images/4280698838.jpg inflating: input/train_images/512152604.jpg inflating: input/train_images/2380764597.jpg inflating: input/train_images/3910075821.jpg inflating: input/train_images/4156293959.jpg inflating: input/train_images/600691544.jpg inflating: input/train_images/2529805366.jpg inflating: input/train_images/3405050538.jpg inflating: input/train_images/672149291.jpg inflating: input/train_images/2158163785.jpg inflating: input/train_images/2534462886.jpg inflating: input/train_images/2848167687.jpg inflating: input/train_images/2705886783.jpg inflating: input/train_images/794665522.jpg inflating: input/train_images/343493007.jpg inflating: input/train_images/1775966274.jpg inflating: input/train_images/169189292.jpg inflating: input/train_images/4218669271.jpg inflating: input/train_images/1599665158.jpg inflating: input/train_images/2346713566.jpg inflating: input/train_images/1140116873.jpg inflating: input/train_images/3931881539.jpg inflating: input/train_images/451431780.jpg inflating: input/train_images/1274424632.jpg inflating: input/train_images/1178309265.jpg inflating: input/train_images/4208508755.jpg inflating: input/train_images/1469995634.jpg inflating: input/train_images/1468561211.jpg inflating: input/train_images/23042367.jpg inflating: input/train_images/396625328.jpg inflating: input/train_images/1652920595.jpg inflating: input/train_images/3876087345.jpg inflating: input/train_images/1151646112.jpg inflating: input/train_images/4123166218.jpg inflating: input/train_images/2349124978.jpg inflating: input/train_images/348828969.jpg inflating: input/train_images/1932604522.jpg inflating: input/train_images/3706807921.jpg inflating: input/train_images/2222709872.jpg inflating: input/train_images/2271948413.jpg inflating: input/train_images/1493725119.jpg inflating: input/train_images/2008776850.jpg inflating: input/train_images/108428649.jpg inflating: input/train_images/2419833907.jpg inflating: input/train_images/3092766457.jpg inflating: input/train_images/2644649435.jpg inflating: input/train_images/1835162927.jpg inflating: input/train_images/3057523045.jpg inflating: input/train_images/2488494933.jpg inflating: input/train_images/1344212681.jpg inflating: input/train_images/141741766.jpg inflating: input/train_images/396829878.jpg inflating: input/train_images/761767350.jpg inflating: input/train_images/3609350672.jpg inflating: input/train_images/1892079469.jpg inflating: input/train_images/2658720625.jpg inflating: input/train_images/2103640329.jpg inflating: input/train_images/3954180556.jpg inflating: input/train_images/1492566436.jpg inflating: input/train_images/4060304349.jpg inflating: input/train_images/4099957665.jpg inflating: input/train_images/4031789905.jpg inflating: input/train_images/3439535328.jpg inflating: input/train_images/463033778.jpg inflating: input/train_images/2527840845.jpg inflating: input/train_images/1800156844.jpg inflating: input/train_images/3644271564.jpg inflating: input/train_images/3584687840.jpg inflating: input/train_images/3729162562.jpg inflating: input/train_images/2975904009.jpg inflating: input/train_images/2800062911.jpg inflating: input/train_images/3564843091.jpg inflating: input/train_images/1345401195.jpg inflating: input/train_images/2889162661.jpg inflating: input/train_images/2860693015.jpg inflating: input/train_images/3702802130.jpg inflating: input/train_images/3929583160.jpg inflating: input/train_images/2476584583.jpg inflating: input/train_images/2137007247.jpg inflating: input/train_images/41357060.jpg inflating: input/train_images/2021701763.jpg inflating: input/train_images/811928525.jpg inflating: input/train_images/3301514895.jpg inflating: input/train_images/2601706592.jpg inflating: input/train_images/58446146.jpg inflating: input/train_images/1470070828.jpg inflating: input/train_images/3967891639.jpg inflating: input/train_images/687913373.jpg inflating: input/train_images/676226256.jpg inflating: input/train_images/1877332484.jpg inflating: input/train_images/1149843066.jpg inflating: input/train_images/2344308543.jpg inflating: input/train_images/849133698.jpg inflating: input/train_images/2268242314.jpg inflating: input/train_images/2281997520.jpg inflating: input/train_images/2033655713.jpg inflating: input/train_images/1295898623.jpg inflating: input/train_images/3308263183.jpg inflating: input/train_images/1231695981.jpg inflating: input/train_images/2613045307.jpg inflating: input/train_images/3375409497.jpg inflating: input/train_images/476113846.jpg inflating: input/train_images/4182745953.jpg inflating: input/train_images/4042037111.jpg inflating: input/train_images/2214576095.jpg inflating: input/train_images/1706796288.jpg inflating: input/train_images/994621972.jpg inflating: input/train_images/3743858641.jpg inflating: input/train_images/2962999252.jpg inflating: input/train_images/1850723562.jpg inflating: input/train_images/2376695116.jpg inflating: input/train_images/1492594056.jpg inflating: input/train_images/190449795.jpg inflating: input/train_images/2218023332.jpg inflating: input/train_images/323873580.jpg inflating: input/train_images/871966628.jpg inflating: input/train_images/511932063.jpg inflating: input/train_images/3896158732.jpg inflating: input/train_images/915715866.jpg inflating: input/train_images/82533757.jpg inflating: input/train_images/2884824828.jpg inflating: input/train_images/319910228.jpg inflating: input/train_images/2940017595.jpg inflating: input/train_images/1592129841.jpg inflating: input/train_images/3107644192.jpg inflating: input/train_images/3698178527.jpg inflating: input/train_images/83337985.jpg inflating: input/train_images/532255691.jpg inflating: input/train_images/1715814415.jpg inflating: input/train_images/3917412702.jpg inflating: input/train_images/1648724139.jpg inflating: input/train_images/2323728288.jpg inflating: input/train_images/1430539919.jpg inflating: input/train_images/4282408832.jpg inflating: input/train_images/4293661491.jpg inflating: input/train_images/2864427141.jpg inflating: input/train_images/1379079003.jpg inflating: input/train_images/3660194933.jpg inflating: input/train_images/249927375.jpg inflating: input/train_images/3219471796.jpg inflating: input/train_images/1834266408.jpg inflating: input/train_images/2016669057.jpg inflating: input/train_images/507004978.jpg inflating: input/train_images/571189248.jpg inflating: input/train_images/952146173.jpg inflating: input/train_images/873526870.jpg inflating: input/train_images/2240458370.jpg inflating: input/train_images/2575222166.jpg inflating: input/train_images/1065833532.jpg inflating: input/train_images/3704493951.jpg inflating: input/train_images/131507385.jpg inflating: input/train_images/111358933.jpg inflating: input/train_images/3758253395.jpg inflating: input/train_images/2475812200.jpg inflating: input/train_images/3235584529.jpg inflating: input/train_images/2178075893.jpg inflating: input/train_images/3675828725.jpg inflating: input/train_images/2337524208.jpg inflating: input/train_images/2024172583.jpg inflating: input/train_images/2326914865.jpg inflating: input/train_images/2941452708.jpg inflating: input/train_images/408414905.jpg inflating: input/train_images/1043184548.jpg inflating: input/train_images/4101194273.jpg inflating: input/train_images/919597577.jpg inflating: input/train_images/654992578.jpg inflating: input/train_images/1775343418.jpg inflating: input/train_images/1472183727.jpg inflating: input/train_images/2559116486.jpg inflating: input/train_images/241148727.jpg inflating: input/train_images/3304643014.jpg inflating: input/train_images/1981041140.jpg inflating: input/train_images/3907936185.jpg inflating: input/train_images/3251562752.jpg inflating: input/train_images/1208145531.jpg inflating: input/train_images/3899552692.jpg inflating: input/train_images/876666484.jpg inflating: input/train_images/211225277.jpg inflating: input/train_images/920401054.jpg inflating: input/train_images/1131959133.jpg inflating: input/train_images/1138006821.jpg inflating: input/train_images/2468963984.jpg inflating: input/train_images/860785504.jpg inflating: input/train_images/55799003.jpg inflating: input/train_images/2873516336.jpg inflating: input/train_images/381393296.jpg inflating: input/train_images/4223217189.jpg inflating: input/train_images/2814433150.jpg inflating: input/train_images/2177675284.jpg inflating: input/train_images/2975448123.jpg inflating: input/train_images/3519335178.jpg inflating: input/train_images/4082420465.jpg inflating: input/train_images/1882919886.jpg inflating: input/train_images/4207293267.jpg inflating: input/train_images/2115648947.jpg inflating: input/train_images/1589109993.jpg inflating: input/train_images/907691648.jpg inflating: input/train_images/4136626919.jpg inflating: input/train_images/761160675.jpg inflating: input/train_images/9312065.jpg inflating: input/train_images/3085973890.jpg inflating: input/train_images/1541714876.jpg inflating: input/train_images/3188953817.jpg inflating: input/train_images/3240792628.jpg inflating: input/train_images/4253799258.jpg inflating: input/train_images/2494865945.jpg inflating: input/train_images/696538469.jpg inflating: input/train_images/3489269448.jpg inflating: input/train_images/497685909.jpg inflating: input/train_images/1154259077.jpg inflating: input/train_images/1491670235.jpg inflating: input/train_images/3563392216.jpg inflating: input/train_images/3623375685.jpg inflating: input/train_images/745566741.jpg inflating: input/train_images/411955232.jpg inflating: input/train_images/2098699727.jpg inflating: input/train_images/2462747672.jpg inflating: input/train_images/1169677118.jpg inflating: input/train_images/775786945.jpg inflating: input/train_images/3180664408.jpg inflating: input/train_images/4078601864.jpg inflating: input/train_images/4170892667.jpg inflating: input/train_images/1226193662.jpg inflating: input/train_images/2742114843.jpg inflating: input/train_images/490760030.jpg inflating: input/train_images/2002346677.jpg inflating: input/train_images/2089853591.jpg inflating: input/train_images/3092716255.jpg inflating: input/train_images/3113190178.jpg inflating: input/train_images/719526260.jpg inflating: input/train_images/808180923.jpg inflating: input/train_images/740762568.jpg inflating: input/train_images/3080481359.jpg inflating: input/train_images/3287692788.jpg inflating: input/train_images/3208609885.jpg inflating: input/train_images/1558118745.jpg inflating: input/train_images/944726140.jpg inflating: input/train_images/3964066128.jpg inflating: input/train_images/1753872657.jpg inflating: input/train_images/513986084.jpg inflating: input/train_images/891426683.jpg inflating: input/train_images/1270368553.jpg inflating: input/train_images/9454129.jpg inflating: input/train_images/1129878051.jpg inflating: input/train_images/1060644080.jpg inflating: input/train_images/3408858113.jpg inflating: input/train_images/581179733.jpg inflating: input/train_images/2847223266.jpg inflating: input/train_images/2529150821.jpg inflating: input/train_images/2105063058.jpg inflating: input/train_images/2182518914.jpg inflating: input/train_images/3376371946.jpg inflating: input/train_images/2437201100.jpg inflating: input/train_images/2951126410.jpg inflating: input/train_images/615415014.jpg inflating: input/train_images/3541075880.jpg inflating: input/train_images/3609260930.jpg inflating: input/train_images/1348606741.jpg inflating: input/train_images/2287869401.jpg inflating: input/train_images/3115057364.jpg inflating: input/train_images/738338306.jpg inflating: input/train_images/1903992787.jpg inflating: input/train_images/462402577.jpg inflating: input/train_images/1129666944.jpg inflating: input/train_images/693164586.jpg inflating: input/train_images/3840637397.jpg inflating: input/train_images/880178968.jpg inflating: input/train_images/3977938536.jpg inflating: input/train_images/3531650713.jpg inflating: input/train_images/3257711542.jpg inflating: input/train_images/3714119135.jpg inflating: input/train_images/3027691323.jpg inflating: input/train_images/2585045883.jpg inflating: input/train_images/3117219248.jpg inflating: input/train_images/2837141717.jpg inflating: input/train_images/1001723730.jpg inflating: input/train_images/696867083.jpg inflating: input/train_images/1522208575.jpg inflating: input/train_images/2270358342.jpg inflating: input/train_images/2078942776.jpg inflating: input/train_images/3147511199.jpg inflating: input/train_images/3818759549.jpg inflating: input/train_images/3316969906.jpg inflating: input/train_images/2333207631.jpg inflating: input/train_images/1968421706.jpg inflating: input/train_images/1752948058.jpg inflating: input/train_images/832440144.jpg inflating: input/train_images/4024391744.jpg inflating: input/train_images/4048156987.jpg inflating: input/train_images/4276465485.jpg inflating: input/train_images/2618036565.jpg inflating: input/train_images/1767778795.jpg inflating: input/train_images/2200762237.jpg inflating: input/train_images/3331347285.jpg inflating: input/train_images/323586160.jpg inflating: input/train_images/3440246067.jpg inflating: input/train_images/3083613226.jpg inflating: input/train_images/2748659636.jpg inflating: input/train_images/4111265654.jpg inflating: input/train_images/3354624529.jpg inflating: input/train_images/1986919607.jpg inflating: input/train_images/742898185.jpg inflating: input/train_images/2384551148.jpg inflating: input/train_images/2251153057.jpg inflating: input/train_images/1860324672.jpg inflating: input/train_images/1676052292.jpg inflating: input/train_images/3670039640.jpg inflating: input/train_images/1177074840.jpg inflating: input/train_images/3951364046.jpg inflating: input/train_images/186667196.jpg inflating: input/train_images/3341713020.jpg inflating: input/train_images/3486225470.jpg inflating: input/train_images/4098341362.jpg inflating: input/train_images/3250253495.jpg inflating: input/train_images/3958986545.jpg inflating: input/train_images/1101317234.jpg inflating: input/train_images/2143264851.jpg inflating: input/train_images/4130203885.jpg inflating: input/train_images/2061733689.jpg inflating: input/train_images/2021948804.jpg inflating: input/train_images/2150406389.jpg inflating: input/train_images/1178519877.jpg inflating: input/train_images/4225133358.jpg inflating: input/train_images/723564013.jpg inflating: input/train_images/3208851813.jpg inflating: input/train_images/3150477025.jpg inflating: input/train_images/3300885184.jpg inflating: input/train_images/231005253.jpg inflating: input/train_images/1023837322.jpg inflating: input/train_images/1727150436.jpg inflating: input/train_images/2563788715.jpg inflating: input/train_images/102039365.jpg inflating: input/train_images/4179147529.jpg inflating: input/train_images/2203981379.jpg inflating: input/train_images/2021244568.jpg inflating: input/train_images/2489350383.jpg inflating: input/train_images/2385423168.jpg inflating: input/train_images/4211138249.jpg inflating: input/train_images/1635544822.jpg inflating: input/train_images/302898400.jpg inflating: input/train_images/736834551.jpg inflating: input/train_images/1643552654.jpg inflating: input/train_images/3110035366.jpg inflating: input/train_images/1595577438.jpg inflating: input/train_images/1674922822.jpg inflating: input/train_images/1688478980.jpg inflating: input/train_images/6103.jpg inflating: input/train_images/825551560.jpg inflating: input/train_images/582179912.jpg inflating: input/train_images/1575013487.jpg inflating: input/train_images/1017006970.jpg inflating: input/train_images/1398572814.jpg inflating: input/train_images/3442867405.jpg inflating: input/train_images/1442249007.jpg inflating: input/train_images/135834998.jpg inflating: input/train_images/3903538298.jpg inflating: input/train_images/2877008433.jpg inflating: input/train_images/2222831550.jpg inflating: input/train_images/3125050696.jpg inflating: input/train_images/336299725.jpg inflating: input/train_images/3435885572.jpg inflating: input/train_images/1575521049.jpg inflating: input/train_images/2403083568.jpg inflating: input/train_images/2371237551.jpg inflating: input/train_images/189585547.jpg inflating: input/train_images/3323965689.jpg inflating: input/train_images/1741967088.jpg inflating: input/train_images/1494726462.jpg inflating: input/train_images/3793827107.jpg inflating: input/train_images/2242503873.jpg inflating: input/train_images/29130164.jpg inflating: input/train_images/2194916526.jpg inflating: input/train_images/814185128.jpg inflating: input/train_images/4006579451.jpg inflating: input/train_images/3924061539.jpg inflating: input/train_images/4192202317.jpg inflating: input/train_images/2917486619.jpg inflating: input/train_images/3368457880.jpg inflating: input/train_images/830772376.jpg inflating: input/train_images/3784391347.jpg inflating: input/train_images/3548679387.jpg inflating: input/train_images/3701689199.jpg inflating: input/train_images/543312121.jpg inflating: input/train_images/3096059384.jpg inflating: input/train_images/607840807.jpg inflating: input/train_images/610094717.jpg inflating: input/train_images/1422694007.jpg inflating: input/train_images/993366541.jpg inflating: input/train_images/1657763940.jpg inflating: input/train_images/2019941140.jpg inflating: input/train_images/3743464955.jpg inflating: input/train_images/12688038.jpg inflating: input/train_images/3623190050.jpg inflating: input/train_images/3170957509.jpg inflating: input/train_images/3791562105.jpg inflating: input/train_images/1271525915.jpg inflating: input/train_images/2649484487.jpg inflating: input/train_images/4221848010.jpg inflating: input/train_images/2058959882.jpg inflating: input/train_images/4046068592.jpg inflating: input/train_images/3644657668.jpg inflating: input/train_images/2055261864.jpg inflating: input/train_images/2443428424.jpg inflating: input/train_images/1653535676.jpg inflating: input/train_images/744972013.jpg inflating: input/train_images/3068359463.jpg inflating: input/train_images/3664934784.jpg inflating: input/train_images/2156883044.jpg inflating: input/train_images/3292555378.jpg inflating: input/train_images/1176894803.jpg inflating: input/train_images/1291065002.jpg inflating: input/train_images/2236610037.jpg inflating: input/train_images/2051048628.jpg inflating: input/train_images/1059213340.jpg inflating: input/train_images/972622677.jpg inflating: input/train_images/491673903.jpg inflating: input/train_images/4131457294.jpg inflating: input/train_images/3333666077.jpg inflating: input/train_images/2734186624.jpg inflating: input/train_images/3403835665.jpg inflating: input/train_images/3598395242.jpg inflating: input/train_images/357823942.jpg inflating: input/train_images/2437048705.jpg inflating: input/train_images/2432364538.jpg inflating: input/train_images/3304581364.jpg inflating: input/train_images/1564583746.jpg inflating: input/train_images/1923179851.jpg inflating: input/train_images/1098441542.jpg inflating: input/train_images/2844800744.jpg inflating: input/train_images/3576795584.jpg inflating: input/train_images/605816056.jpg inflating: input/train_images/3632711020.jpg inflating: input/train_images/3523363514.jpg inflating: input/train_images/3613817114.jpg inflating: input/train_images/3365264596.jpg inflating: input/train_images/931943521.jpg inflating: input/train_images/3277182366.jpg inflating: input/train_images/2588469356.jpg inflating: input/train_images/4172480899.jpg inflating: input/train_images/2888640560.jpg inflating: input/train_images/920229727.jpg inflating: input/train_images/4121566836.jpg inflating: input/train_images/1946046925.jpg inflating: input/train_images/2578576273.jpg inflating: input/train_images/1687852669.jpg inflating: input/train_images/1408639438.jpg inflating: input/train_images/1851047251.jpg inflating: input/train_images/4177391802.jpg inflating: input/train_images/1544151022.jpg inflating: input/train_images/157014347.jpg inflating: input/train_images/2462876995.jpg inflating: input/train_images/572515769.jpg inflating: input/train_images/3942244753.jpg inflating: input/train_images/4250885951.jpg inflating: input/train_images/1040079282.jpg inflating: input/train_images/1679233615.jpg inflating: input/train_images/4054246073.jpg inflating: input/train_images/1633652647.jpg inflating: input/train_images/3454772304.jpg inflating: input/train_images/3384300864.jpg inflating: input/train_images/3728053314.jpg inflating: input/train_images/144301620.jpg inflating: input/train_images/4213525466.jpg inflating: input/train_images/1189155349.jpg inflating: input/train_images/3902366551.jpg inflating: input/train_images/3406720343.jpg inflating: input/train_images/1925077855.jpg inflating: input/train_images/3604705495.jpg inflating: input/train_images/1700921498.jpg inflating: input/train_images/3175679586.jpg inflating: input/train_images/3921328805.jpg inflating: input/train_images/1803764964.jpg inflating: input/train_images/1486873366.jpg inflating: input/train_images/3356619304.jpg inflating: input/train_images/2990902039.jpg inflating: input/train_images/1092772509.jpg inflating: input/train_images/1750580369.jpg inflating: input/train_images/3640609321.jpg inflating: input/train_images/747770020.jpg inflating: input/train_images/3702249794.jpg inflating: input/train_images/4283521063.jpg inflating: input/train_images/2721303722.jpg inflating: input/train_images/1278246781.jpg inflating: input/train_images/1698429014.jpg inflating: input/train_images/4044329664.jpg inflating: input/train_images/897925605.jpg inflating: input/train_images/3991445025.jpg inflating: input/train_images/1350898322.jpg inflating: input/train_images/627068686.jpg inflating: input/train_images/4206288054.jpg inflating: input/train_images/3959033347.jpg inflating: input/train_images/2549684718.jpg inflating: input/train_images/3943363815.jpg inflating: input/train_images/3305068232.jpg inflating: input/train_images/3912538989.jpg inflating: input/train_images/1768185229.jpg inflating: input/train_images/652624585.jpg inflating: input/train_images/149791608.jpg inflating: input/train_images/1694314252.jpg inflating: input/train_images/324248837.jpg inflating: input/train_images/551716959.jpg inflating: input/train_images/2837753620.jpg inflating: input/train_images/1710828726.jpg inflating: input/train_images/3672364441.jpg inflating: input/train_images/1031500522.jpg inflating: input/train_images/1162809006.jpg inflating: input/train_images/1290189931.jpg inflating: input/train_images/2657104946.jpg inflating: input/train_images/2702330830.jpg inflating: input/train_images/3986218390.jpg inflating: input/train_images/2321458.jpg inflating: input/train_images/790568397.jpg inflating: input/train_images/2725369010.jpg inflating: input/train_images/3248325951.jpg inflating: input/train_images/442743258.jpg inflating: input/train_images/2176153898.jpg inflating: input/train_images/1420352773.jpg inflating: input/train_images/553195372.jpg inflating: input/train_images/2212089862.jpg inflating: input/train_images/163947288.jpg inflating: input/train_images/561647799.jpg inflating: input/train_images/1049791378.jpg inflating: input/train_images/2292197107.jpg inflating: input/train_images/700664783.jpg inflating: input/train_images/3943338687.jpg inflating: input/train_images/1900666535.jpg inflating: input/train_images/338729354.jpg inflating: input/train_images/3504889993.jpg inflating: input/train_images/2260738205.jpg inflating: input/train_images/3223282866.jpg inflating: input/train_images/630797550.jpg inflating: input/train_images/4286174060.jpg inflating: input/train_images/3320071514.jpg inflating: input/train_images/2612899548.jpg inflating: input/train_images/2242351929.jpg inflating: input/train_images/3761713726.jpg inflating: input/train_images/2152051451.jpg inflating: input/train_images/2187716233.jpg inflating: input/train_images/2433307411.jpg inflating: input/train_images/2833869009.jpg inflating: input/train_images/2703773318.jpg inflating: input/train_images/2512300453.jpg inflating: input/train_images/550691642.jpg inflating: input/train_images/1373499412.jpg inflating: input/train_images/3324881806.jpg inflating: input/train_images/1281155236.jpg inflating: input/train_images/3957562076.jpg inflating: input/train_images/3356800378.jpg inflating: input/train_images/476858432.jpg inflating: input/train_images/3561069837.jpg inflating: input/train_images/3834284991.jpg inflating: input/train_images/601644904.jpg inflating: input/train_images/1740309612.jpg inflating: input/train_images/1238821861.jpg inflating: input/train_images/1164692375.jpg inflating: input/train_images/798006612.jpg inflating: input/train_images/3139351952.jpg inflating: input/train_images/621367062.jpg inflating: input/train_images/1787178614.jpg inflating: input/train_images/1227161199.jpg inflating: input/train_images/3451871229.jpg inflating: input/train_images/36508013.jpg inflating: input/train_images/1454850686.jpg inflating: input/train_images/2045580929.jpg inflating: input/train_images/1721634086.jpg inflating: input/train_images/3779724069.jpg inflating: input/train_images/2529358101.jpg inflating: input/train_images/2174309008.jpg inflating: input/train_images/3486487741.jpg inflating: input/train_images/3816412484.jpg inflating: input/train_images/2686776292.jpg inflating: input/train_images/1317487445.jpg inflating: input/train_images/549750394.jpg inflating: input/train_images/447048984.jpg inflating: input/train_images/2074319088.jpg inflating: input/train_images/187343662.jpg inflating: input/train_images/181355439.jpg inflating: input/train_images/1556497496.jpg inflating: input/train_images/2791918976.jpg inflating: input/train_images/1009361983.jpg inflating: input/train_images/3452080171.jpg inflating: input/train_images/2727816974.jpg inflating: input/train_images/1655615998.jpg inflating: input/train_images/3413220258.jpg inflating: input/train_images/3238426139.jpg inflating: input/train_images/957437817.jpg inflating: input/train_images/3318282640.jpg inflating: input/train_images/1810295906.jpg inflating: input/train_images/527923260.jpg inflating: input/train_images/3029026599.jpg inflating: input/train_images/2397511243.jpg inflating: input/train_images/523467512.jpg inflating: input/train_images/2189140444.jpg inflating: input/train_images/2893140493.jpg inflating: input/train_images/1515921207.jpg inflating: input/train_images/2017329516.jpg inflating: input/train_images/3231201573.jpg inflating: input/train_images/123865158.jpg inflating: input/train_images/391853550.jpg inflating: input/train_images/1383579851.jpg inflating: input/train_images/3792533899.jpg inflating: input/train_images/3617067141.jpg inflating: input/train_images/623333046.jpg inflating: input/train_images/3559981218.jpg inflating: input/train_images/3426035333.jpg inflating: input/train_images/1345964218.jpg inflating: input/train_images/1951270318.jpg inflating: input/train_images/440896922.jpg inflating: input/train_images/1142600361.jpg inflating: input/train_images/1258505000.jpg inflating: input/train_images/2452364106.jpg inflating: input/train_images/2164681780.jpg inflating: input/train_images/2267434559.jpg inflating: input/train_images/954749288.jpg inflating: input/train_images/2293810835.jpg inflating: input/train_images/1799764071.jpg inflating: input/train_images/519373224.jpg inflating: input/train_images/3376905285.jpg inflating: input/train_images/31398935.jpg inflating: input/train_images/459566440.jpg inflating: input/train_images/3609925731.jpg inflating: input/train_images/3910162936.jpg inflating: input/train_images/425235104.jpg inflating: input/train_images/1728004537.jpg inflating: input/train_images/823276084.jpg inflating: input/train_images/3485849218.jpg inflating: input/train_images/1345258060.jpg inflating: input/train_images/2906227978.jpg inflating: input/train_images/1533935132.jpg inflating: input/train_images/892025744.jpg inflating: input/train_images/2657169592.jpg inflating: input/train_images/57149651.jpg inflating: input/train_images/2382758285.jpg inflating: input/train_images/2442102115.jpg inflating: input/train_images/3194870771.jpg inflating: input/train_images/495190803.jpg inflating: input/train_images/3884199625.jpg inflating: input/train_images/432371484.jpg inflating: input/train_images/235258659.jpg inflating: input/train_images/3705669883.jpg inflating: input/train_images/77379532.jpg inflating: input/train_images/3769167654.jpg inflating: input/train_images/3672629086.jpg inflating: input/train_images/3803823261.jpg inflating: input/train_images/70656521.jpg inflating: input/train_images/725027388.jpg inflating: input/train_images/3905145362.jpg inflating: input/train_images/69803851.jpg inflating: input/train_images/1996862654.jpg inflating: input/train_images/3556675221.jpg inflating: input/train_images/7830631.jpg inflating: input/train_images/3528647821.jpg inflating: input/train_images/4019771530.jpg inflating: input/train_images/3820517266.jpg inflating: input/train_images/2003067998.jpg inflating: input/train_images/3738618109.jpg inflating: input/train_images/871333676.jpg inflating: input/train_images/854773586.jpg inflating: input/train_images/4004133979.jpg inflating: input/train_images/3712064465.jpg inflating: input/train_images/3384250377.jpg inflating: input/train_images/2091940865.jpg inflating: input/train_images/1435182915.jpg inflating: input/train_images/4263534897.jpg inflating: input/train_images/2094357697.jpg inflating: input/train_images/3212523761.jpg inflating: input/train_images/4057359447.jpg inflating: input/train_images/353518711.jpg inflating: input/train_images/1745296302.jpg inflating: input/train_images/2668524110.jpg inflating: input/train_images/534784883.jpg inflating: input/train_images/3758838047.jpg inflating: input/train_images/284270936.jpg inflating: input/train_images/2079104179.jpg inflating: input/train_images/1206025945.jpg inflating: input/train_images/240469234.jpg inflating: input/train_images/207893947.jpg inflating: input/train_images/1433061380.jpg inflating: input/train_images/3567260259.jpg inflating: input/train_images/724302384.jpg inflating: input/train_images/1823721668.jpg inflating: input/train_images/3207910782.jpg inflating: input/train_images/999329392.jpg inflating: input/train_images/563348054.jpg inflating: input/train_images/414363375.jpg inflating: input/train_images/2154249381.jpg inflating: input/train_images/2854519294.jpg inflating: input/train_images/3305821160.jpg inflating: input/train_images/3645419540.jpg inflating: input/train_images/2365265934.jpg inflating: input/train_images/3341706471.jpg inflating: input/train_images/2565456267.jpg inflating: input/train_images/2241394681.jpg inflating: input/train_images/2756642189.jpg inflating: input/train_images/128594927.jpg inflating: input/train_images/2650949618.jpg inflating: input/train_images/1831917433.jpg inflating: input/train_images/473823142.jpg inflating: input/train_images/2173229407.jpg inflating: input/train_images/2698282165.jpg inflating: input/train_images/3542768898.jpg inflating: input/train_images/1926981545.jpg inflating: input/train_images/1208216776.jpg inflating: input/train_images/4147991798.jpg inflating: input/train_images/2750295170.jpg inflating: input/train_images/3713964400.jpg inflating: input/train_images/3924602971.jpg inflating: input/train_images/2051629821.jpg inflating: input/train_images/3406705095.jpg inflating: input/train_images/1157584839.jpg inflating: input/train_images/1966061216.jpg inflating: input/train_images/1938730022.jpg inflating: input/train_images/2252678193.jpg inflating: input/train_images/2666373738.jpg inflating: input/train_images/3151577248.jpg inflating: input/train_images/1854790191.jpg inflating: input/train_images/4170665280.jpg inflating: input/train_images/326839479.jpg inflating: input/train_images/3500204258.jpg inflating: input/train_images/1335214678.jpg inflating: input/train_images/2045675044.jpg inflating: input/train_images/53615554.jpg inflating: input/train_images/2569083558.jpg inflating: input/train_images/745442190.jpg inflating: input/train_images/3579980941.jpg inflating: input/train_images/2103659900.jpg inflating: input/train_images/304408360.jpg inflating: input/train_images/3410015128.jpg inflating: input/train_images/3495009786.jpg inflating: input/train_images/178079419.jpg inflating: input/train_images/4156956690.jpg inflating: input/train_images/691285209.jpg inflating: input/train_images/3190980772.jpg inflating: input/train_images/2946977526.jpg inflating: input/train_images/2095602074.jpg inflating: input/train_images/3298994120.jpg inflating: input/train_images/2116662197.jpg inflating: input/train_images/4202441426.jpg inflating: input/train_images/824321777.jpg inflating: input/train_images/3140362576.jpg inflating: input/train_images/2207440318.jpg inflating: input/train_images/226557134.jpg inflating: input/train_images/2484530081.jpg inflating: input/train_images/1983454737.jpg inflating: input/train_images/3653076658.jpg inflating: input/train_images/4183866544.jpg inflating: input/train_images/2178767483.jpg inflating: input/train_images/2138403170.jpg inflating: input/train_images/898386629.jpg inflating: input/train_images/239724736.jpg inflating: input/train_images/4135889078.jpg inflating: input/train_images/1218546888.jpg inflating: input/train_images/3443846811.jpg inflating: input/train_images/3365267863.jpg inflating: input/train_images/1510579448.jpg inflating: input/train_images/4146003606.jpg inflating: input/train_images/494596361.jpg inflating: input/train_images/2484602563.jpg inflating: input/train_images/1815972967.jpg inflating: input/train_images/3576823132.jpg inflating: input/train_images/2620251115.jpg inflating: input/train_images/1053009170.jpg inflating: input/train_images/2610411314.jpg inflating: input/train_images/1542373427.jpg inflating: input/train_images/512575634.jpg inflating: input/train_images/3306255309.jpg inflating: input/train_images/2220309469.jpg inflating: input/train_images/2273730548.jpg inflating: input/train_images/535314273.jpg inflating: input/train_images/2707336069.jpg inflating: input/train_images/379548308.jpg inflating: input/train_images/2189576451.jpg inflating: input/train_images/557774617.jpg inflating: input/train_images/2757539730.jpg inflating: input/train_images/2976035478.jpg inflating: input/train_images/3647297248.jpg inflating: input/train_images/544346867.jpg inflating: input/train_images/1220118716.jpg inflating: input/train_images/3815135505.jpg inflating: input/train_images/1775001723.jpg inflating: input/train_images/396499078.jpg inflating: input/train_images/2663749229.jpg inflating: input/train_images/309569120.jpg inflating: input/train_images/4102729978.jpg inflating: input/train_images/2018165733.jpg inflating: input/train_images/1643576810.jpg inflating: input/train_images/1291178007.jpg inflating: input/train_images/3957819631.jpg inflating: input/train_images/3389583925.jpg inflating: input/train_images/2653588387.jpg inflating: input/train_images/2384181550.jpg inflating: input/train_images/2594282701.jpg inflating: input/train_images/4288418406.jpg inflating: input/train_images/1355462312.jpg inflating: input/train_images/314599917.jpg inflating: input/train_images/2628555515.jpg inflating: input/train_images/1332855741.jpg inflating: input/train_images/4221104214.jpg inflating: input/train_images/1446871248.jpg inflating: input/train_images/2083878392.jpg inflating: input/train_images/3511671285.jpg inflating: input/train_images/651123589.jpg inflating: input/train_images/2421566220.jpg inflating: input/train_images/368553798.jpg inflating: input/train_images/1974079097.jpg inflating: input/train_images/412390858.jpg inflating: input/train_images/3917185101.jpg inflating: input/train_images/2225817818.jpg inflating: input/train_images/3608578044.jpg inflating: input/train_images/3854923530.jpg inflating: input/train_images/2795551857.jpg inflating: input/train_images/1733354827.jpg inflating: input/train_images/376932028.jpg inflating: input/train_images/3203412332.jpg inflating: input/train_images/815702740.jpg inflating: input/train_images/1680657766.jpg inflating: input/train_images/4127132722.jpg inflating: input/train_images/2082251851.jpg inflating: input/train_images/3442647074.jpg inflating: input/train_images/3684209409.jpg inflating: input/train_images/147604859.jpg inflating: input/train_images/1873100849.jpg inflating: input/train_images/3814035701.jpg inflating: input/train_images/3869030734.jpg inflating: input/train_images/1567877420.jpg inflating: input/train_images/619658845.jpg inflating: input/train_images/2378984273.jpg inflating: input/train_images/2214228898.jpg inflating: input/train_images/3205016772.jpg inflating: input/train_images/494558399.jpg inflating: input/train_images/573039129.jpg inflating: input/train_images/2710440557.jpg inflating: input/train_images/3192657039.jpg inflating: input/train_images/3570121717.jpg inflating: input/train_images/1898437154.jpg inflating: input/train_images/1302078468.jpg inflating: input/train_images/1483743890.jpg inflating: input/train_images/657424989.jpg inflating: input/train_images/159031113.jpg inflating: input/train_images/3652093161.jpg inflating: input/train_images/1998363687.jpg inflating: input/train_images/1968596086.jpg inflating: input/train_images/1009322597.jpg inflating: input/train_images/1972409682.jpg inflating: input/train_images/4089218356.jpg inflating: input/train_images/2600500593.jpg inflating: input/train_images/1960063101.jpg inflating: input/train_images/2016371750.jpg inflating: input/train_images/1063110047.jpg inflating: input/train_images/3662018109.jpg inflating: input/train_images/2514350663.jpg inflating: input/train_images/3219439906.jpg inflating: input/train_images/700464495.jpg inflating: input/train_images/3192692419.jpg inflating: input/train_images/3719058586.jpg inflating: input/train_images/1194042617.jpg inflating: input/train_images/3747440776.jpg inflating: input/train_images/2895326283.jpg inflating: input/train_images/265181391.jpg inflating: input/train_images/3856769685.jpg inflating: input/train_images/4009888434.jpg inflating: input/train_images/1512350296.jpg inflating: input/train_images/641590483.jpg inflating: input/train_images/2514394316.jpg inflating: input/train_images/1631620098.jpg inflating: input/train_images/2907723622.jpg inflating: input/train_images/1314553833.jpg inflating: input/train_images/3566226674.jpg inflating: input/train_images/1077138637.jpg inflating: input/train_images/1083021605.jpg inflating: input/train_images/1150608601.jpg inflating: input/train_images/2713091649.jpg inflating: input/train_images/2797611751.jpg inflating: input/train_images/1525852725.jpg inflating: input/train_images/3658178204.jpg inflating: input/train_images/117226420.jpg inflating: input/train_images/441408374.jpg inflating: input/train_images/910617288.jpg inflating: input/train_images/744676370.jpg inflating: input/train_images/2462241027.jpg inflating: input/train_images/4060346540.jpg inflating: input/train_images/2292154193.jpg inflating: input/train_images/2457737762.jpg inflating: input/train_images/1262742218.jpg inflating: input/train_images/972840038.jpg inflating: input/train_images/631563709.jpg inflating: input/train_images/3914082089.jpg inflating: input/train_images/3934216826.jpg inflating: input/train_images/1131545521.jpg inflating: input/train_images/3988748153.jpg inflating: input/train_images/3633505917.jpg inflating: input/train_images/207761661.jpg inflating: input/train_images/2086061590.jpg inflating: input/train_images/2272721188.jpg inflating: input/train_images/2148834762.jpg inflating: input/train_images/3317706044.jpg inflating: input/train_images/3115055353.jpg inflating: input/train_images/2995689898.jpg inflating: input/train_images/2875351329.jpg inflating: input/train_images/3586867158.jpg inflating: input/train_images/1906831443.jpg inflating: input/train_images/568949064.jpg inflating: input/train_images/2742350070.jpg inflating: input/train_images/2878480561.jpg inflating: input/train_images/4186680625.jpg inflating: input/train_images/2056154613.jpg inflating: input/train_images/3435254116.jpg inflating: input/train_images/3484566225.jpg inflating: input/train_images/3120725353.jpg inflating: input/train_images/3192892221.jpg inflating: input/train_images/1670109260.jpg inflating: input/train_images/3589849323.jpg inflating: input/train_images/813060428.jpg inflating: input/train_images/1033403106.jpg inflating: input/train_images/3078123533.jpg inflating: input/train_images/2800642069.jpg inflating: input/train_images/1705724767.jpg inflating: input/train_images/817366566.jpg inflating: input/train_images/2876605372.jpg inflating: input/train_images/3211443011.jpg inflating: input/train_images/2810787386.jpg inflating: input/train_images/3027251380.jpg inflating: input/train_images/1545341197.jpg inflating: input/train_images/2648991795.jpg inflating: input/train_images/3302044032.jpg inflating: input/train_images/2754537497.jpg inflating: input/train_images/3945332868.jpg inflating: input/train_images/3058243587.jpg inflating: input/train_images/2856404486.jpg inflating: input/train_images/2059048377.jpg inflating: input/train_images/681211585.jpg inflating: input/train_images/4290607578.jpg inflating: input/train_images/1454944435.jpg inflating: input/train_images/1649231975.jpg inflating: input/train_images/4290883718.jpg inflating: input/train_images/1844847808.jpg inflating: input/train_images/107466550.jpg inflating: input/train_images/248540513.jpg inflating: input/train_images/1744118582.jpg inflating: input/train_images/3247553763.jpg inflating: input/train_images/2241778439.jpg inflating: input/train_images/3675829567.jpg inflating: input/train_images/1664825517.jpg inflating: input/train_images/1040828572.jpg inflating: input/train_images/705928796.jpg inflating: input/train_images/2807875042.jpg inflating: input/train_images/2198414004.jpg inflating: input/train_images/1595866872.jpg inflating: input/train_images/181157076.jpg inflating: input/train_images/3523670880.jpg inflating: input/train_images/1300599354.jpg inflating: input/train_images/3731510435.jpg inflating: input/train_images/1956034762.jpg inflating: input/train_images/3088191583.jpg inflating: input/train_images/3052959460.jpg inflating: input/train_images/2330534234.jpg inflating: input/train_images/4188219605.jpg inflating: input/train_images/2275525608.jpg inflating: input/train_images/2577068353.jpg inflating: input/train_images/673931298.jpg inflating: input/train_images/1482562306.jpg inflating: input/train_images/2943495695.jpg inflating: input/train_images/2863474549.jpg inflating: input/train_images/1903950320.jpg inflating: input/train_images/2095589836.jpg inflating: input/train_images/4027944552.jpg inflating: input/train_images/2852147190.jpg inflating: input/train_images/4151340541.jpg inflating: input/train_images/2665470851.jpg inflating: input/train_images/3023855128.jpg inflating: input/train_images/268372107.jpg inflating: input/train_images/1997488168.jpg inflating: input/train_images/3289230042.jpg inflating: input/train_images/3389713573.jpg inflating: input/train_images/2417374571.jpg inflating: input/train_images/2274065917.jpg inflating: input/train_images/794895924.jpg inflating: input/train_images/1667727245.jpg inflating: input/train_images/4034495674.jpg inflating: input/train_images/2486687383.jpg inflating: input/train_images/3413149507.jpg inflating: input/train_images/1249688756.jpg inflating: input/train_images/3643428044.jpg inflating: input/train_images/3217927386.jpg inflating: input/train_images/1946306561.jpg inflating: input/train_images/3223218079.jpg inflating: input/train_images/2408821742.jpg inflating: input/train_images/390092040.jpg inflating: input/train_images/431535307.jpg inflating: input/train_images/2394770217.jpg inflating: input/train_images/391364557.jpg inflating: input/train_images/2840988158.jpg inflating: input/train_images/4000584857.jpg inflating: input/train_images/1397439068.jpg inflating: input/train_images/2832723542.jpg inflating: input/train_images/1904646699.jpg inflating: input/train_images/1343777320.jpg inflating: input/train_images/3850927712.jpg inflating: input/train_images/582352615.jpg inflating: input/train_images/2130379306.jpg inflating: input/train_images/3316874782.jpg inflating: input/train_images/2043115778.jpg inflating: input/train_images/1544234863.jpg inflating: input/train_images/700971789.jpg inflating: input/train_images/1442268656.jpg inflating: input/train_images/3083319765.jpg inflating: input/train_images/2179057801.jpg inflating: input/train_images/1442929249.jpg inflating: input/train_images/2098716407.jpg inflating: input/train_images/1910478563.jpg inflating: input/train_images/3638291703.jpg inflating: input/train_images/3211907814.jpg inflating: input/train_images/61492497.jpg inflating: input/train_images/1814763610.jpg inflating: input/train_images/131746797.jpg inflating: input/train_images/3656998236.jpg inflating: input/train_images/2213150889.jpg inflating: input/train_images/2291300428.jpg inflating: input/train_images/2736444451.jpg inflating: input/train_images/1681857148.jpg inflating: input/train_images/2519147193.jpg inflating: input/train_images/1185369128.jpg inflating: input/train_images/4018307313.jpg inflating: input/train_images/1987438093.jpg inflating: input/train_images/2141260400.jpg inflating: input/train_images/506080526.jpg inflating: input/train_images/3939103661.jpg inflating: input/train_images/3806878671.jpg inflating: input/train_images/925945591.jpg inflating: input/train_images/3490253996.jpg inflating: input/train_images/2916268128.jpg inflating: input/train_images/2466684931.jpg inflating: input/train_images/1348221044.jpg inflating: input/train_images/630798966.jpg inflating: input/train_images/1834263937.jpg inflating: input/train_images/1247742333.jpg inflating: input/train_images/1279535323.jpg inflating: input/train_images/760863006.jpg inflating: input/train_images/1687514090.jpg inflating: input/train_images/3141049473.jpg inflating: input/train_images/52672633.jpg inflating: input/train_images/4046910331.jpg inflating: input/train_images/3375224217.jpg inflating: input/train_images/3668854435.jpg inflating: input/train_images/518719429.jpg inflating: input/train_images/2861545981.jpg inflating: input/train_images/3883954527.jpg inflating: input/train_images/4225259568.jpg inflating: input/train_images/2967863031.jpg inflating: input/train_images/550742055.jpg inflating: input/train_images/1703538353.jpg inflating: input/train_images/717532306.jpg inflating: input/train_images/3232846318.jpg inflating: input/train_images/3863840044.jpg inflating: input/train_images/3829295052.jpg inflating: input/train_images/1756754615.jpg inflating: input/train_images/2203540560.jpg inflating: input/train_images/2694971765.jpg inflating: input/train_images/3153618395.jpg inflating: input/train_images/2869465595.jpg inflating: input/train_images/2573573471.jpg inflating: input/train_images/2498112851.jpg inflating: input/train_images/1092232758.jpg inflating: input/train_images/2240579189.jpg inflating: input/train_images/996539252.jpg inflating: input/train_images/1999438235.jpg inflating: input/train_images/2188616846.jpg inflating: input/train_images/4022980210.jpg inflating: input/train_images/1991345445.jpg inflating: input/train_images/3182540417.jpg inflating: input/train_images/216687816.jpg inflating: input/train_images/1988989222.jpg inflating: input/train_images/1645330578.jpg inflating: input/train_images/4011808410.jpg inflating: input/train_images/1075249116.jpg inflating: input/train_images/2224409184.jpg inflating: input/train_images/1357774593.jpg inflating: input/train_images/842973014.jpg inflating: input/train_images/1699816187.jpg inflating: input/train_images/3989761123.jpg inflating: input/train_images/125088495.jpg inflating: input/train_images/1050774063.jpg inflating: input/train_images/3876777651.jpg inflating: input/train_images/334728567.jpg inflating: input/train_images/4274049119.jpg inflating: input/train_images/3929446886.jpg inflating: input/train_images/807698612.jpg inflating: input/train_images/174581727.jpg inflating: input/train_images/1613918546.jpg inflating: input/train_images/382849332.jpg inflating: input/train_images/687753518.jpg inflating: input/train_images/3880993061.jpg inflating: input/train_images/775831061.jpg inflating: input/train_images/3852521.jpg inflating: input/train_images/4160459669.jpg inflating: input/train_images/857983591.jpg inflating: input/train_images/3646458335.jpg inflating: input/train_images/2458353661.jpg inflating: input/train_images/3345535790.jpg inflating: input/train_images/2823421970.jpg inflating: input/train_images/319927039.jpg inflating: input/train_images/725034194.jpg inflating: input/train_images/3088061893.jpg inflating: input/train_images/1615166642.jpg inflating: input/train_images/1133741600.jpg inflating: input/train_images/224402404.jpg inflating: input/train_images/3738228775.jpg inflating: input/train_images/3779096121.jpg inflating: input/train_images/504065374.jpg inflating: input/train_images/3094956073.jpg inflating: input/train_images/1552938679.jpg inflating: input/train_images/1421166262.jpg inflating: input/train_images/3964576371.jpg inflating: input/train_images/3057285715.jpg inflating: input/train_images/832729024.jpg inflating: input/train_images/30053778.jpg inflating: input/train_images/327801627.jpg inflating: input/train_images/208435588.jpg inflating: input/train_images/471570254.jpg inflating: input/train_images/1813365799.jpg inflating: input/train_images/1633620342.jpg inflating: input/train_images/3692116146.jpg inflating: input/train_images/2378730150.jpg inflating: input/train_images/1836597085.jpg inflating: input/train_images/235479847.jpg inflating: input/train_images/66720017.jpg inflating: input/train_images/873720819.jpg inflating: input/train_images/2753076252.jpg inflating: input/train_images/483774797.jpg inflating: input/train_images/392932902.jpg inflating: input/train_images/2821260437.jpg inflating: input/train_images/2708567457.jpg inflating: input/train_images/2101603304.jpg inflating: input/train_images/3615279906.jpg inflating: input/train_images/257033092.jpg inflating: input/train_images/2679988285.jpg inflating: input/train_images/2238082787.jpg inflating: input/train_images/817893600.jpg inflating: input/train_images/3378163527.jpg inflating: input/train_images/651331224.jpg inflating: input/train_images/832048490.jpg inflating: input/train_images/2416353814.jpg inflating: input/train_images/1527255990.jpg inflating: input/train_images/910870110.jpg inflating: input/train_images/1201098987.jpg inflating: input/train_images/180819743.jpg inflating: input/train_images/1620448232.jpg inflating: input/train_images/1568139691.jpg inflating: input/train_images/31203445.jpg inflating: input/train_images/4102201143.jpg inflating: input/train_images/3075515456.jpg inflating: input/train_images/3582059053.jpg inflating: input/train_images/315067949.jpg inflating: input/train_images/1902246685.jpg inflating: input/train_images/2047483616.jpg inflating: input/train_images/651791438.jpg inflating: input/train_images/3945098769.jpg inflating: input/train_images/1745794549.jpg inflating: input/train_images/3616264908.jpg inflating: input/train_images/1913393149.jpg inflating: input/train_images/573324267.jpg inflating: input/train_images/2170099924.jpg inflating: input/train_images/298252775.jpg inflating: input/train_images/142510693.jpg inflating: input/train_images/1389564003.jpg inflating: input/train_images/230268037.jpg inflating: input/train_images/3916490828.jpg inflating: input/train_images/997973414.jpg inflating: input/train_images/2997330474.jpg inflating: input/train_images/1670353820.jpg inflating: input/train_images/2573993718.jpg inflating: input/train_images/2834607422.jpg inflating: input/train_images/3793586140.jpg inflating: input/train_images/2510072136.jpg inflating: input/train_images/2371937835.jpg inflating: input/train_images/3578968000.jpg inflating: input/train_images/1048372814.jpg inflating: input/train_images/1070630875.jpg inflating: input/train_images/4145051602.jpg inflating: input/train_images/2806021040.jpg inflating: input/train_images/1172621803.jpg inflating: input/train_images/3755850035.jpg inflating: input/train_images/1115331699.jpg inflating: input/train_images/1591211160.jpg inflating: input/train_images/2536929613.jpg inflating: input/train_images/1973608314.jpg inflating: input/train_images/1590856402.jpg inflating: input/train_images/1313437821.jpg inflating: input/train_images/1874752223.jpg inflating: input/train_images/407043133.jpg inflating: input/train_images/3880530404.jpg inflating: input/train_images/670606517.jpg inflating: input/train_images/4188579631.jpg inflating: input/train_images/2846698529.jpg inflating: input/train_images/818188540.jpg inflating: input/train_images/2494580860.jpg inflating: input/train_images/2468056909.jpg inflating: input/train_images/1362172635.jpg inflating: input/train_images/3379826408.jpg inflating: input/train_images/3370597486.jpg inflating: input/train_images/3102370100.jpg inflating: input/train_images/4124483418.jpg inflating: input/train_images/3928691677.jpg inflating: input/train_images/1797636994.jpg inflating: input/train_images/2247014271.jpg inflating: input/train_images/1964957251.jpg inflating: input/train_images/2260330058.jpg inflating: input/train_images/2272550.jpg inflating: input/train_images/3783300400.jpg inflating: input/train_images/1082098147.jpg inflating: input/train_images/1286475043.jpg inflating: input/train_images/4255275522.jpg inflating: input/train_images/1726536780.jpg inflating: input/train_images/1340999953.jpg inflating: input/train_images/624872321.jpg inflating: input/train_images/2552592093.jpg inflating: input/train_images/1540424279.jpg inflating: input/train_images/2456930353.jpg inflating: input/train_images/3516555909.jpg inflating: input/train_images/1908512219.jpg inflating: input/train_images/2690529206.jpg inflating: input/train_images/2803815396.jpg inflating: input/train_images/1478209787.jpg inflating: input/train_images/497447638.jpg inflating: input/train_images/593922825.jpg inflating: input/train_images/2822454255.jpg inflating: input/train_images/895910836.jpg inflating: input/train_images/2073193450.jpg inflating: input/train_images/2593681769.jpg inflating: input/train_images/2479163539.jpg inflating: input/train_images/1573242622.jpg inflating: input/train_images/3229492371.jpg inflating: input/train_images/3807708050.jpg inflating: input/train_images/15196864.jpg inflating: input/train_images/3484852968.jpg inflating: input/train_images/1983523977.jpg inflating: input/train_images/710380163.jpg inflating: input/train_images/3397396466.jpg inflating: input/train_images/2195305103.jpg inflating: input/train_images/3986526512.jpg inflating: input/train_images/623023838.jpg inflating: input/train_images/1074822391.jpg inflating: input/train_images/2315459950.jpg inflating: input/train_images/434367485.jpg inflating: input/train_images/2275346369.jpg inflating: input/train_images/2370587478.jpg inflating: input/train_images/224544096.jpg inflating: input/train_images/716052378.jpg inflating: input/train_images/937960341.jpg inflating: input/train_images/759559409.jpg inflating: input/train_images/1196761091.jpg inflating: input/train_images/2198388199.jpg inflating: input/train_images/2666280615.jpg inflating: input/train_images/4060987360.jpg inflating: input/train_images/2002289812.jpg inflating: input/train_images/2169718096.jpg inflating: input/train_images/2279072182.jpg inflating: input/train_images/76754228.jpg inflating: input/train_images/3291696815.jpg inflating: input/train_images/3551024298.jpg inflating: input/train_images/1814144394.jpg inflating: input/train_images/1395467521.jpg inflating: input/train_images/2590010123.jpg inflating: input/train_images/3734809897.jpg inflating: input/train_images/851450770.jpg inflating: input/train_images/722419138.jpg inflating: input/train_images/2425413365.jpg inflating: input/train_images/4114035268.jpg inflating: input/train_images/2547653381.jpg inflating: input/train_images/179499224.jpg inflating: input/train_images/2719402606.jpg inflating: input/train_images/1959890279.jpg inflating: input/train_images/1758318062.jpg inflating: input/train_images/2704844325.jpg inflating: input/train_images/4285379899.jpg inflating: input/train_images/1391510011.jpg inflating: input/train_images/1492381879.jpg inflating: input/train_images/3486341851.jpg inflating: input/train_images/3917462304.jpg inflating: input/train_images/1569815719.jpg inflating: input/train_images/384773120.jpg inflating: input/train_images/271724485.jpg inflating: input/train_images/351189555.jpg inflating: input/train_images/3799141039.jpg inflating: input/train_images/1948579246.jpg inflating: input/train_images/226294252.jpg inflating: input/train_images/3070263575.jpg inflating: input/train_images/3162418489.jpg inflating: input/train_images/662372109.jpg inflating: input/train_images/3031971659.jpg inflating: input/train_images/1467768254.jpg inflating: input/train_images/3962684748.jpg inflating: input/train_images/599872588.jpg inflating: input/train_images/845640217.jpg inflating: input/train_images/1539638666.jpg inflating: input/train_images/2236456685.jpg inflating: input/train_images/2231604198.jpg inflating: input/train_images/19555068.jpg inflating: input/train_images/2347169881.jpg inflating: input/train_images/3961645455.jpg inflating: input/train_images/38680980.jpg inflating: input/train_images/4151371064.jpg inflating: input/train_images/1138072371.jpg inflating: input/train_images/2026618644.jpg inflating: input/train_images/2016389925.jpg inflating: input/train_images/3729595157.jpg inflating: input/train_images/2792806251.jpg inflating: input/train_images/1547490615.jpg inflating: input/train_images/4063216337.jpg inflating: input/train_images/3631359549.jpg inflating: input/train_images/3620010252.jpg inflating: input/train_images/1681772018.jpg inflating: input/train_images/731897320.jpg inflating: input/train_images/2209567923.jpg inflating: input/train_images/723805565.jpg inflating: input/train_images/634816572.jpg inflating: input/train_images/3681083835.jpg inflating: input/train_images/878720080.jpg inflating: input/train_images/1316293623.jpg inflating: input/train_images/3110572972.jpg inflating: input/train_images/3410127077.jpg inflating: input/train_images/971188113.jpg inflating: input/train_images/4254996610.jpg inflating: input/train_images/2023062288.jpg inflating: input/train_images/69026823.jpg inflating: input/train_images/1820631202.jpg inflating: input/train_images/646841236.jpg inflating: input/train_images/3083312540.jpg inflating: input/train_images/3818159518.jpg inflating: input/train_images/383656390.jpg inflating: input/train_images/2828802203.jpg inflating: input/train_images/1751029526.jpg inflating: input/train_images/1844147447.jpg inflating: input/train_images/793076912.jpg inflating: input/train_images/2382410530.jpg inflating: input/train_images/3324645534.jpg inflating: input/train_images/62070739.jpg inflating: input/train_images/2097527991.jpg inflating: input/train_images/1085931637.jpg inflating: input/train_images/1600157246.jpg inflating: input/train_images/1445131056.jpg inflating: input/train_images/639068838.jpg inflating: input/train_images/3456289388.jpg inflating: input/train_images/1117635403.jpg inflating: input/train_images/1328015019.jpg inflating: input/train_images/2286469795.jpg inflating: input/train_images/2044199243.jpg inflating: input/train_images/1581350775.jpg inflating: input/train_images/4137700702.jpg inflating: input/train_images/524188630.jpg inflating: input/train_images/3459275499.jpg inflating: input/train_images/2054130310.jpg inflating: input/train_images/3555694863.jpg inflating: input/train_images/4250668297.jpg inflating: input/train_images/532038171.jpg inflating: input/train_images/1835974960.jpg inflating: input/train_images/1794430804.jpg inflating: input/train_images/2494192748.jpg inflating: input/train_images/4052896742.jpg inflating: input/train_images/2406746609.jpg inflating: input/train_images/947208202.jpg inflating: input/train_images/3072589200.jpg inflating: input/train_images/1820335596.jpg inflating: input/train_images/713259486.jpg inflating: input/train_images/2476023220.jpg inflating: input/train_images/1019359196.jpg inflating: input/train_images/809489252.jpg inflating: input/train_images/3158054107.jpg inflating: input/train_images/3365094524.jpg inflating: input/train_images/1941569739.jpg inflating: input/train_images/4268256477.jpg inflating: input/train_images/1246560412.jpg inflating: input/train_images/678943117.jpg inflating: input/train_images/1704757491.jpg inflating: input/train_images/4184902338.jpg inflating: input/train_images/2478621909.jpg inflating: input/train_images/3954910918.jpg inflating: input/train_images/2725135519.jpg inflating: input/train_images/2848893902.jpg inflating: input/train_images/2878808214.jpg inflating: input/train_images/3888347347.jpg inflating: input/train_images/2793573567.jpg inflating: input/train_images/2823249481.jpg inflating: input/train_images/3492042850.jpg inflating: input/train_images/3780777265.jpg inflating: input/train_images/1922719796.jpg inflating: input/train_images/2204493218.jpg inflating: input/train_images/4100436529.jpg inflating: input/train_images/2661455807.jpg inflating: input/train_images/341323855.jpg inflating: input/train_images/3419650756.jpg inflating: input/train_images/3697315680.jpg inflating: input/train_images/2892268393.jpg inflating: input/train_images/3349471928.jpg inflating: input/train_images/1809996556.jpg inflating: input/train_images/1515903038.jpg inflating: input/train_images/3240849248.jpg inflating: input/train_images/1849571285.jpg inflating: input/train_images/1859104179.jpg inflating: input/train_images/3312370190.jpg inflating: input/train_images/4276437960.jpg inflating: input/train_images/1034735631.jpg inflating: input/train_images/1166984087.jpg inflating: input/train_images/1362265434.jpg inflating: input/train_images/3271313528.jpg inflating: input/train_images/1121089876.jpg inflating: input/train_images/1847003440.jpg inflating: input/train_images/3741620114.jpg inflating: input/train_images/2888884309.jpg inflating: input/train_images/2865650772.jpg inflating: input/train_images/3643755636.jpg inflating: input/train_images/562228915.jpg inflating: input/train_images/1124255421.jpg inflating: input/train_images/1138779690.jpg inflating: input/train_images/3408901143.jpg inflating: input/train_images/854627770.jpg inflating: input/train_images/699952648.jpg inflating: input/train_images/127665486.jpg inflating: input/train_images/2513639394.jpg inflating: input/train_images/2218891230.jpg inflating: input/train_images/1990169159.jpg inflating: input/train_images/1196276402.jpg inflating: input/train_images/2825142093.jpg inflating: input/train_images/1226067101.jpg inflating: input/train_images/2673180218.jpg inflating: input/train_images/126180843.jpg inflating: input/train_images/3822961101.jpg inflating: input/train_images/3089786786.jpg inflating: input/train_images/4018949072.jpg inflating: input/train_images/415127331.jpg inflating: input/train_images/2776534686.jpg inflating: input/train_images/938742634.jpg inflating: input/train_images/4006299018.jpg inflating: input/train_images/1865345123.jpg inflating: input/train_images/1595574343.jpg inflating: input/train_images/226270925.jpg inflating: input/train_images/546383916.jpg inflating: input/train_images/374033272.jpg inflating: input/train_images/2444460528.jpg inflating: input/train_images/3878495459.jpg inflating: input/train_images/2409113043.jpg inflating: input/train_images/3795384573.jpg inflating: input/train_images/879089403.jpg inflating: input/train_images/2916471006.jpg inflating: input/train_images/2552409953.jpg inflating: input/train_images/3772118108.jpg inflating: input/train_images/3177907789.jpg inflating: input/train_images/1993464761.jpg inflating: input/train_images/699893195.jpg inflating: input/train_images/3034275498.jpg inflating: input/train_images/1640734047.jpg inflating: input/train_images/2828723686.jpg inflating: input/train_images/2324206704.jpg inflating: input/train_images/3465555642.jpg inflating: input/train_images/3222591815.jpg inflating: input/train_images/4287278405.jpg inflating: input/train_images/3971124978.jpg inflating: input/train_images/352708690.jpg inflating: input/train_images/2285402273.jpg inflating: input/train_images/1036302176.jpg inflating: input/train_images/2792323624.jpg inflating: input/train_images/787914923.jpg inflating: input/train_images/1904073700.jpg inflating: input/train_images/830740908.jpg inflating: input/train_images/4291622548.jpg inflating: input/train_images/1409426378.jpg inflating: input/train_images/696072814.jpg inflating: input/train_images/3943400574.jpg inflating: input/train_images/1504494469.jpg inflating: input/train_images/363497551.jpg inflating: input/train_images/3335254269.jpg inflating: input/train_images/4237476054.jpg inflating: input/train_images/2988461706.jpg inflating: input/train_images/520992069.jpg inflating: input/train_images/4186528669.jpg inflating: input/train_images/4224255718.jpg inflating: input/train_images/1617011317.jpg inflating: input/train_images/4174034867.jpg inflating: input/train_images/1178339881.jpg inflating: input/train_images/1119747653.jpg inflating: input/train_images/1315797481.jpg inflating: input/train_images/3943173652.jpg inflating: input/train_images/1012755275.jpg inflating: input/train_images/712756334.jpg inflating: input/train_images/2778033959.jpg inflating: input/train_images/1343457656.jpg inflating: input/train_images/1124029406.jpg inflating: input/train_images/3330242957.jpg inflating: input/train_images/3140977512.jpg inflating: input/train_images/3689683022.jpg inflating: input/train_images/3732011479.jpg inflating: input/train_images/4248150807.jpg inflating: input/train_images/3738494351.jpg inflating: input/train_images/3227667303.jpg inflating: input/train_images/1240563843.jpg inflating: input/train_images/4250119562.jpg inflating: input/train_images/1852697554.jpg inflating: input/train_images/3107549236.jpg inflating: input/train_images/188217517.jpg inflating: input/train_images/913294875.jpg inflating: input/train_images/3013103054.jpg inflating: input/train_images/2810410846.jpg inflating: input/train_images/2936136374.jpg inflating: input/train_images/2053079432.jpg inflating: input/train_images/1628667516.jpg inflating: input/train_images/172123475.jpg inflating: input/train_images/4785038.jpg inflating: input/train_images/1830680184.jpg inflating: input/train_images/1438970432.jpg inflating: input/train_images/618683385.jpg inflating: input/train_images/3495835530.jpg inflating: input/train_images/2742838328.jpg inflating: input/train_images/1791690921.jpg inflating: input/train_images/258351073.jpg inflating: input/train_images/1260451249.jpg inflating: input/train_images/49247184.jpg inflating: input/train_images/1509840012.jpg inflating: input/train_images/3245080798.jpg inflating: input/train_images/2512000919.jpg inflating: input/train_images/443211656.jpg inflating: input/train_images/1270179035.jpg inflating: input/train_images/2399292310.jpg inflating: input/train_images/948363257.jpg inflating: input/train_images/223143311.jpg inflating: input/train_images/3432358469.jpg inflating: input/train_images/3152994734.jpg inflating: input/train_images/2799109400.jpg inflating: input/train_images/1000015157.jpg inflating: input/train_images/3719761839.jpg inflating: input/train_images/644212609.jpg inflating: input/train_images/3321411338.jpg inflating: input/train_images/2602727826.jpg inflating: input/train_images/2143941183.jpg inflating: input/train_images/317345345.jpg inflating: input/train_images/850170128.jpg inflating: input/train_images/2504965655.jpg inflating: input/train_images/266508251.jpg inflating: input/train_images/46087551.jpg inflating: input/train_images/2499466480.jpg inflating: input/train_images/2203128362.jpg inflating: input/train_images/2167218965.jpg inflating: input/train_images/297361079.jpg inflating: input/train_images/1312051349.jpg inflating: input/train_images/858147094.jpg inflating: input/train_images/718324300.jpg inflating: input/train_images/3952521277.jpg inflating: input/train_images/1458175598.jpg inflating: input/train_images/22205792.jpg inflating: input/train_images/3454506248.jpg inflating: input/train_images/2325593465.jpg inflating: input/train_images/1333145781.jpg inflating: input/train_images/3927863529.jpg inflating: input/train_images/2478144118.jpg inflating: input/train_images/4267085223.jpg inflating: input/train_images/2724038983.jpg inflating: input/train_images/4283076582.jpg inflating: input/train_images/445689900.jpg inflating: input/train_images/343243475.jpg inflating: input/train_images/1138949936.jpg inflating: input/train_images/1367882980.jpg inflating: input/train_images/2539159693.jpg inflating: input/train_images/2949246528.jpg inflating: input/train_images/259935954.jpg inflating: input/train_images/1241954880.jpg inflating: input/train_images/2580494027.jpg inflating: input/train_images/1364893627.jpg inflating: input/train_images/3318985729.jpg inflating: input/train_images/1313344197.jpg inflating: input/train_images/2181259401.jpg inflating: input/train_images/1826588021.jpg inflating: input/train_images/218377.jpg inflating: input/train_images/4166830303.jpg inflating: input/train_images/1242632379.jpg inflating: input/train_images/292358670.jpg inflating: input/train_images/657935270.jpg inflating: input/train_images/1795774689.jpg inflating: input/train_images/3421593064.jpg inflating: input/train_images/3010385016.jpg inflating: input/train_images/3462014192.jpg inflating: input/train_images/678699468.jpg inflating: input/train_images/3174223236.jpg inflating: input/train_images/881020012.jpg inflating: input/train_images/3493200468.jpg inflating: input/train_images/1272204314.jpg inflating: input/train_images/3432135920.jpg inflating: input/train_images/984417293.jpg inflating: input/train_images/71842711.jpg inflating: input/train_images/1206126822.jpg inflating: input/train_images/3474960927.jpg inflating: input/train_images/3395550776.jpg inflating: input/train_images/2182247433.jpg inflating: input/train_images/2655690235.jpg inflating: input/train_images/3384690676.jpg inflating: input/train_images/2944007610.jpg inflating: input/train_images/2102230404.jpg inflating: input/train_images/1256156533.jpg inflating: input/train_images/3540765435.jpg inflating: input/train_images/2974027386.jpg inflating: input/train_images/1445981750.jpg inflating: input/train_images/4278290945.jpg inflating: input/train_images/2736688100.jpg inflating: input/train_images/737465791.jpg inflating: input/train_images/2321781860.jpg inflating: input/train_images/2335461038.jpg inflating: input/train_images/3568729258.jpg inflating: input/train_images/3198558728.jpg inflating: input/train_images/223775564.jpg inflating: input/train_images/811696349.jpg inflating: input/train_images/665859596.jpg inflating: input/train_images/3563733619.jpg inflating: input/train_images/3196839385.jpg inflating: input/train_images/4151543321.jpg inflating: input/train_images/3026867163.jpg inflating: input/train_images/1887102374.jpg inflating: input/train_images/2828087857.jpg inflating: input/train_images/3115800767.jpg inflating: input/train_images/3171295117.jpg inflating: input/train_images/3826378692.jpg inflating: input/train_images/471759171.jpg inflating: input/train_images/4021120982.jpg inflating: input/train_images/2532502018.jpg inflating: input/train_images/2216672463.jpg inflating: input/train_images/630537916.jpg inflating: input/train_images/3808548941.jpg inflating: input/train_images/2900265052.jpg inflating: input/train_images/3815339672.jpg inflating: input/train_images/1654496299.jpg inflating: input/train_images/2016922102.jpg inflating: input/train_images/3476129770.jpg inflating: input/train_images/2629547729.jpg inflating: input/train_images/3251222806.jpg inflating: input/train_images/1202619622.jpg inflating: input/train_images/3116602626.jpg inflating: input/train_images/955110808.jpg inflating: input/train_images/3226850517.jpg inflating: input/train_images/138459723.jpg inflating: input/train_images/2379208411.jpg inflating: input/train_images/1058466257.jpg inflating: input/train_images/3699018572.jpg inflating: input/train_images/491516744.jpg inflating: input/train_images/2360034731.jpg inflating: input/train_images/1109535439.jpg inflating: input/train_images/1906662889.jpg inflating: input/train_images/685497354.jpg inflating: input/train_images/3182178940.jpg inflating: input/train_images/1196683812.jpg inflating: input/train_images/3923826368.jpg inflating: input/train_images/353529214.jpg inflating: input/train_images/2492261561.jpg inflating: input/train_images/3047244862.jpg inflating: input/train_images/701939948.jpg inflating: input/train_images/3536918233.jpg inflating: input/train_images/230708644.jpg inflating: input/train_images/3558210232.jpg inflating: input/train_images/454637792.jpg inflating: input/train_images/1679058349.jpg inflating: input/train_images/2626785894.jpg inflating: input/train_images/3452368233.jpg inflating: input/train_images/1391911669.jpg inflating: input/train_images/3963194620.jpg inflating: input/train_images/3430083704.jpg inflating: input/train_images/1903454403.jpg inflating: input/train_images/3704646396.jpg inflating: input/train_images/79165028.jpg inflating: input/train_images/124731659.jpg inflating: input/train_images/318227226.jpg inflating: input/train_images/2903757445.jpg inflating: input/train_images/281473459.jpg inflating: input/train_images/2040980180.jpg inflating: input/train_images/2523040233.jpg inflating: input/train_images/986387276.jpg inflating: input/train_images/95322868.jpg inflating: input/train_images/2187520505.jpg inflating: input/train_images/4165383936.jpg inflating: input/train_images/3366388775.jpg inflating: input/train_images/1149366109.jpg inflating: input/train_images/1711803773.jpg inflating: input/train_images/3619872017.jpg inflating: input/train_images/2087904046.jpg inflating: input/train_images/1823518467.jpg inflating: input/train_images/2853557444.jpg inflating: input/train_images/4077418003.jpg inflating: input/train_images/4156520758.jpg inflating: input/train_images/2871112358.jpg inflating: input/train_images/544532198.jpg inflating: input/train_images/1524851298.jpg inflating: input/train_images/2079191755.jpg inflating: input/train_images/2784153881.jpg inflating: input/train_images/1870791731.jpg inflating: input/train_images/284130814.jpg inflating: input/train_images/3842835147.jpg inflating: input/train_images/1550131198.jpg inflating: input/train_images/488621358.jpg inflating: input/train_images/107179104.jpg inflating: input/train_images/1648797663.jpg inflating: input/train_images/1716516140.jpg inflating: input/train_images/3983622976.jpg inflating: input/train_images/4237027288.jpg inflating: input/train_images/3163389622.jpg inflating: input/train_images/2415642544.jpg inflating: input/train_images/1708593214.jpg inflating: input/train_images/1074804892.jpg inflating: input/train_images/2598383245.jpg inflating: input/train_images/1966479162.jpg inflating: input/train_images/1176036516.jpg inflating: input/train_images/670049521.jpg inflating: input/train_images/1011571614.jpg inflating: input/train_images/1556372049.jpg inflating: input/train_images/1662332092.jpg inflating: input/train_images/1788421624.jpg inflating: input/train_images/1182166221.jpg inflating: input/train_images/1098348421.jpg inflating: input/train_images/2314598518.jpg inflating: input/train_images/410771727.jpg inflating: input/train_images/288071387.jpg inflating: input/train_images/3030866180.jpg inflating: input/train_images/3190228731.jpg inflating: input/train_images/2243019094.jpg inflating: input/train_images/2373222201.jpg inflating: input/train_images/1682355627.jpg inflating: input/train_images/1983716706.jpg inflating: input/train_images/2497722314.jpg inflating: input/train_images/1437139355.jpg inflating: input/train_images/3491035063.jpg inflating: input/train_images/3314463308.jpg inflating: input/train_images/2037654079.jpg inflating: input/train_images/2597522280.jpg inflating: input/train_images/2642218624.jpg inflating: input/train_images/2003778001.jpg inflating: input/train_images/1630104012.jpg inflating: input/train_images/2235231408.jpg inflating: input/train_images/2884334007.jpg inflating: input/train_images/3007566713.jpg inflating: input/train_images/4179303014.jpg inflating: input/train_images/1934675446.jpg inflating: input/train_images/632445353.jpg inflating: input/train_images/2489013604.jpg inflating: input/train_images/340856242.jpg inflating: input/train_images/1178737001.jpg inflating: input/train_images/135225385.jpg inflating: input/train_images/3508055707.jpg inflating: input/train_images/3474174991.jpg inflating: input/train_images/3608785177.jpg inflating: input/train_images/3002089936.jpg inflating: input/train_images/2892596636.jpg inflating: input/train_images/4267879183.jpg inflating: input/train_images/1427678310.jpg inflating: input/train_images/1221540590.jpg inflating: input/train_images/1316234196.jpg inflating: input/train_images/879395678.jpg inflating: input/train_images/3676902854.jpg inflating: input/train_images/2608690004.jpg inflating: input/train_images/1846294489.jpg inflating: input/train_images/959693086.jpg inflating: input/train_images/2451619030.jpg inflating: input/train_images/307854780.jpg inflating: input/train_images/2585623036.jpg inflating: input/train_images/3277846362.jpg inflating: input/train_images/4037735151.jpg inflating: input/train_images/255761886.jpg inflating: input/train_images/3795252251.jpg inflating: input/train_images/2474023641.jpg inflating: input/train_images/1185052767.jpg inflating: input/train_images/3550628898.jpg inflating: input/train_images/2187563548.jpg inflating: input/train_images/2525317901.jpg inflating: input/train_images/331060034.jpg inflating: input/train_images/1864756253.jpg inflating: input/train_images/838136657.jpg inflating: input/train_images/1902258647.jpg inflating: input/train_images/2026837055.jpg inflating: input/train_images/1447520990.jpg inflating: input/train_images/4178594597.jpg inflating: input/train_images/3537514783.jpg inflating: input/train_images/872867609.jpg inflating: input/train_images/316457574.jpg inflating: input/train_images/2997262447.jpg inflating: input/train_images/3276323574.jpg inflating: input/train_images/1791700029.jpg inflating: input/train_images/2447058144.jpg inflating: input/train_images/1918762654.jpg inflating: input/train_images/1128373288.jpg inflating: input/train_images/524234621.jpg inflating: input/train_images/792990285.jpg inflating: input/train_images/474493920.jpg inflating: input/train_images/1741717414.jpg inflating: input/train_images/2987785704.jpg inflating: input/train_images/340679528.jpg inflating: input/train_images/2853469251.jpg inflating: input/train_images/1252338072.jpg inflating: input/train_images/4273998923.jpg inflating: input/train_images/343990809.jpg inflating: input/train_images/871044756.jpg inflating: input/train_images/3295247232.jpg inflating: input/train_images/3135970412.jpg inflating: input/train_images/3021177990.jpg inflating: input/train_images/2648357013.jpg inflating: input/train_images/2130483498.jpg inflating: input/train_images/736957194.jpg inflating: input/train_images/3801909688.jpg inflating: input/train_images/1017667711.jpg inflating: input/train_images/2361236588.jpg inflating: input/train_images/2889971119.jpg inflating: input/train_images/1232852695.jpg inflating: input/train_images/294829234.jpg inflating: input/train_images/847946899.jpg inflating: input/train_images/450239051.jpg inflating: input/train_images/2120170838.jpg inflating: input/train_images/270643654.jpg inflating: input/train_images/3340101218.jpg inflating: input/train_images/1784432938.jpg inflating: input/train_images/2618441199.jpg inflating: input/train_images/606006336.jpg inflating: input/train_images/2051128435.jpg inflating: input/train_images/1109418037.jpg inflating: input/train_images/3031879144.jpg inflating: input/train_images/4126193524.jpg inflating: input/train_images/2190685942.jpg inflating: input/train_images/3779623554.jpg inflating: input/train_images/1150322026.jpg inflating: input/train_images/1633537888.jpg inflating: input/train_images/4155925395.jpg inflating: input/train_images/3369161144.jpg inflating: input/train_images/4239036041.jpg inflating: input/train_images/59208991.jpg inflating: input/train_images/3720115396.jpg inflating: input/train_images/782478171.jpg inflating: input/train_images/2882347147.jpg inflating: input/train_images/3160420933.jpg inflating: input/train_images/2435051665.jpg inflating: input/train_images/2032441634.jpg inflating: input/train_images/2847345267.jpg inflating: input/train_images/60094859.jpg inflating: input/train_images/3837457616.jpg inflating: input/train_images/4291020124.jpg inflating: input/train_images/673860639.jpg inflating: input/train_images/3982368414.jpg inflating: input/train_images/4123940124.jpg inflating: input/train_images/1881799608.jpg inflating: input/train_images/560592460.jpg inflating: input/train_images/1393861868.jpg inflating: input/train_images/428725949.jpg inflating: input/train_images/2579865055.jpg inflating: input/train_images/2202207984.jpg inflating: input/train_images/730431773.jpg inflating: input/train_images/3971597689.jpg inflating: input/train_images/4107485206.jpg inflating: input/train_images/248855703.jpg extracting: input/sample_submission.csv ###Markdown install apex ###Code if CFG['apex']: try: import apex except Exception: ! git clone https://github.com/NVIDIA/apex.git % cd apex !pip install --no-cache-dir --global-option="--cpp_ext" --global-option="--cuda_ext" . %cd .. ###Output _____no_output_____ ###Markdown Library ###Code # ==================================================== # Library # ==================================================== import os import datetime import math import time import random import glob import shutil from pathlib import Path from contextlib import contextmanager from collections import defaultdict, Counter import scipy as sp import numpy as np import pandas as pd from matplotlib import pyplot as plt import seaborn as sns from sklearn import preprocessing from sklearn.metrics import accuracy_score from sklearn.model_selection import StratifiedKFold from tqdm.auto import tqdm from functools import partial import cv2 from PIL import Image import torch import torch.nn as nn import torch.nn.functional as F from torch.optim import Adam, SGD import torchvision.models as models from torch.nn.parameter import Parameter from torch.utils.data import DataLoader, Dataset from torch.optim.lr_scheduler import CosineAnnealingWarmRestarts, CosineAnnealingLR, ReduceLROnPlateau from albumentations import ( Compose, OneOf, Normalize, Resize, RandomResizedCrop, RandomCrop, HorizontalFlip, VerticalFlip, RandomBrightness, RandomContrast, RandomBrightnessContrast, Rotate, ShiftScaleRotate, Cutout, IAAAdditiveGaussianNoise, Transpose ) from albumentations.pytorch import ToTensorV2 from albumentations import ImageOnlyTransform import timm import mlflow import warnings warnings.filterwarnings('ignore') if CFG['apex']: from apex import amp if CFG['debug']: device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') else: device = torch.device('cuda') start_time = datetime.datetime.now() start_time_str = start_time.strftime('%m%d%H%M') ###Output _____no_output_____ ###Markdown Directory settings ###Code # ==================================================== # Directory settings # ==================================================== if os.path.exists(OUTPUT_DIR): shutil.rmtree(OUTPUT_DIR) if not os.path.exists(OUTPUT_DIR): os.makedirs(OUTPUT_DIR) ###Output _____no_output_____ ###Markdown save basic files ###Code # with open(f'{OUTPUT_DIR}/{start_time_str}_TAG.json', 'w') as f: # json.dump(TAG, f, indent=4) # with open(f'{OUTPUT_DIR}/{start_time_str}_CFG.json', 'w') as f: # json.dump(CFG, f, indent=4) import shutil notebook_path = f'{OUTPUT_DIR}/{start_time_str}_{TITLE}.ipynb' shutil.copy2(NOTEBOOK_PATH, notebook_path) ###Output _____no_output_____ ###Markdown Data Loading ###Code train = pd.read_csv(f'{DATA_PATH}/train.csv') test = pd.read_csv(f'{DATA_PATH}/sample_submission.csv') label_map = pd.read_json(f'{DATA_PATH}/label_num_to_disease_map.json', orient='index') if CFG['debug']: train = train.sample(n=1000, random_state=CFG['seed']).reset_index(drop=True) ###Output _____no_output_____ ###Markdown Utils ###Code # ==================================================== # Utils # ==================================================== def get_score(y_true, y_pred): return accuracy_score(y_true, y_pred) @contextmanager def timer(name): t0 = time.time() LOGGER.info(f'[{name}] start') yield LOGGER.info(f'[{name}] done in {time.time() - t0:.0f} s.') def init_logger(log_file=OUTPUT_DIR+'train.log'): from logging import getLogger, FileHandler, Formatter, StreamHandler from logging import INFO as INFO_ logger = getLogger(__name__) logger.setLevel(INFO_) handler1 = StreamHandler() handler1.setFormatter(Formatter("%(message)s")) handler2 = FileHandler(filename=log_file) handler2.setFormatter(Formatter("%(message)s")) logger.addHandler(handler1) logger.addHandler(handler2) return logger logger_path = OUTPUT_DIR+f'{start_time_str}_train.log' LOGGER = init_logger(logger_path) def seed_torch(seed=42): 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_torch(seed=CFG['seed']) class EarlyStopping: """Early stops the training if validation loss doesn't improve after a given patience.""" def __init__(self, patience=7, verbose=False, save_path='checkpoint.pt', counter=0, best_score=None, save_latest_path=None): """ Args: patience (int): How long to wait after last time validation loss improved. Default: 7 verbose (bool): If True, prints a message for each validation loss improvement. Default: False save_path (str): Directory for saving a model. Default: "'checkpoint.pt'" """ self.patience = patience self.verbose = verbose self.save_path = save_path self.counter = counter self.best_score = best_score self.save_latest_path = save_latest_path self.early_stop = False self.val_loss_min = np.Inf def __call__(self, val_loss, model, preds, epoch): score = -val_loss if self.best_score is None: self.best_score = score self.save_checkpoint(val_loss, model, preds, epoch) self.save_latest(val_loss, model, preds, epoch, score) elif score >= self.best_score: self.counter = 0 self.best_score = score self.save_checkpoint(val_loss, model, preds, epoch) self.save_latest(val_loss, model, preds, epoch, score) # nanになったら学習ストップ elif math.isnan(score): self.early_stop = True else: self.counter += 1 if self.save_latest_path is not None: self.save_latest(val_loss, model, preds, epoch, score) if self.verbose: print(f'EarlyStopping counter: {self.counter} out of {self.patience}') if self.counter >= self.patience: self.early_stop = True def save_checkpoint(self, val_loss, model, preds, epoch): '''Saves model when validation loss decrease.''' if self.verbose: print(f'Validation loss decreased ({self.val_loss_min:.10f} --> {val_loss:.10f}). Saving model ...') torch.save({'model': model.state_dict(), 'preds': preds, 'epoch' : epoch, 'best_score' : self.best_score, 'counter' : self.counter}, self.save_path) self.val_loss_min = val_loss def save_latest(self, val_loss, model, preds, epoch, score): '''Saves latest model.''' torch.save({'model': model.state_dict(), 'preds': preds, 'epoch' : epoch, 'score' : score, 'counter' : self.counter}, self.save_latest_path) self.val_loss_min = val_loss def remove_glob(pathname, recursive=True): for p in glob.glob(pathname, recursive=recursive): if os.path.isfile(p): os.remove(p) ###Output _____no_output_____ ###Markdown CV split ###Code folds = train.copy() Fold = StratifiedKFold(n_splits=CFG['n_fold'], shuffle=True, random_state=CFG['seed']) for n, (train_index, val_index) in enumerate(Fold.split(folds, folds[CFG['target_col']])): folds.loc[val_index, 'fold'] = int(n) folds['fold'] = folds['fold'].astype(int) print(folds.groupby(['fold', CFG['target_col']]).size()) ###Output fold label 0 0 218 1 438 2 477 3 2631 4 516 1 0 218 1 438 2 477 3 2631 4 516 2 0 217 1 438 2 477 3 2632 4 515 3 0 217 1 438 2 477 3 2632 4 515 4 0 217 1 437 2 478 3 2632 4 515 dtype: int64 ###Markdown Dataset ###Code # ==================================================== # Dataset # ==================================================== class TrainDataset(Dataset): def __init__(self, df, transform=None): self.df = df self.file_names = df['image_id'].values self.labels = df['label'].values self.transform = transform def __len__(self): return len(self.df) def __getitem__(self, idx): file_name = self.file_names[idx] file_path = f'{DATA_PATH}/train_images/{file_name}' image = cv2.imread(file_path) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) if self.transform: augmented = self.transform(image=image) image = augmented['image'] label = torch.tensor(self.labels[idx]).long() return image, label class TestDataset(Dataset): def __init__(self, df, transform=None): self.df = df self.file_names = df['image_id'].values self.transform = transform def __len__(self): return len(self.df) def __getitem__(self, idx): file_name = self.file_names[idx] file_path = f'{DATA_PATH}/test_images/{file_name}' image = cv2.imread(file_path) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) if self.transform: augmented = self.transform(image=image) image = augmented['image'] return image # train_dataset = TrainDataset(train, transform=None) # for i in range(1): # image, label = train_dataset[i] # plt.imshow(image) # plt.title(f'label: {label}') # plt.show() ###Output _____no_output_____ ###Markdown Transforms ###Code def _get_augmentations(aug_list): process = [] for aug in aug_list: if aug == 'Resize': process.append(Resize(CFG['size'], CFG['size'])) elif aug == 'RandomResizedCrop': process.append(RandomResizedCrop(CFG['size'], CFG['size'])) elif aug == 'Transpose': process.append(Transpose(p=0.5)) elif aug == 'HorizontalFlip': process.append(HorizontalFlip(p=0.5)) elif aug == 'VerticalFlip': process.append(VerticalFlip(p=0.5)) elif aug == 'ShiftScaleRotate': process.append(ShiftScaleRotate(p=0.5)) elif aug == 'Cutout': process.append(Cutout(max_h_size=CFG['CutoutSize'], max_w_size=CFG['CutoutSize'], p=0.5)) elif aug == 'Normalize': process.append(Normalize( mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225], )) else: raise ValueError(f'{aug} is not suitable') process.append(ToTensorV2()) return process # ==================================================== # Transforms # ==================================================== def get_transforms(*, data): if data == 'train': return Compose( _get_augmentations(TAG['augmentation']) ) elif data == 'valid': return Compose( _get_augmentations(['Resize', 'Normalize']) ) train_dataset = TrainDataset(train, transform=get_transforms(data='train')) for i in range(1): image, label = train_dataset[i] plt.imshow(image[0]) plt.title(f'label: {label}') plt.show() ###Output _____no_output_____ ###Markdown Bi-tempered logistic loss ###Code def log_t(u, t): """Compute log_t for `u'.""" if t==1.0: return u.log() else: return (u.pow(1.0 - t) - 1.0) / (1.0 - t) def exp_t(u, t): """Compute exp_t for `u'.""" if t==1: return u.exp() else: return (1.0 + (1.0-t)*u).relu().pow(1.0 / (1.0 - t)) def compute_normalization_fixed_point(activations, t, num_iters): """Returns the normalization value for each example (t > 1.0). Args: activations: A multi-dimensional tensor with last dimension `num_classes`. t: Temperature 2 (> 1.0 for tail heaviness). num_iters: Number of iterations to run the method. Return: A tensor of same shape as activation with the last dimension being 1. """ mu, _ = torch.max(activations, -1, keepdim=True) normalized_activations_step_0 = activations - mu normalized_activations = normalized_activations_step_0 for _ in range(num_iters): logt_partition = torch.sum( exp_t(normalized_activations, t), -1, keepdim=True) normalized_activations = normalized_activations_step_0 * \ logt_partition.pow(1.0-t) logt_partition = torch.sum( exp_t(normalized_activations, t), -1, keepdim=True) normalization_constants = - log_t(1.0 / logt_partition, t) + mu return normalization_constants def compute_normalization_binary_search(activations, t, num_iters): """Returns the normalization value for each example (t < 1.0). Args: activations: A multi-dimensional tensor with last dimension `num_classes`. t: Temperature 2 (< 1.0 for finite support). num_iters: Number of iterations to run the method. Return: A tensor of same rank as activation with the last dimension being 1. """ mu, _ = torch.max(activations, -1, keepdim=True) normalized_activations = activations - mu effective_dim = \ torch.sum( (normalized_activations > -1.0 / (1.0-t)).to(torch.int32), dim=-1, keepdim=True).to(activations.dtype) shape_partition = activations.shape[:-1] + (1,) lower = torch.zeros(shape_partition, dtype=activations.dtype, device=activations.device) upper = -log_t(1.0/effective_dim, t) * torch.ones_like(lower) for _ in range(num_iters): logt_partition = (upper + lower)/2.0 sum_probs = torch.sum( exp_t(normalized_activations - logt_partition, t), dim=-1, keepdim=True) update = (sum_probs < 1.0).to(activations.dtype) lower = torch.reshape( lower * update + (1.0-update) * logt_partition, shape_partition) upper = torch.reshape( upper * (1.0 - update) + update * logt_partition, shape_partition) logt_partition = (upper + lower)/2.0 return logt_partition + mu class ComputeNormalization(torch.autograd.Function): """ Class implementing custom backward pass for compute_normalization. See compute_normalization. """ @staticmethod def forward(ctx, activations, t, num_iters): if t < 1.0: normalization_constants = compute_normalization_binary_search(activations, t, num_iters) else: normalization_constants = compute_normalization_fixed_point(activations, t, num_iters) ctx.save_for_backward(activations, normalization_constants) ctx.t=t return normalization_constants @staticmethod def backward(ctx, grad_output): activations, normalization_constants = ctx.saved_tensors t = ctx.t normalized_activations = activations - normalization_constants probabilities = exp_t(normalized_activations, t) escorts = probabilities.pow(t) escorts = escorts / escorts.sum(dim=-1, keepdim=True) grad_input = escorts * grad_output return grad_input, None, None def compute_normalization(activations, t, num_iters=5): """Returns the normalization value for each example. Backward pass is implemented. Args: activations: A multi-dimensional tensor with last dimension `num_classes`. t: Temperature 2 (> 1.0 for tail heaviness, < 1.0 for finite support). num_iters: Number of iterations to run the method. Return: A tensor of same rank as activation with the last dimension being 1. """ return ComputeNormalization.apply(activations, t, num_iters) def tempered_sigmoid(activations, t, num_iters = 5): """Tempered sigmoid function. Args: activations: Activations for the positive class for binary classification. t: Temperature tensor > 0.0. num_iters: Number of iterations to run the method. Returns: A probabilities tensor. """ internal_activations = torch.stack([activations, torch.zeros_like(activations)], dim=-1) internal_probabilities = tempered_softmax(internal_activations, t, num_iters) return internal_probabilities[..., 0] def tempered_softmax(activations, t, num_iters=5): """Tempered softmax function. Args: activations: A multi-dimensional tensor with last dimension `num_classes`. t: Temperature > 1.0. num_iters: Number of iterations to run the method. Returns: A probabilities tensor. """ if t == 1.0: return activations.softmax(dim=-1) normalization_constants = compute_normalization(activations, t, num_iters) return exp_t(activations - normalization_constants, t) def bi_tempered_binary_logistic_loss(activations, labels, t1, t2, label_smoothing = 0.0, num_iters=5, reduction='mean'): """Bi-Tempered binary logistic loss. Args: activations: A tensor containing activations for class 1. labels: A tensor with shape as activations, containing probabilities for class 1 t1: Temperature 1 (< 1.0 for boundedness). t2: Temperature 2 (> 1.0 for tail heaviness, < 1.0 for finite support). label_smoothing: Label smoothing num_iters: Number of iterations to run the method. Returns: A loss tensor. """ internal_activations = torch.stack([activations, torch.zeros_like(activations)], dim=-1) internal_labels = torch.stack([labels.to(activations.dtype), 1.0 - labels.to(activations.dtype)], dim=-1) return bi_tempered_logistic_loss(internal_activations, internal_labels, t1, t2, label_smoothing = label_smoothing, num_iters = num_iters, reduction = reduction) def bi_tempered_logistic_loss(activations, labels, t1, t2, label_smoothing=0.0, num_iters=5, reduction = 'mean'): """Bi-Tempered Logistic Loss. Args: activations: A multi-dimensional tensor with last dimension `num_classes`. labels: A tensor with shape and dtype as activations (onehot), or a long tensor of one dimension less than activations (pytorch standard) t1: Temperature 1 (< 1.0 for boundedness). t2: Temperature 2 (> 1.0 for tail heaviness, < 1.0 for finite support). label_smoothing: Label smoothing parameter between [0, 1). Default 0.0. num_iters: Number of iterations to run the method. Default 5. reduction: ``'none'`` | ``'mean'`` | ``'sum'``. Default ``'mean'``. ``'none'``: No reduction is applied, return shape is shape of activations without the last dimension. ``'mean'``: Loss is averaged over minibatch. Return shape (1,) ``'sum'``: Loss is summed over minibatch. Return shape (1,) Returns: A loss tensor. """ if len(labels.shape)<len(activations.shape): #not one-hot labels_onehot = torch.zeros_like(activations) labels_onehot.scatter_(1, labels[..., None], 1) else: labels_onehot = labels if label_smoothing > 0: num_classes = labels_onehot.shape[-1] labels_onehot = ( 1 - label_smoothing * num_classes / (num_classes - 1) ) \ * labels_onehot + \ label_smoothing / (num_classes - 1) probabilities = tempered_softmax(activations, t2, num_iters) loss_values = labels_onehot * log_t(labels_onehot + 1e-10, t1) \ - labels_onehot * log_t(probabilities, t1) \ - labels_onehot.pow(2.0 - t1) / (2.0 - t1) \ + probabilities.pow(2.0 - t1) / (2.0 - t1) loss_values = loss_values.sum(dim = -1) #sum over classes if reduction == 'none': return loss_values if reduction == 'sum': return loss_values.sum() if reduction == 'mean': return loss_values.mean() ###Output _____no_output_____ ###Markdown MODEL ###Code # ==================================================== # MODEL # ==================================================== class CustomModel(nn.Module): def __init__(self, model_name, pretrained=False): super().__init__() self.model = timm.create_model(model_name, pretrained=pretrained) if hasattr(self.model, 'classifier'): n_features = self.model.classifier.in_features self.model.classifier = nn.Linear(n_features, CFG['target_size']) elif hasattr(self.model, 'fc'): n_features = self.model.fc.in_features self.model.fc = nn.Linear(n_features, CFG['target_size']) def forward(self, x): x = self.model(x) return x model = CustomModel(model_name=TAG['model_name'], pretrained=False) train_dataset = TrainDataset(train, transform=get_transforms(data='train')) train_loader = DataLoader(train_dataset, batch_size=4, shuffle=True, num_workers=4, pin_memory=True, drop_last=True) for image, label in train_loader: output = model(image) print(output) break ###Output tensor([[ 0.1053, 0.0638, -0.0791, -0.0618, 0.1788], [ 0.2584, -0.0821, 0.0660, -0.1673, 0.5926], [-0.1389, 0.0700, -0.0451, -0.0245, -0.0411], [-0.0775, 0.0708, -0.0659, -0.0337, 0.0190]], grad_fn=<AddmmBackward>) ###Markdown Helper functions ###Code # ==================================================== # Helper functions # ==================================================== class AverageMeter(object): """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count def asMinutes(s): m = math.floor(s / 60) s -= m * 60 return '%dm %ds' % (m, s) def timeSince(since, percent): now = time.time() s = now - since es = s / (percent) rs = es - s return '%s (remain %s)' % (asMinutes(s), asMinutes(rs)) # ==================================================== # loss # ==================================================== def get_loss(criterion, y_preds, labels): if TAG['criterion']=='CrossEntropyLoss': loss = criterion(y_preds, labels) elif TAG['criterion'] == 'bi_tempered_logistic_loss': loss = criterion(y_preds, labels, t1=CFG['bi_tempered_loss_t1'], t2=CFG['bi_tempered_loss_t2']) return loss # ==================================================== # Helper functions # ==================================================== def train_fn(train_loader, model, criterion, optimizer, epoch, scheduler, device): batch_time = AverageMeter() data_time = AverageMeter() losses = AverageMeter() scores = AverageMeter() # switch to train mode model.train() start = end = time.time() global_step = 0 for step, (images, labels) in enumerate(train_loader): # measure data loading time data_time.update(time.time() - end) images = images.to(device) labels = labels.to(device) batch_size = labels.size(0) y_preds = model(images) loss = get_loss(criterion, y_preds, labels) # record loss losses.update(loss.item(), batch_size) if CFG['gradient_accumulation_steps'] > 1: loss = loss / CFG['gradient_accumulation_steps'] if CFG['apex']: with amp.scale_loss(loss, optimizer) as scaled_loss: scaled_loss.backward() else: loss.backward() # clear memory del loss, y_preds torch.cuda.empty_cache() grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), CFG['max_grad_norm']) if (step + 1) % CFG['gradient_accumulation_steps'] == 0: optimizer.step() optimizer.zero_grad() global_step += 1 # measure elapsed time batch_time.update(time.time() - end) end = time.time() if step % CFG['print_freq'] == 0 or step == (len(train_loader)-1): print('Epoch: [{0}][{1}/{2}] ' 'Data {data_time.val:.3f} ({data_time.avg:.3f}) ' 'Elapsed {remain:s} ' 'Loss: {loss.val:.4f}({loss.avg:.4f}) ' 'Grad: {grad_norm:.4f} ' #'LR: {lr:.6f} ' .format( epoch+1, step, len(train_loader), batch_time=batch_time, data_time=data_time, loss=losses, remain=timeSince(start, float(step+1)/len(train_loader)), grad_norm=grad_norm, #lr=scheduler.get_lr()[0], )) return losses.avg def valid_fn(valid_loader, model, criterion, device): batch_time = AverageMeter() data_time = AverageMeter() losses = AverageMeter() scores = AverageMeter() # switch to evaluation mode model.eval() preds = [] start = end = time.time() for step, (images, labels) in enumerate(valid_loader): # measure data loading time data_time.update(time.time() - end) images = images.to(device) labels = labels.to(device) batch_size = labels.size(0) # compute loss with torch.no_grad(): y_preds = model(images) loss = get_loss(criterion, y_preds, labels) losses.update(loss.item(), batch_size) # record accuracy preds.append(y_preds.softmax(1).to('cpu').numpy()) if CFG['gradient_accumulation_steps'] > 1: loss = loss / CFG['gradient_accumulation_steps'] # measure elapsed time batch_time.update(time.time() - end) end = time.time() if step % CFG['print_freq'] == 0 or step == (len(valid_loader)-1): print('EVAL: [{0}/{1}] ' 'Data {data_time.val:.3f} ({data_time.avg:.3f}) ' 'Elapsed {remain:s} ' 'Loss: {loss.val:.4f}({loss.avg:.4f}) ' .format( step, len(valid_loader), batch_time=batch_time, data_time=data_time, loss=losses, remain=timeSince(start, float(step+1)/len(valid_loader)), )) predictions = np.concatenate(preds) return losses.avg, predictions def inference(model, states, test_loader, device): model.to(device) tk0 = tqdm(enumerate(test_loader), total=len(test_loader)) probs = [] for i, (images) in tk0: images = images.to(device) avg_preds = [] for state in states: # model.load_state_dict(state['model']) model.load_state_dict(state) model.eval() with torch.no_grad(): y_preds = model(images) avg_preds.append(y_preds.softmax(1).to('cpu').numpy()) avg_preds = np.mean(avg_preds, axis=0) probs.append(avg_preds) probs = np.concatenate(probs) return probs ###Output _____no_output_____ ###Markdown Train loop ###Code # ==================================================== # scheduler # ==================================================== def get_scheduler(optimizer): if TAG['scheduler']=='ReduceLROnPlateau': scheduler = ReduceLROnPlateau(optimizer, mode='min', factor=CFG['factor'], patience=CFG['patience'], verbose=True, eps=CFG['eps']) elif TAG['scheduler']=='CosineAnnealingLR': scheduler = CosineAnnealingLR(optimizer, T_max=CFG['T_max'], eta_min=CFG['min_lr'], last_epoch=-1) elif TAG['scheduler']=='CosineAnnealingWarmRestarts': scheduler = CosineAnnealingWarmRestarts(optimizer, T_0=CFG['T_0'], T_mult=1, eta_min=CFG['min_lr'], last_epoch=-1) return scheduler # ==================================================== # criterion # ==================================================== def get_criterion(): if TAG['criterion']=='CrossEntropyLoss': criterion = nn.CrossEntropyLoss() elif TAG['criterion'] == 'bi_tempered_logistic_loss': criterion = bi_tempered_logistic_loss return criterion # ==================================================== # Train loop # ==================================================== def train_loop(folds, fold): LOGGER.info(f"========== fold: {fold} training ==========") if not CFG['debug']: mlflow.set_tag('running.fold', str(fold)) # ==================================================== # loader # ==================================================== trn_idx = folds[folds['fold'] != fold].index val_idx = folds[folds['fold'] == fold].index train_folds = folds.loc[trn_idx].reset_index(drop=True) valid_folds = folds.loc[val_idx].reset_index(drop=True) train_dataset = TrainDataset(train_folds, transform=get_transforms(data='train')) valid_dataset = TrainDataset(valid_folds, transform=get_transforms(data='valid')) train_loader = DataLoader(train_dataset, batch_size=CFG['batch_size'], shuffle=True, num_workers=CFG['num_workers'], pin_memory=True, drop_last=True) valid_loader = DataLoader(valid_dataset, batch_size=CFG['batch_size'], shuffle=False, num_workers=CFG['num_workers'], pin_memory=True, drop_last=False) # ==================================================== # model & optimizer & criterion # ==================================================== best_model_path = OUTPUT_DIR+f'{TAG["model_name"]}_fold{fold}_best.pth' latest_model_path = OUTPUT_DIR+f'{TAG["model_name"]}_fold{fold}_latest.pth' model = CustomModel(TAG['model_name'], pretrained=True) model.to(device) # 学習途中の重みがあれば読み込み if os.path.isfile(latest_model_path): state_latest = torch.load(latest_model_path) state_best = torch.load(best_model_path) model.load_state_dict(state_latest['model']) epoch_start = state_latest['epoch']+1 # er_best_score = state_latest['score'] er_counter = state_latest['counter'] er_best_score = state_best['best_score'] LOGGER.info(f'Retrain model in epoch:{epoch_start}, best_score:{er_best_score:.3f}, counter:{er_counter}') else: epoch_start = 0 er_best_score = None er_counter = 0 optimizer = Adam(model.parameters(), lr=CFG['lr'], weight_decay=CFG['weight_decay'], amsgrad=False) scheduler = get_scheduler(optimizer) criterion = get_criterion() # ==================================================== # apex # ==================================================== if CFG['apex']: model, optimizer = amp.initialize(model, optimizer, opt_level='O1', verbosity=0) # ==================================================== # loop # ==================================================== # best_score = 0. # best_loss = np.inf early_stopping = EarlyStopping( patience=CFG['early_stopping_round'], verbose=True, save_path=best_model_path, counter=er_counter, best_score=er_best_score, save_latest_path=latest_model_path) for epoch in range(epoch_start, CFG['epochs']): start_time = time.time() # train avg_loss = train_fn(train_loader, model, criterion, optimizer, epoch, scheduler, device) # eval avg_val_loss, preds = valid_fn(valid_loader, model, criterion, device) valid_labels = valid_folds[CFG['target_col']].values # early stopping early_stopping(avg_val_loss, model, preds, epoch) if early_stopping.early_stop: print(f'Epoch {epoch+1} - early stopping') break if isinstance(scheduler, ReduceLROnPlateau): scheduler.step(avg_val_loss) elif isinstance(scheduler, CosineAnnealingLR): scheduler.step() elif isinstance(scheduler, CosineAnnealingWarmRestarts): scheduler.step() # scoring score = get_score(valid_labels, preds.argmax(1)) elapsed = time.time() - start_time LOGGER.info(f'Epoch {epoch+1} - avg_train_loss: {avg_loss:.4f} avg_val_loss: {avg_val_loss:.4f} time: {elapsed:.0f}s') LOGGER.info(f'Epoch {epoch+1} - Accuracy: {score}') # log mlflow if not CFG['debug']: mlflow.log_metric(f"fold{fold} avg_train_loss", avg_loss, step=epoch) mlflow.log_metric(f"fold{fold} avg_valid_loss", avg_val_loss, step=epoch) mlflow.log_metric(f"fold{fold} score", score, step=epoch) mlflow.log_metric(f"fold{fold} lr", scheduler.get_last_lr()[0], step=epoch) mlflow.log_artifact(best_model_path) if os.path.isfile(latest_model_path): mlflow.log_artifact(latest_model_path) check_point = torch.load(best_model_path) valid_folds[[str(c) for c in range(5)]] = check_point['preds'] valid_folds['preds'] = check_point['preds'].argmax(1) return valid_folds # ==================================================== # main # ==================================================== def get_result(result_df): preds = result_df['preds'].values labels = result_df[CFG['target_col']].values score = get_score(labels, preds) LOGGER.info(f'Score: {score:<.5f}') return score def main(): """ Prepare: 1.train 2.test 3.submission 4.folds """ if CFG['train']: # train oof_df = pd.DataFrame() for fold in range(CFG['n_fold']): if fold in CFG['trn_fold']: _oof_df = train_loop(folds, fold) oof_df = pd.concat([oof_df, _oof_df]) LOGGER.info(f"========== fold: {fold} result ==========") _ = get_result(_oof_df) # CV result LOGGER.info(f"========== CV ==========") score = get_result(oof_df) # save result oof_df.to_csv(OUTPUT_DIR+'oof_df.csv', index=False) # log mlflow if not CFG['debug']: mlflow.log_metric('oof score', score) mlflow.delete_tag('running.fold') mlflow.log_artifact(OUTPUT_DIR+'oof_df.csv') if CFG['inference']: # inference model = CustomModel(TAG['model_name'], pretrained=False) states = [torch.load(OUTPUT_DIR+f'{TAG["model_name"]}_fold{fold}_best.pth') for fold in CFG['trn_fold']] test_dataset = TestDataset(test, transform=get_transforms(data='valid')) test_loader = DataLoader(test_dataset, batch_size=CFG['batch_size'], shuffle=False, num_workers=CFG['num_workers'], pin_memory=True) predictions = inference(model, states, test_loader, device) # submission test['label'] = predictions.argmax(1) test[['image_id', 'label']].to_csv(OUTPUT_DIR+'submission.csv', index=False) ###Output _____no_output_____ ###Markdown rerun ###Code def _load_save_point(run_id): # どこで中断したか取得 stop_fold = int(mlflow.get_run(run_id=run_id).to_dictionary()['data']['tags']['running.fold']) # 学習対象のfoldを変更 CFG['trn_fold'] = [fold for fold in CFG['trn_fold'] if fold>=stop_fold] # 学習済みモデルがあれば.pthファイルを取得(学習中も含む) client = mlflow.tracking.MlflowClient() artifacts = [artifact for artifact in client.list_artifacts(run_id) if ".pth" in artifact.path] for artifact in artifacts: client.download_artifacts(run_id, artifact.path, OUTPUT_DIR) def check_have_run(): results = mlflow.search_runs(INFO['EXPERIMENT_ID']) run_id_list = results[results['tags.mlflow.runName']==TITLE]['run_id'].tolist() # 初めて実行する場合 if len(run_id_list) == 0: run_id = None # 既に実行されている場合 else: assert len(run_id_list)==1 run_id = run_id_list[0] _load_save_point(run_id) return run_id if __name__ == '__main__': if CFG['debug']: main() else: mlflow.set_tracking_uri(INFO['TRACKING_URI']) mlflow.set_experiment('single model') # 既に実行済みの場合は続きから実行する run_id = check_have_run() with mlflow.start_run(run_id=run_id, run_name=TITLE): if run_id is None: mlflow.log_artifact(CONFIG_PATH) mlflow.log_param('device', device) mlflow.set_tag('env', env) mlflow.set_tags(TAG) mlflow.log_params(CFG) mlflow.log_artifact(notebook_path) main() mlflow.log_artifacts(OUTPUT_DIR) remove_glob(f'{OUTPUT_DIR}/*latest.pth') if env=="kaggle": shutil.copy2(CONFIG_PATH, f'{OUTPUT_DIR}/{CONFIG_NAME}') ! rm -r cassava elif env=="colab": shutil.copytree(OUTPUT_DIR, f'{INFO["SHARE_DRIVE_PATH"]}/{TITLE}') shutil.copy2(CONFIG_PATH, f'{INFO["SHARE_DRIVE_PATH"]}/{TITLE}/{CONFIG_NAME}') # remove_glob(f'{INFO["SHARE_DRIVE_PATH"]}/{TITLE}/*latest.pth') ###Output _____no_output_____
env_with_anaconda_test/test matplotlib.ipynb
###Markdown rollaxis 实例 ###Code %matplotlib inline import matplotlib.pyplot as plt import numpy as np import scipy.misc b = scipy.misc.imread('magic.png') b.dtype toimage(b) b.shape c = np.rollaxis(b, 1) c.shape toimage(c) d = np.swapaxes(b, 0, 1) d.shape toimage(d) ###Output _____no_output_____
sympy/polarCurves.ipynb
###Markdown Import sympy parametric plot modules ###Code %reset -f from sympy import * from sympy.plotting import plot_parametric from sympy.plotting import plot3d_parametric_line import math init_printing() # for nice math output # uncomment for plot in separate window %matplotlib qt # uncomment for plot inline --- DEFAULT #%matplotlib inline ###Output _____no_output_____ ###Markdown Declare symbolic variables ###Code t = symbols('t') ###Output _____no_output_____ ###Markdown Example: Plot the polar curve $r = 2\cos(t)$ ###Code # 2d - Example 1 r = 2*cos(t) %matplotlib inline plot_parametric( r*cos(t), r*sin(t), (t, 0, 2*pi)) ###Output _____no_output_____ ###Markdown Example: Plot the polar curve $r = 1 + 2 \sin(t)$ ###Code r = 1 + 2*sin(t) %matplotlib inline plot_parametric( r*cos(t), r*sin(t), (t, 0, 2*pi)) ###Output _____no_output_____ ###Markdown Example: Plot the polar curve $r = 3 + 2\cos(t)$ ###Code r = 3 + 2*cos(t) %matplotlib inline plot_parametric( r*cos(t), r*sin(t), (t, 0, 2*pi)) ###Output _____no_output_____ ###Markdown Example: Plot the polar curve $r = \sin(3t)$ ###Code r = sin(2*t) %matplotlib inline plot_parametric( r*cos(t), r*sin(t), (t, 0, 2*pi)) ###Output _____no_output_____ ###Markdown Example: Plot the family of curve curve $r = a + b \sin(t)$ with slidable $a$ and $b$. ###Code %reset -f %matplotlib qt import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import Slider plt.subplots_adjust(bottom=0.25) t = np.arange(0.0, 2*np.pi, 0.001) a = 1 b = 1 r = a + b*np.sin(t) x = r*np.cos(t) y = r*np.sin(t) l, = plt.plot(x,y, lw=4, color='black') plt.axis([-3, 3, -3, 3]) axcolor = 'lightgoldenrodyellow' axb = plt.axes([0.25, 0.10, 0.65, 0.03], axisbg=axcolor) axa = plt.axes([0.25, 0.15, 0.65, 0.03], axisbg=axcolor) sa = Slider(axa, 'a', 0, 2, valinit=a) sb = Slider(axb, 'b', 0, 2, valinit=b) def update(val): a = sa.val b = sb.val r = a + b*np.sin(t) x = r*np.cos(t) y = r*np.sin(t) l.set_ydata(y) l.set_xdata(x) fig.canvas.draw_idle() sa.on_changed(update) sb.on_changed(update) plt.title('r = a + b cos(t)') plt.show() ###Output _____no_output_____ ###Markdown Example: Plot the family of curve curve $r = \sin[a(t+b)]$ with slidable $a$ and $b$. ###Code %reset -f %matplotlib qt import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import Slider plt.subplots_adjust(bottom=0.25) t = np.arange(0.0, 2*np.pi, 0.001) a = 2 b = 0 r = np.cos(a*(t + b)) x = r*np.cos(t) y = r*np.sin(t) l, = plt.plot(x,y, lw=4, color='black') plt.axis([-3, 3, -3, 3]) axcolor = 'lightgoldenrodyellow' axb = plt.axes([0.25, 0.10, 0.65, 0.03], axisbg=axcolor) axa = plt.axes([0.25, 0.15, 0.65, 0.03], axisbg=axcolor) sa = Slider(axa, 'a', 0, 10, valinit=a) sb = Slider(axb, 'b', -np.pi, np.pi, valinit=b) def update(val): a = (sa.val) b = sb.val r = np.cos(a*(t + b)) x = r*np.cos(t) y = r*np.sin(t) l.set_ydata(y) l.set_xdata(x) fig.canvas.draw_idle() sa.on_changed(update) sb.on_changed(update) plt.title('r = cos(a(t + b))') plt.show() ###Output _____no_output_____
tables_boxplot/all_patients_all_features_numeric/num_variable_distribution_boxplot_tables.ipynb
###Markdown Imports ###Code import numpy as np import pandas as pd from collections import Counter import os import glob import copy from random import sample ###Output _____no_output_____ ###Markdown Opening the CSV files ###Code dataframes = [pd.read_csv(file, sep=',') for file in sorted(glob.glob('../../feature_tables' + "/*."+'csv'))] modalities = [file.split(".")[0] for file in sorted(os.listdir('../../feature_tables'))] # make a dictionary that contains all modalities as a dataframe all_features = dict() for modal, df in zip(modalities, dataframes): table = modal.split(" - ")[1] all_features[table] = df # drop irrelevant columns for moda in all_features: all_features[moda].drop(columns=['CURIE', 'Definition', 'Synonyms'], inplace=True) # combine the modalities into a dataframe merged = pd.concat(all_features, ignore_index=True) # replace the "no total score" as the test was performed but the total score was not reported merged.replace({"No total score.": np.nan}, inplace=True) # fill all the nan cells with 0 merged.fillna(0, inplace=True) # rank 2 is taboo numeric_df = merged.loc[(merged.Rank!=1) & (merged.Rank!=2)] # select the features that are numerical measurements categoric_df = merged.loc[(merged.Rank==1) & (merged.Rank!=2)] # select the features that are categorical measurements ###Output _____no_output_____ ###Markdown Read the merged file for every cohort ###Code datasets = [pd.read_csv(file, index_col=0, low_memory=False) for file in sorted(glob.glob('../../cohort_studies_full_data/' + "/*."+'csv'))] cohorts = [file.split(".")[0] for file in sorted(os.listdir('../../cohort_studies_full_data/'))] # make a dictionary that contains all modalities as a dataframe cohort_studies = dict() for cohort, dataset in zip(cohorts, datasets): cohort_n = cohort.split("_MERGE")[0] cohort_studies[cohort_n] = dataset.loc[dataset['Months']==0].copy() # reduce to BL visit # make the index column consistent among the cohort dataframes for cohort in cohort_studies: if cohort!='JADNI': cohort_studies[cohort]['ID'] = cohort_studies[cohort].index cohort_studies[cohort] = cohort_studies[cohort].reset_index().set_index('ID') cohort_studies[cohort].dropna(axis=1, how='all', inplace=True) # drop columns with all NAN entries ###Output _____no_output_____ ###Markdown Funtion: extracting the reported values for every available feature ###Code def extract_features(df_dict, feature_df, result_dict): """make a dictionary containing dictionaries of each feature, the values of the inner dictionary are the measurements for every available feature in each cohort study""" for feature in feature_df.Feature: # take columns that are same name as cohorts for cohort in feature_df.columns.intersection(df_dict.keys()): # select the feature name according to the respective cohort feat = feature_df.loc[feature_df['Feature']==feature, cohort].item() # in the cells containing "," there are multiple features mapped # if there is no comma that means the mapping are 1 to 1 # the value 0 represent the absence of the feature in the respective cohort if (feat!=0) and (", " not in feat): flag = False # in some cases we have multiple targets features for the mapping, we prioritize the 100 match if available for col in df_dict[cohort].columns: if feat==col: flag = True # if the 100% match was found l = list(df_dict[cohort][col].dropna()) # when there are measurements available for the features shuffle and store them if len(l)!=0: result_dict[feature][feature + "." + cohort] = sample(l, len(l)) elif (feat in col) and (flag==False): l = list(df_dict[cohort][col].dropna()) # when there are measurements available for the features shuffle and store them if len(l)!=0: result_dict[feature][feature + "." + cohort] = sample(l, len(l)) # in the cells containing "," there are multiple features mapped # when there is multiple, take the second one # the value 0 represent the absence of the feature in the respective cohort elif (feat!=0) and (", " in feat): # select the feature name according to the respective cohort feat_n = feature_df.loc[feature_df['Feature']==feature, cohort].item().split(", ")[1] flag = False # in some cases we have multiple targets features for the mapping, we prioritize the 100 match if available for col in df_dict[cohort].columns: if feat_n==col: flag = True # if the 100% match was found l = list(df_dict[cohort][col].dropna()) # when there are measurements available for the features shuffle and store them if len(l)!=0: result_dict[feature][feature + "." + cohort] = sample(l, len(l)) elif (feat_n in col) and (flag==False): l = list(df_dict[cohort][col].dropna()) # when there are measurements available for the features shuffle and store them if len(l)!=0: result_dict[feature][feature + "." + cohort] = sample(l, len(l)) ###Output _____no_output_____ ###Markdown Results ###Code # make a dictionary of dictionaries to store the results result = dict() # select the target features as outer dictionary's keys for feat in numeric_df.Feature: avai_cohorts = dict() for cohort in numeric_df.columns.intersection(cohort_studies.keys()): # target feature names + the feature names for each cohort as inner dictionary's keys if numeric_df.loc[numeric_df.Feature == feat, cohort].item()!=0: avai_cohorts[feat + "." + cohort] = [] result[feat]= avai_cohorts # call the function to generate the tables for boxplots extract_features(cohort_studies, numeric_df, result) ###Output _____no_output_____ ###Markdown Save the results into tsv files ###Code # aibl did not report the age of the participnats, they reported the date of birth del result['Age']['Age.AIBL'] del result['Age']['Age.ABVIB'] #only month and year of birth was reported # Certain measurements were collected as values in some cohorts and as categorical in others # Remove the ones that are categorical as we can not plot them del result['PiB PET']['PiB PET.AIBL'] # Positive, Negative del result['AV45 PET']['AV45 PET.AIBL'] # Positive, Negative del result['AV45 PET']['AV45 PET.NACC'] # Abnormally elevated amyloid on PET: 0=No, 1=Yes, 8=Unknown/not assessed del result['AV45 PET']['AV45 PET.EMIF'] # 0.0 and 1.0 #convert each feature dictionary into a dataframe and save it as csv file for i in result: if (i=="Age") or (i=="Education"): for j in result[i]: result[i][j] = list(map(int, result[i][j])) df = pd.DataFrame.from_dict(result[i], orient='index').transpose() df.index.name = 'Participant number' df.dropna(how='all', axis=1, inplace=True) if df.empty==False: df.to_csv(f"{i}.tsv", sep='\t', index_label='Participant number') ###Output _____no_output_____
Adaptive Sensitive Reweighting/Adaptive_Sensitive_Reweightening_Adult-dataset.ipynb
###Markdown 1. Load and preprocess the datasets* In the article it was wentioned, that all categorical features were encoded using one-hot scheme, whereas all numeric attributes were normalized by dividing with their mean value. ###Code def encode_and_bind(original_dataframe, feature_to_encode): """ To obtain dummy features from original feature `feature_to_encode`, add them to original dataframe `original_dataframe`, and drop original feature from it. """ dummies = pd.get_dummies(original_dataframe[[feature_to_encode]], drop_first=True) res = pd.concat([original_dataframe, dummies], axis=1) res = res.drop([feature_to_encode], axis=1) return(res) ###Output _____no_output_____ ###Markdown 1.1 Adult dataset`data_adult` - [Adult income dataset](https://www.kaggle.com/wenruliu/adult-income-dataset?select=adult.csv) comprises 48842 samples with 14 features and a label `income` with two possible values `50K`. In the article the `gender` was considered as *sensitive feature*.Let's make the following preprocessing steps:1. Replace values in `income`: `>50K` -> `1` and ` `0`. 2. Replace values in `gender`: `Female` -> `1` and `Male` -> `0`.3. Divide the following numerical features with their mean values: `age`, `fnlwgt`, `educational-num`, `capital-gain`, `capital-loss`, `hours-per-week`4. Encode the following categorical features with one-hot scheme: `workclass`, `education`, `marital-status`, `occupation`, `relationship`, `race`, `native-country`After preprocessing we will perform five 70:30 random splits to obtain training and test data. Each split corrresponds to one experiment. ###Code data_adult = pd.read_csv("adult.csv") # Replace values in 'income' data_adult.loc[data_adult['income'] == '<=50K', 'income'] = 1 data_adult.loc[data_adult['income'] == '>50K', 'income'] = 0 # Replace values in 'gender' data_adult.loc[data_adult['gender'] == 'Female', 'gender'] = 1 data_adult.loc[data_adult['gender'] == 'Male', 'gender'] = 0 # Normalize all numerical features by dividing with mean value num_features_adult = ["age", "fnlwgt", "educational-num", "capital-gain", "capital-loss", "hours-per-week"] for feature in num_features_adult: mean = data_adult[feature].mean() data_adult[feature] = data_adult[feature] / mean # Make dummy features for all categorical features cat_features_adult = ["workclass", "education", "marital-status", "race", "occupation", "relationship", "native-country"] for feature in cat_features_adult: data_adult = encode_and_bind(data_adult, feature) data_adult.shape ###Output _____no_output_____ ###Markdown 2. Adaptive Sensitive Reweightening (ASR) + CULEP model 2.1 Adaptive Sensitive Reweightening (`ReweightedClassifier`) ###Code class ReweightedClassifier: def __init__(self, baze_clf, alpha, beta, params = {}): """ Input: baze_clf - object from sklearn with methods .fit(sample_weight=), .predict(), .predict_proba() alpha - list of alphas for sensitive and non-sensitive objects [alpha, alpha'] beta - list of betss for sensitive and non-sensitive objects [beta, beta'] params - **kwargs compatible with baze_clf """ self.baze_clf = baze_clf self.model = None self.alpha = np.array(alpha) self.alphas = None self.beta = np.array(beta) self.betas = None self.weights = None self.prev_weights = None self.params = params def reweight_dataset(self, length, error, minority_idx): """ This function recalculates values of weights and saves their previous values """ if self.alphas is None or self.betas is None: # If alpha_0, alpha_1 or beta_0, beta_1 are not defined, # then define alpha_0 and beta_0 to every object from non-sensitive class, # and alpha_1 and beta_1 to every object from sensitive class (minority). self.alphas = np.ones(length) * self.alpha[0] self.betas = np.ones(length) * self.beta[0] self.alphas[minority_idx] = self.alpha[1] self.betas[minority_idx] = self.beta[1] # w_i_prev <- w_i for all i in dataset self.prev_weights = self.weights.copy() # w_i = alpha_i * L_{beta_i} (P'(y_pred_i =! y_true_i)) # + (1 - alpha_i) * L_{beta_i} (-P'(y_pred_i =! y_true_i)), # where # L_{beta_i} (x) = exp(beta_i * x) self.weights = self.alphas * np.exp(self.betas * error) \ + (1 - self.alphas) * np.exp(- self.betas * error) def pRule(self, prediction, minority_idx): """ This function calculates | P(y_pred_i = 1 | i in S) P(y_pred_i = 1 | i not in S) | pRule = min { ---------------------------- , ---------------------------- } | P(y_pred_i = 1 | i not in S) P(y_pred_i = 1 | i in S) | S - the group of sensitive objects --------- Input: prediction - labels ({0,1}) of a sample for which pRule is calculated minority_idx - indexes of objects from a sensitive group """ # majority indexes = set of all indexes / set of minority indexes, # where set of all indexes = all numbers from 0 to size of sample (=len(prediction)) majority_idx = set(np.linspace(0, len(prediction) - 1, len(prediction), dtype = int)).difference(minority_idx) # minority = P(y_pred_i = 1 | i in minority) # majority = P(y_pred_i = 1 | i in majority) minority = prediction[minority_idx].mean() majority = prediction[list(majority_idx)].mean() minority = np.clip(minority, 1e-10, 1 - 1e-10) majority = np.clip(majority, 1e-10, 1 - 1e-10) return min(minority/majority, majority/minority) def fit(self, X_train, y_train, X_test, y_test, minority_idx, verbose=True, max_iter=30): # Initialize equal weights w_i = 1 self.weights = np.ones(len(y_train)) self.prev_weights = np.zeros(len(y_train)) # Lists for saving metrics accuracys = [] pRules = [] differences = [] accuracy_plus_prule = [] # Adaptive Sensitive Reweighting iteration = 0 while ((self.prev_weights - self.weights) ** 2).mean() > 10**(-6) and iteration < max_iter: iteration += 1 # Train classifier on X_train with weights (w_i / sum(w_i)) self.model = self.baze_clf(**self.params) self.model.fit(X_train, y_train, sample_weight = self.weights / (self.weights.sum())) # Use classifier to obtain P`(y_pred_i =! y_pred) (here it is called 'error') prediction_proba = self.model.predict_proba(X_train)[:, 1] error = prediction_proba - y_train # Update weights self.reweight_dataset(len(y_train), error, minority_idx) # Get metrics on X_train prediction = self.model.predict(X_train) accuracys.append(accuracy_score(prediction, y_train)) pRules.append(self.pRule(prediction, minority_idx)) accuracy_plus_prule.append(accuracys[-1] + pRules[-1]) differences.append(((self.prev_weights - self.weights)**2).mean()**0.5) # Visualize metrics if it's needed if verbose: display.clear_output(True) fig, axes = plt.subplots(ncols=2, nrows=2, figsize=(16, 7)) metrics = [accuracys, pRules, accuracy_plus_prule, differences] metrics_names = ["Accuracy score", "pRule", "Accuracy + pRule", "Mean of weight edits"] for name, metric, ax in zip(metrics_names, metrics, axes.flat): ax.plot(metric, label='train') ax.set_title(f'{name}, iteration {iteration}') ax.legend() if name == "Mean of weight edits": ax.set_yscale('log') plt.show() return accuracys, pRules, accuracy_plus_prule, differences def predict(self, X): return self.model.predict(X) def predict_proba(self, X): return self.model.predict_proba(X) def get_metrics_test(self, X_test, y_test, minority_idx_test): """ Obtain pRule and accuracy for trained model """ # Obtain predictions on X_test to calculate metrics prediction_test = self.model.predict(X_test) # Get metrics on test accuracy_test = accuracy_score(prediction_test, y_test) pRule_test = self.pRule(prediction_test, minority_idx_test) return accuracy_test, pRule_test ###Output _____no_output_____ ###Markdown 2.2. Optimizing CULEP parameter (`train_model`)In the article CULEP parameters are $\alpha, \alpha', \beta, \beta'$. They searched for the optimal hyperparameters in the space $\left( \alpha, \alpha', \beta, \beta' \right) \in \left[ 0, 1 \right] ^2 \times \left[ 0, 3 \right] ^2$ and used for it DIvided RECTangles (DIRECT) method. Each combination of parameters is evaluated with a full run of Adaptive Sensitive Reweightening algorithm on the training set. After optimization of the objective function (in case of Adult dataset it is `accuracy + pRule`), we get optimal hyperparameters $\alpha, \alpha', \beta, \beta'$. Then trained model (on the training set) with these hyperparameters make predictions on test set and the obtained metrics (accuracy and pRule) are reported.The optimization of objective function is time-consuming. For one split on train and test sets this process can take up to **2 hours** for Adult dataset. The whole process is repeated for 5 different random splits on train and test sets. To be able to keep track of the process each split will be started in its own cell (instead of a loop). Each split will correspont to one experiment. ###Code def prep_train_model(X_train, y_train, X_test, y_test, minority_idx): def train_model(a): """ Function of 4 variables (a[0], a[1], a[2], a[3]) that will be minimized by DIRECT method. a[0], a[1] = alpha, alpha' a[2], a[3] = beta, beta' """ model = ReweightedClassifier(LogisticRegression, [a[0], a[1]], [a[2], a[3]], params = {"max_iter": 4000, 'solver':'liblinear'}) _, _, accuracy_plus_prule, _ = model.fit(X_train, y_train, X_test, y_test, minority_idx) # We'll maximize [acc + pRule] which we get at the last iteration of Adaptive Sensitive Reweighting return - accuracy_plus_prule[-1] return train_model # return function for optimization ###Output _____no_output_____ ###Markdown 3. ExperimentsIn order to make all experiments independent from each other, all necessary variables will have name endings either `_1`, `_2`, `_3`, `_4` or `_5`. 3.1. Experiment 1 1) Obtain a split for the experiment. ###Code # Split on train and test labels_adult = data_adult["income"] features_adult = data_adult.drop(columns=["income"]) X_train_1, X_test_1, y_train_1, y_test_1 = train_test_split(features_adult, labels_adult, test_size=0.3, random_state=1) y_train_1 = y_train_1.astype(int).values y_test_1 = y_test_1.astype(int).values # Obtain indexes of sensitive class minority_idx_1 = X_train_1.reset_index(drop=True).index.values[X_train_1["gender"] == 1] minority_idx_test_1 = X_test_1.reset_index(drop=True).index.values[X_test_1["gender"] == 1] ###Output _____no_output_____ ###Markdown 2) Perform ASR+CULEP. ###Code objective_1 = prep_train_model(X_train_1, y_train_1, X_test_1, y_test_1, minority_idx_1) start = time.time() my_res_1 = minimize(objective_1, bounds=[[0.0, 1.0], [0.0, 1.0], [0.0, 3.0], [0.0, 3.0]], maxT=160, maxf=320) stop = time.time() print(f"Elapsed time: {stop - start} s") print(f"Elapsed time: {(stop - start) // 60} min {(stop - start) % 60} s") print(my_res_1) ###Output _____no_output_____ ###Markdown 3) Get necessary metrics on test set (for Adult dataset the metrics are accuracy and pRule). ###Code # Create model with obtained hyperparameters alpha, alpha', beta, beta' a_1 = my_res_1.x model_1 = ReweightedClassifier(LogisticRegression, [a_1[0], a_1[1]], [a_1[2], a_1[3]], params = {"max_iter": 4000, 'solver':'liblinear'}) # Train model on X_train model_1.fit(X_train_1, y_train_1, X_test_1, y_test_1, minority_idx_1, verbose=False) # Calculate metrics (pRule, accuracy) on X_test accuracy_test_1, pRule_test_1 = model_1.get_metrics_test(X_test_1, y_test_1, minority_idx_test_1) print('ASR+CULEP for X_test') print(f"prule = {pRule_test_1:.6}, accuracy = {accuracy_test_1:.6}") print(f"prule + accuracy = {(pRule_test_1 + accuracy_test_1):.6}") ###Output ASR+CULEP for X_test prule = 0.995213, accuracy = 0.789395 prule + accuracy = 1.78461 ###Markdown 4) For the same split train simple Logistic Regression (without ASR+CULEP) on the train set. Then obtain necessary metrics on the test set. ###Code # Fit LogisticRegression on X_train model_simple = LogisticRegression(max_iter=4000, solver='liblinear') model_simple.fit(X_train_1, y_train_1) # Get predictions for X_test prediction = model_simple.predict(X_test_1) # Obtain indexes for sensitive and non-sensitive groups majority_idx_test_1 = set(np.linspace(0, len(prediction) - 1, len(prediction), dtype = int)).difference(minority_idx_test_1) minority = prediction[minority_idx_test_1].mean() majority = prediction[list(majority_idx_test_1)].mean() # Calculate metrics on X_test prule_simple = min(minority/majority, majority/minority) accuracy_simple = accuracy_score(prediction, y_test_1) print('Without ASR+CULEP for X_test') print(f"prule = {prule_simple:.6}, accuracy = {accuracy_simple:.6}") print(f"prule + accuracy = {(prule_simple + accuracy_simple):.6}") ###Output Without ASR+CULEP for X_test prule = 0.811552, accuracy = 0.855183 prule + accuracy = 1.66674 ###Markdown 3.2. Experiment 2 1) Obtain a split for the experiment. ###Code # Split on train and test labels_adult = data_adult["income"] features_adult = data_adult.drop(columns=["income"]) X_train_2, X_test_2, y_train_2, y_test_2 = train_test_split(features_adult, labels_adult, test_size=0.3, random_state=2) y_train_2 = y_train_2.astype(int).values y_test_2 = y_test_2.astype(int).values # Obtain indexes of sensitive class minority_idx_2 = X_train_2.reset_index(drop=True).index.values[X_train_2["gender"] == 1] minority_idx_test_2 = X_test_2.reset_index(drop=True).index.values[X_test_2["gender"] == 1] ###Output _____no_output_____ ###Markdown 2) Perform ASR+CULEP. ###Code objective_2 = prep_train_model(X_train_2, y_train_2, X_test_2, y_test_2, minority_idx_2) start = time.time() my_res_2 = minimize(objective_2, bounds=[[0.0, 1.0], [0.0, 1.0], [0.0, 3.0], [0.0, 3.0]], maxT=80, maxf=320) stop = time.time() print(f"Elapsed time: {stop - start} s") print(f"Elapsed time: {(stop - start) // 60} min {(stop - start) % 60} s") print(my_res_2) ###Output _____no_output_____ ###Markdown 3) Get necessary metrics on test set (for Adult dataset the metrics are accuracy and pRule). ###Code # Create model with obtained hyperparameters alpha, alpha', beta, beta' a_2 = my_res_2.x model_2 = ReweightedClassifier(LogisticRegression, [a_2[0], a_2[1]], [a_2[2], a_2[3]], params = {"max_iter": 4000, 'solver':'liblinear'}) # Train model on X_train model_2.fit(X_train_2, y_train_2, X_test_2, y_test_2, minority_idx_2, verbose=False) # Calculate metrics (pRule, accuracy) on X_test accuracy_test_2, pRule_test_2 = model_2.get_metrics_test(X_test_2, y_test_2, minority_idx_test_2) print('ASR+CULEP for X_test') print(f"prule = {pRule_test_2:.6}, accuracy = {accuracy_test_2:.6}") print(f"prule + accuracy = {(pRule_test_2 + accuracy_test_2):.6}") ###Output ASR+CULEP for X_test prule = 0.992735, accuracy = 0.793012 prule + accuracy = 1.78575 ###Markdown 4) For the same split train simple Logistic Regression (without ASR+CULEP) on the train set. Then obtain necessary metrics on the test set. ###Code # Fit LogisticRegression on X_train model_simple = LogisticRegression(max_iter=4000, solver='liblinear') model_simple.fit(X_train_2, y_train_2) # Get predictions for X_test prediction = model_simple.predict(X_test_2) # Obtain indexes for sensitive and non-sensitive groups majority_idx_test_2 = set(np.linspace(0, len(prediction) - 1, len(prediction), dtype = int)).difference(minority_idx_test_2) minority = prediction[minority_idx_test_2].mean() majority = prediction[list(majority_idx_test_2)].mean() # Calculate metrics on X_test prule_simple = min(minority/majority, majority/minority) accuracy_simple = accuracy_score(prediction, y_test_2) print('Without ASR+CULEP for X_test') print(f"prule = {prule_simple:.6}, accuracy = {accuracy_simple:.6}") print(f"prule + accuracy = {(prule_simple + accuracy_simple):.6}") ###Output Without ASR+CULEP for X_test prule = 0.808386, accuracy = 0.852863 prule + accuracy = 1.66125 ###Markdown 3.3. Experiment 3 1) Obtain a split for the experiment. ###Code # Split on train and test labels_adult = data_adult["income"] features_adult = data_adult.drop(columns=["income"]) X_train_3, X_test_3, y_train_3, y_test_3 = train_test_split(features_adult, labels_adult, test_size=0.3, random_state=3) y_train_3 = y_train_3.astype(int).values y_test_3 = y_test_3.astype(int).values # Obtain indexes of sensitive class minority_idx_3 = X_train_3.reset_index(drop=True).index.values[X_train_3["gender"] == 1] minority_idx_test_3 = X_test_3.reset_index(drop=True).index.values[X_test_3["gender"] == 1] ###Output _____no_output_____ ###Markdown 2) Perform ASR+CULEP. ###Code objective_3 = prep_train_model(X_train_3, y_train_3, X_test_3, y_test_3, minority_idx_3) start = time.time() my_res_3 = minimize(objective_3, bounds=[[0.0, 1.0], [0.0, 1.0], [0.0, 3.0], [0.0, 3.0]], maxT=80, maxf=320) stop = time.time() print(f"Elapsed time: {stop - start} s") print(f"Elapsed time: {(stop - start) // 60} min {(stop - start) % 60} s") print(my_res_3) ###Output _____no_output_____ ###Markdown 3) Get necessary metrics on test set (for Adult dataset the metrics are accuracy and pRule). ###Code # Create model with obtained hyperparameters alpha, alpha', beta, beta' a_3 = my_res_3.x model_3 = ReweightedClassifier(LogisticRegression, [a_3[0], a_3[1]], [a_3[2], a_3[3]], params = {"max_iter": 4000, 'solver':'liblinear'}) # Train model on X_train model_3.fit(X_train_3, y_train_3, X_test_3, y_test_3, minority_idx_3, verbose=False) # Calculate metrics (pRule, accuracy) on X_test accuracy_test_3, pRule_test_3 = model_3.get_metrics_test(X_test_3, y_test_3, minority_idx_test_3) print('ASR+CULEP for X_test') print(f"prule = {pRule_test_3:.6}, accuracy = {accuracy_test_3:.6}") print(f"prule + accuracy = {(pRule_test_3 + accuracy_test_3):.6}") ###Output ASR+CULEP for X_test prule = 0.990077, accuracy = 0.793694 prule + accuracy = 1.78377 ###Markdown 4) For the same split train simple Logistic Regression (without ASR+CULEP) on the train set. Then obtain necessary metrics on the test set. ###Code # Fit LogisticRegression on X_train model_simple = LogisticRegression(max_iter=4000, solver='liblinear') model_simple.fit(X_train_3, y_train_3) # Get predictions for X_test prediction = model_simple.predict(X_test_3) # Obtain indexes for sensitive and non-sensitive groups majority_idx_test_3 = set(np.linspace(0, len(prediction) - 1, len(prediction), dtype = int)).difference(minority_idx_test_3) minority = prediction[minority_idx_test_3].mean() majority = prediction[list(majority_idx_test_3)].mean() # Calculate metrics on X_test prule_simple = min(minority/majority, majority/minority) accuracy_simple = accuracy_score(prediction, y_test_3) print('Without ASR+CULEP for X_test') print(f"prule = {prule_simple:.6}, accuracy = {accuracy_simple:.6}") print(f"prule + accuracy = {(prule_simple + accuracy_simple):.6}") ###Output Without ASR+CULEP for X_test prule = 0.810961, accuracy = 0.852726 prule + accuracy = 1.66369 ###Markdown 3.4. Experiment 4 1) Obtain a split for the experiment. ###Code # Split on train and test labels_adult = data_adult["income"] features_adult = data_adult.drop(columns=["income"]) X_train_4, X_test_4, y_train_4, y_test_4 = train_test_split(features_adult, labels_adult, test_size=0.3, random_state=4) y_train_4 = y_train_4.astype(int).values y_test_4 = y_test_4.astype(int).values # Obtain indexes of sensitive class minority_idx_4 = X_train_4.reset_index(drop=True).index.values[X_train_4["gender"] == 1] minority_idx_test_4 = X_test_4.reset_index(drop=True).index.values[X_test_4["gender"] == 1] ###Output _____no_output_____ ###Markdown 2) Perform ASR+CULEP. ###Code objective_4 = prep_train_model(X_train_4, y_train_4, X_test_4, y_test_4, minority_idx_4) start = time.time() my_res_4 = minimize(objective_4, bounds=[[0.0, 1.0], [0.0, 1.0], [0.0, 3.0], [0.0, 3.0]], maxT=80, maxf=320) stop = time.time() print(f"Elapsed time: {stop - start} s") print(f"Elapsed time: {(stop - start) // 60} min {(stop - start) % 60} s") print(my_res_4) ###Output _____no_output_____ ###Markdown 3) Get necessary metrics on test set (for Adult dataset the metrics are accuracy and pRule). ###Code # Create model with obtained hyperparameters alpha, alpha', beta, beta' a_4 = my_res_4.x model_4 = ReweightedClassifier(LogisticRegression, [a_4[0], a_4[1]], [a_4[2], a_4[3]], params = {"max_iter": 4000, 'solver':'liblinear'}) # Train model on X_train model_4.fit(X_train_4, y_train_4, X_test_4, y_test_4, minority_idx_4, verbose=False) # Calculate metrics (pRule, accuracy) on X_test accuracy_test_4, pRule_test_4 = model_4.get_metrics_test(X_test_4, y_test_4, minority_idx_test_4) print('ASR+CULEP for X_test') print(f"prule = {pRule_test_4:.6}, accuracy = {accuracy_test_4:.6}") print(f"prule + accuracy = {(pRule_test_4 + accuracy_test_4):.6}") ###Output ASR+CULEP for X_test prule = 0.992053, accuracy = 0.792329 prule + accuracy = 1.78438 ###Markdown 4) For the same split train simple Logistic Regression (without ASR+CULEP) on the train set. Then obtain necessary metrics on the test set. ###Code # Fit LogisticRegression on X_train model_simple = LogisticRegression(max_iter=4000, solver='liblinear') model_simple.fit(X_train_4, y_train_4) # Get predictions for X_test prediction = model_simple.predict(X_test_4) # Obtain indexes for sensitive and non-sensitive groups majority_idx_test_4 = set(np.linspace(0, len(prediction) - 1, len(prediction), dtype = int)).difference(minority_idx_test_4) minority = prediction[minority_idx_test_4].mean() majority = prediction[list(majority_idx_test_4)].mean() # Calculate metrics on X_test prule_simple = min(minority/majority, majority/minority) accuracy_simple = accuracy_score(prediction, y_test_4) print('Without ASR+CULEP for X_test') print(f"prule = {prule_simple:.6}, accuracy = {accuracy_simple:.6}") print(f"prule + accuracy = {(prule_simple + accuracy_simple):.6}") ###Output Without ASR+CULEP for X_test prule = 0.806501, accuracy = 0.852863 prule + accuracy = 1.65936 ###Markdown 3.5. Experiment 5 1) Obtain a split for the experiment. ###Code # Split on train and test labels_adult = data_adult["income"] features_adult = data_adult.drop(columns=["income"]) X_train_5, X_test_5, y_train_5, y_test_5 = train_test_split(features_adult, labels_adult, test_size=0.3, random_state=5) y_train_5 = y_train_5.astype(int).values y_test_5 = y_test_5.astype(int).values # Obtain indexes of sensitive class minority_idx_5 = X_train_5.reset_index(drop=True).index.values[X_train_5["gender"] == 1] minority_idx_test_5 = X_test_5.reset_index(drop=True).index.values[X_test_5["gender"] == 1] ###Output _____no_output_____ ###Markdown 2) Perform ASR+CULEP. ###Code objective_5 = prep_train_model(X_train_5, y_train_5, X_test_5, y_test_5, minority_idx_5) start = time.time() my_res_5 = minimize(objective_5, bounds=[[0.0, 1.0], [0.0, 1.0], [0.0, 3.0], [0.0, 3.0]], maxT=80, maxf=320) stop = time.time() print(f"Elapsed time: {stop - start} s") print(f"Elapsed time: {(stop - start) // 60} min {(stop - start) % 60} s") print(my_res_5) ###Output _____no_output_____ ###Markdown 3) Get necessary metrics on test set (for Adult dataset the metrics are accuracy and pRule). ###Code # Create model with obtained hyperparameters alpha, alpha', beta, beta' a_5 = my_res_5.x model_5 = ReweightedClassifier(LogisticRegression, [a_5[0], a_5[1]], [a_5[2], a_5[3]], params = {"max_iter": 4000, 'solver':'liblinear'}) # Train model on X_train model_5.fit(X_train_5, y_train_5, X_test_5, y_test_5, minority_idx_5, verbose=False) # Calculate metrics (pRule, accuracy) on X_test accuracy_test_5, pRule_test_5 = model_5.get_metrics_test(X_test_5, y_test_5, minority_idx_test_5) print('ASR+CULEP for X_test') print(f"prule = {pRule_test_5:.6}, accuracy = {accuracy_test_5:.6}") print(f"prule + accuracy = {(pRule_test_5 + accuracy_test_5):.6}") ###Output ASR+CULEP for X_test prule = 0.990393, accuracy = 0.790214 prule + accuracy = 1.78061 ###Markdown 4) For the same split train simple Logistic Regression (without ASR+CULEP) on the train set. Then obtain necessary metrics on the test set. ###Code # Fit LogisticRegression on X_train model_simple = LogisticRegression(max_iter=4000, solver='liblinear') model_simple.fit(X_train_5, y_train_5) # Get predictions for X_test prediction = model_simple.predict(X_test_5) # Obtain indexes for sensitive and non-sensitive groups majority_idx_test_5 = set(np.linspace(0, len(prediction) - 1, len(prediction), dtype = int)).difference(minority_idx_test_5) minority = prediction[minority_idx_test_5].mean() majority = prediction[list(majority_idx_test_5)].mean() # Calculate metrics on X_test prule_simple = min(minority/majority, majority/minority) accuracy_simple = accuracy_score(prediction, y_test_5) print('Without ASR+CULEP for X_test') print(f"prule = {prule_simple:.6}, accuracy = {accuracy_simple:.6}") print(f"prule + accuracy = {(prule_simple + accuracy_simple):.6}") ###Output Without ASR+CULEP for X_test prule = 0.801194, accuracy = 0.851566 prule + accuracy = 1.65276 ###Markdown Results ###Code results = {'prule': [], 'accuracy': [], 'a': []} results['accuracy'] = [accuracy_test_1, accuracy_test_2, accuracy_test_3, accuracy_test_4, accuracy_test_5] results['prule'] = [pRule_test_1, pRule_test_2, pRule_test_3, pRule_test_4, pRule_test_5] results['a'] = [a_1, a_2, a_3, a_4, a_5] pd.DataFrame(results).to_csv("./results/adult_results.csv") ###Output _____no_output_____
Extraction_Based_Text_Summarization.ipynb
###Markdown İçerik* [Gerekli Kütüphaneler](Gerekli-Kütüphaneler)* [Çıkarım Bazlı Özetleme](Çıkarım-Bazlı-Özetleme)* [Örnek Kullanım](Örnek-Kullanım) Gerekli Kütüphaneler ###Code import pandas as pd import numpy as np from nltk.corpus import stopwords import heapq from gensim.summarization import keywords from nltk import sent_tokenize from sklearn.metrics.pairwise import cosine_similarity from gensim.models import KeyedVectors import tensorflow as tf import networkx as nx import re import numpy as np import json import pickle from keras.models import model_from_json from keras.models import load_model ###Output _____no_output_____ ###Markdown Çıkarım Bazlı Özetleme ###Code class extraction_based_sum(): def __init__(self): # Modelimizi kokbulma.json dosyasından okuyoruz. self.jstr = json.loads(open('kokbulma.json').read()) self.model = model_from_json(self.jstr) # Sonrasında model.hdf5 dosyasından önceden eğitilmiş 1.2 milyon kelimelik ağırlıklarımızı alıyoruz. self.model.load_weights('model.hdf5') # trmodel.dms[2] Türkçe Word2Vec modeli için kullandığımız hazır bir model. self.word_tr = KeyedVectors.load_word2vec_format('trmodel.dms', binary=True) # datafile.pkl dosyasının içerisinde Türkçe harfler, kelime uzunluğu gibi özellikler tutuluyor. fp = open('datafile.pkl','rb') data = pickle.load(fp) fp.close() self.chars = data['chars'] self.charlen = data['charlen'] self.maxlen = data['maxlen'] def encode(self,word,maxlen=22,is_pad_pre=False): # Bu methodda, kelimelerimizin uzunluklarını kontrol ediyoruz, # ve kelimelerimizi matris formuna dönüştürüyoruz. wlen = len(str(word)) if wlen > maxlen: word = word[:maxlen] word = str(word).lower() pad = maxlen - len(word) if is_pad_pre : word = pad*' '+word else: word = word + pad*' ' mat = [] for w in word: vec = np.zeros((self.charlen)) if w in self.chars: ix = self.chars.index(w) vec[ix] = 1 mat.append(vec) return np.array(mat) def decode(self,mat): # Encode methodunda oluşturulan matrisi bu methodda tekrar kelimeye dönüştürüyoruz. word = "" for i in range(mat.shape[0]): word += self.chars[np.argmax(mat[i,:])] return word.strip() def kokBul(self,word): # Bu methodda ise encoder ve decoder methodları kullanılarak elimizdeki kelimenin modelimize göre # kök sonucunu buluyoruz. X = [] w = self.encode(word) X.append(w) X = np.array(X) yp = self.model.predict(X) return self.decode(yp[0]) def cleanText(self,text): # Bu methodda, elimizdeki metnin temizliğini, 1.2 milyon kelimeyle üretilmiş, kök bulma konusunda # %99.94 başarı oranına sahip 'Ka|Ve Stemmer' modelimizle köklerine ayırıp Türkçe'deki # durak kelimelerinden(stopwords) arındırarak TextRank algoritmasının daha iyi sonuçlar vermesini # sağlıyoruz. Kullandığımız model deeplearningtürkiye'nin 'Kelime Kök Ayırıcı' modeli üzerine # ve TsCorpus'un sağladığı kök analizi sonuçlarına göre kendimiz oluşturduk.[1][4] text_file = open("turkce-stop-words.txt", "r") lines = text_file.readlines() self.stop_words = [] for line in lines: self.stop_words.append(line[:-1]) self.stop_words.append('bir') self.stop_words.append('bin') text = re.sub(r'[\s]',' ',text) sentences = sent_tokenize(text) self.clean_sentences = [] for sentence in sentences: temp_list = [] for word in sentence.split(): if (word.lower() not in self.stop_words) and (len(word) >= 2): temp_list.append(self.kokBul(word)) self.clean_sentences.append(' '.join(temp_list)) # Bu kısımda ise Hasan Kemik tarafından önceden oluşturulmuş 'Çıkarım Tabanlı Metin Özetleme' # kodu[3] üzerine 'Ka|Ve Stemmer' modülü entegre edilerek geliştirilmiştir. # Word2Vec modeline göre benzerlik matrisi oluşturduktan sonra, networkx kütüphanesi kullanılarak, # cümle skorlarına karar veriyoruz. sentence_vectors = [] for sentence in self.clean_sentences: for word in sentence.split(): try: v = word_tr[word.lower()] except: v = np.zeros(400) sentence_vectors.append(v) sim_mat = np.zeros([len(sentences), len(sentences)]) for i in range(len(sentences)): for j in range(len(sentences)): if i != j: sim_mat[i][j] = cosine_similarity(sentence_vectors[i].reshape(1,400), sentence_vectors[j].reshape(1,400))[0,0] nx_graph = nx.from_numpy_array(sim_mat) scores = nx.pagerank(nx_graph) ranked_sentences = sorted(((scores[i],s) for i,s in enumerate(sentences)), reverse=True) return ranked_sentences def get_sentences(self,text,sum_length): # Bu methodda ise, temizlediğimiz ve skorladığımız metnimizden 'n' tane cümleyi özet olarak # sisteme geri dönüyoruz. ranked_sentences = self.cleanText(text) summary = [] for i in range(sum_length): summary.append(ranked_sentences[i][1]) return " ".join(summary) def get_keywords(self,text,ratio): # Bu methodda ise, gensim kütüphanesinin anahtar kelime çıkarım mekanizması kullanılarak, # metindeki en önemki stop word olmayan kelimelerin bulunmasını hedefledik x = self.cleanText(text) text_keywords = keywords(text,ratio=ratio).split("\n") valid_keywords = [] for keyword in text_keywords: if keyword not in self.stop_words: valid_keywords.append(keyword) return valid_keywords ###Output _____no_output_____ ###Markdown Örnek Kullanım ###Code ex_sum = extraction_based_sum() text = """ Transition-One adlı girişim, donanım iyileştirme teknolojisiyle eski dizel araçları elektrikli araca dönüştürüyor. Fransız girişimi Transition-One, eski dizel araçlara 8 bin 500 Euro karşılığında elektrik motoru, batarya ve bağlantılı bir gösterge paneli ekleyen donanım iyileştirme teknolojisi geliştirdi. Transition-One kurucusu Aymeric Libeau “Yeni bir elektrikli arabaya 20 bin Euro veremeyecek durumdaki insanlara ulaşmayı hedefliyorum.” diyor. 2009 model bir Renault Twingo’yu 180 kilometre menzilli bir elektrikli araca dönüştürdüğü ilk prototipini gösteren Libeau “Avrupa’da en çok satılan modelleri elektrikli arabalara dönüştürüyoruz.” dedi. Dönüşüm bir günden az sürüyor. Libeau, bu yılın sonuna kadar Fransız ve Avrupalı düzenleyicilerden onay almayı umuyor. Ayrıca talep durumunu test etmek için Eylül ayında ön sipariş almaya başlayacak. Otomobil üreticileri, Avrupa’daki katı karbon salınımı düzenlemelerine uyabilmek için hızla elektrikli araba üretmeye çalışıyor. Eski dizel arabaları yasaklayan şehirlerin sayısı her geçen gün artıyor. Önümüzdeki on yıl içinde de çok daha fazla Avrupa şehri fosil yakıtlı arabalara erişimi kesecek. Libeau’nun yöntemiyle dizel aracı elektrikliye dönüştürme işlemi bir günden az sürüyor. """ ex_sum.get_sentences(text,5) ex_sum.get_keywords(text,0.25) ###Output _____no_output_____
RNN_Text_Gen_Model.ipynb
###Markdown RNN Model Load Text ###Code # Load the Drive helper and mount from google.colab import drive # This will prompt for authorization. drive.mount('/content/drive') # set working directory import os os.chdir("/content/drive/My Drive/Python 101/") os.getcwd() # load doc into memory def load_doc(filename): # open the file as read only file = open(filename, 'r') # read all text text = file.read() # close the file file.close() return text # load document in_filename = 'plato.txt' doc = load_doc(in_filename) print(doc[:200]) ###Output BOOK I. I went down yesterday to the Piraeus with Glaucon the son of Ariston, that I might offer up my prayers to the goddess (Bendis, the Thracian Artemis.); and also because I wanted to see in wh ###Markdown Clean TextWe need to transform the raw text into a sequence of tokens or words that we can use as a source to train the model.Based on reviewing the raw text (above), below are some specific operations we will perform to clean the text. You may want to explore more cleaning operations yourself as an extension.Replace ‘–‘ with a white space so we can split words better.Split words based on white space.Remove all punctuation from words to reduce the vocabulary size (e.g. ‘What?’ becomes ‘What’).Remove all words that are not alphabetic to remove standalone punctuation tokens.Normalize all words to lowercase to reduce the vocabulary size.Vocabulary size is a big deal with language modeling. A smaller vocabulary results in a smaller model that trains faster.We can implement each of these cleaning operations in this order in a function. Below is the function clean_doc() that takes a loaded document as an argument and returns an array of clean tokens. ###Code import string # turn a doc into clean tokens def clean_doc(doc): # replace '--' with a space ' ' doc = doc.replace('--', ' ') # split into tokens by white space tokens = doc.split() # remove punctuation from each token table = str.maketrans('', '', string.punctuation) tokens = [w.translate(table) for w in tokens] # remove remaining tokens that are not alphabetic tokens = [word for word in tokens if word.isalpha()] # make lower case tokens = [word.lower() for word in tokens] return tokens # clean document tokens = clean_doc(doc) print(tokens[:200]) print('Total Tokens: %d' % len(tokens)) print('Unique Tokens: %d' % len(set(tokens))) ###Output ['book', 'i', 'i', 'went', 'down', 'yesterday', 'to', 'the', 'piraeus', 'with', 'glaucon', 'the', 'son', 'of', 'ariston', 'that', 'i', 'might', 'offer', 'up', 'my', 'prayers', 'to', 'the', 'goddess', 'bendis', 'the', 'thracian', 'artemis', 'and', 'also', 'because', 'i', 'wanted', 'to', 'see', 'in', 'what', 'manner', 'they', 'would', 'celebrate', 'the', 'festival', 'which', 'was', 'a', 'new', 'thing', 'i', 'was', 'delighted', 'with', 'the', 'procession', 'of', 'the', 'inhabitants', 'but', 'that', 'of', 'the', 'thracians', 'was', 'equally', 'if', 'not', 'more', 'beautiful', 'when', 'we', 'had', 'finished', 'our', 'prayers', 'and', 'viewed', 'the', 'spectacle', 'we', 'turned', 'in', 'the', 'direction', 'of', 'the', 'city', 'and', 'at', 'that', 'instant', 'polemarchus', 'the', 'son', 'of', 'cephalus', 'chanced', 'to', 'catch', 'sight', 'of', 'us', 'from', 'a', 'distance', 'as', 'we', 'were', 'starting', 'on', 'our', 'way', 'home', 'and', 'told', 'his', 'servant', 'to', 'run', 'and', 'bid', 'us', 'wait', 'for', 'him', 'the', 'servant', 'took', 'hold', 'of', 'me', 'by', 'the', 'cloak', 'behind', 'and', 'said', 'polemarchus', 'desires', 'you', 'to', 'wait', 'i', 'turned', 'round', 'and', 'asked', 'him', 'where', 'his', 'master', 'was', 'there', 'he', 'is', 'said', 'the', 'youth', 'coming', 'after', 'you', 'if', 'you', 'will', 'only', 'wait', 'certainly', 'we', 'will', 'said', 'glaucon', 'and', 'in', 'a', 'few', 'minutes', 'polemarchus', 'appeared', 'and', 'with', 'him', 'adeimantus', 'glaucons', 'brother', 'niceratus', 'the', 'son', 'of', 'nicias', 'and', 'several', 'others', 'who', 'had', 'been', 'at', 'the', 'procession', 'polemarchus', 'said'] Total Tokens: 121527 Unique Tokens: 7671 ###Markdown Organize in Sequences ###Code # organize into sequences of tokens length = 50 + 1 sequences = list() for i in range(length, len(tokens)): # select sequence of tokens seq = tokens[i-length:i] # convert into a line line = ' '.join(seq) # store sequences.append(line) print('Total Sequences: %d' % len(sequences)) # save tokens to file, one dialog per line def save_doc(lines, filename): data = '\n'.join(lines) file = open(filename, 'w') file.write(data) file.close() # save sequences to file out_filename = 'republic_sequences.txt' save_doc(sequences, out_filename) ###Output _____no_output_____ ###Markdown Load Sequences ###Code # load doc into memory def load_doc(filename): # open the file as read only file = open(filename, 'r') # read all text text = file.read() # close the file file.close() return text # load in_filename = 'republic_sequences.txt' doc = load_doc(in_filename) lines = doc.split('\n') # load packages from numpy import array from pickle import dump from keras.preprocessing.text import Tokenizer from keras.utils import to_categorical from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM from keras.layers import Embedding # integer encode sequences of words tokenizer = Tokenizer() tokenizer.fit_on_texts(lines) sequences = tokenizer.texts_to_sequences(lines) # vocabulary size vocab_size = len(tokenizer.word_index) + 1 vocab_size # separate into input and output sequences = array(sequences) X, y = sequences[:,:-1], sequences[:,-1] y = to_categorical(y, num_classes=vocab_size) seq_length = X.shape[1] # define model model = Sequential() model.add(Embedding(vocab_size, 50, input_length=seq_length)) model.add(LSTM(100, return_sequences=True)) model.add(LSTM(100)) model.add(Dense(100, activation='relu')) model.add(Dense(vocab_size, activation='softmax')) print(model.summary()) # compile model model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) # fit model model.fit(X, y, batch_size=256, epochs=20) # save the model to file model.save('model.h5') # save the tokenizer dump(tokenizer, open('tokenizer.pkl', 'wb')) from google.colab import drive drive.mount('/content/drive') ###Output _____no_output_____ ###Markdown Use the Model ###Code from random import randint from pickle import load from keras.models import load_model from keras.preprocessing.sequence import pad_sequences # load doc into memory def load_doc(filename): # open the file as read only file = open(filename, 'r') # read all text text = file.read() # close the file file.close() return text # generate a sequence from a language model def generate_seq(model, tokenizer, seq_length, seed_text, n_words): result = list() in_text = seed_text # generate a fixed number of words for _ in range(n_words): # encode the text as integer encoded = tokenizer.texts_to_sequences([in_text])[0] # truncate sequences to a fixed length encoded = pad_sequences([encoded], maxlen=seq_length, truncating='pre') # predict probabilities for each word yhat = model.predict_classes(encoded, verbose=0) # map predicted word index to word out_word = '' for word, index in tokenizer.word_index.items(): if index == yhat: out_word = word break # append to input in_text += ' ' + out_word result.append(out_word) return ' '.join(result) # load cleaned text sequences in_filename = 'republic_sequences.txt' doc = load_doc(in_filename) lines = doc.split('\n') seq_length = len(lines[0].split()) - 1 # load the model model = load_model('model.h5') # load the tokenizer tokenizer = load(open('tokenizer.pkl', 'rb')) # select a seed text seed_text = lines[randint(0,len(lines))] print(seed_text + '\n') # generate new text generated = generate_seq(model, tokenizer, seq_length, seed_text, 50) print(generated) lines[1] seed_text ###Output _____no_output_____
NREL/alaska_wave.ipynb
###Markdown NREL WAVE data Alaska This notebook demonstrates basic usage of the National Renewable Energy Laboratory (NREL) Wave data. More complete examples can be found here: https://github.com/NREL/hsds-examples. ###Code %matplotlib inline import h5pyd import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mpimg h5pyd.version.version # should be >= 0.4.2 ! hsinfo # In the shell, use the --bucket option to list files from NREL's S3 bucket ! hsls --bucket nrel-pds-hsds -H -v /nrel/US_wave/Alaska/ # Open the wind data "file". Use the bucket param to get data from NREL's S3 bucket %time f = h5pyd.File("/nrel/US_wave/Alaska/Alaska_wave_1991.h5", 'r', bucket="nrel-pds-hsds") # attributes can be used to provide desriptions of the content for k in f.attrs: print(f"{k}: {f.attrs[k]}") list(f) # list the datasets in the file # get the windspeed at 80 meters dset = f['significant_wave_height'] dset.id.id # each object is identified with a guid dset.shape # shape is three-dimensional time x lat x lon dset.dtype # type is four byte floats # chunks describe how the dataset data is stored # 'H5D_CHUNKED_REF_INDIRECT' is used to reference chunks stored in an external HDF5 file dset.chunks dset.shape[0] * dset.shape[1] * 4 # ~40 GB per dataset # read one slice of the data %time tseries = dset[::,12345] len(tseries) tseries.min(), tseries.max(), tseries.mean() x = range(len(tseries)) plt.plot(x, tseries) ###Output _____no_output_____
Proyecto/src/Proyecto_opti_tests.ipynb
###Markdown Proyecto - Optimización I Oscar Esaú Peralta Rosales y Stack Sánchez Pablo Antonio Maestría en computación - CIMAT Parte 2: Pruebas y comparaciones A continuación se presenta la implementación del paper *On the acceleration of the Barzilai-Borwein method*Se puede acceder a él a través de:https://arxiv.org/abs/2001.02335 ###Code from time import time from typing import Callable, Dict, Tuple from collections import namedtuple import numpy as np from scipy import linalg, optimize import matplotlib.pyplot as plt import rosembrock import wood ###Output _____no_output_____ ###Markdown Clase con los optimizadores ###Code class ANGM(): def __init__(self, ls_variant=0): self.__clear() self.ls_v = ls_variant def __clear(self): """ Reiniciliza los logs """ self.x_log = [] self.f_log = [] self.g_norm_log = [] self.x_best = None self.iters = 0 def __get_q(self, g_k, gk_prev): """ Retorna la aproximación a q como se define en el paper """ zeros = g_k==0 g_k[zeros] = 1 qk = gk_prev**2 / g_k qk[zeros] = 0 return qk def __get_alpha_sd(self, g_k, H_k): """ Retorna el valor de alṕha para descenso de gradiente estándar """ alpha_sd = g_k.dot(g_k) / g_k@H_k@g_k return alpha_sd def __get_alpha_bb1(self, qk_prev, g_k, H_k): """ Retorna el nuevo cálculo para BB1 propuesto """ alpha_sd = 1/self.__get_alpha_sd(g_k, H_k) qAq = qk_prev@H_k@qk_prev qk_norm = qk_prev.dot(qk_prev) gk_norm = g_k.dot(g_k) qAg = qk_prev@H_k@g_k raiz = ((qAq/qk_norm - alpha_sd)**2 + 4*qAg / (qk_norm * gk_norm)) den = qAq/qk_norm + alpha_sd + np.sqrt(raiz) return 2/den def __get_alpha_mg(self, g_k, H_k ): """ Retorna el cálculo de alpha para minimal gradient """ return (g_k@H_k@g_k) / (g_k@H_k@H_k@g_k) def __get_alpha_k(self, qk, H_k): """ Retorna el cálculo de alpha gorrito para la obtencion de BB2 """ return self.__get_alpha_mg(qk, H_k) def __get_gamma_k(self, qk_prev, g_k, H_k): """ Retorna el valor de gamma usado para calcular BB2 """ return 4 * (qk_prev@H_k@H_k@g_k)**2 / (qk_prev@H_k@qk_prev * g_k@H_k@g_k) def __get_alpha_bb2(self, qk_prev, H_k, g_k, alpha_k_prev, alpha_mg): """ Retorna la nueva aproximación a BB2 """ alpha_mg = 1 / alpha_mg gamma_k = self.__get_gamma_k(qk_prev, g_k, H_k) alpha_k_prev = 1 / alpha_k_prev raiz= (alpha_k_prev - alpha_mg)**2 + gamma_k den = alpha_k_prev + alpha_mg + np.sqrt(np.abs(raiz)) return 2 / den def optimize_BB_standard(self, X: np.array, f: Callable[[np.array], np.array], g: Callable[[np.array], np.array], a0: float = 0.001, use_BB1 = True, tol_g: float=1e-12, mxitr: int=1000, **kwargs): """ Implementación del método optimizador de BB estandar Args: X: Punto inicial f: función objetivo g: Derivada de la función objetivo a0: Valor de tamaño de paso alpha inicial t1: Valor de tao 1 para el nuevo monotone stepsize BB2 t2: Valor de tao 2 para el nuevo monotone stepsize BB2 tol_g: Tolerancia para criterio con la norma del gradiente mxitr: Máximo número de iteraciones use_BB1: Inidica si se debe usar la fórmula BB1 sino se usa BB2 kwargs: f_kwargs: Diccionario con parámetros extra para la función objetivo g_kwargs: Diccionario con parámetros extra para la derivada de la función objetivo """ self.__clear() x_k = X g_k = g(x_k, **kwargs.get('g_kwargs', {})) x_k_prev = None gk_prev= None self.x_log.append(x_k) self.g_norm_log.append(np.linalg.norm(g_k)) self.f_log.append(f(x_k, **kwargs.get('f_kwargs', {}))) while self.g_norm_log[-1] > tol_g and self.iters < mxitr: alpha_ok = a0 if self.iters == 0 : alpha_ok = a0 else: sk= x_k - x_k_prev yk= g_k - gk_prev if use_BB1: alpha_ok = sk.dot(sk)/sk.dot(yk) else: alpha_ok = sk.dot(yk)/yk.dot(yk) x_k_prev = x_k x_k = x_k - alpha_ok * g_k gk_prev = g_k g_k = g(x_k, **kwargs.get('g_kwargs', {})) self.x_log.append(x_k) self.g_norm_log.append(np.linalg.norm(g_k)) self.f_log.append(f(x_k, **kwargs.get('f_kwargs', {}))) self.iters +=1 self.x_best = x_k def optimize_SDC(self, X: np.array, f: Callable[[np.array], np.array], g: Callable[[np.array], np.array], h: np.array=None, tol_g: float=1e-12, mxitr: int=1000, **kwargs): """ Implementación del método optimizador para SDC Args: X: Punto inicial f: función objetivo g: Derivada de la función objetivo a0: Valor de tamaño de paso alpha inicial tol_g: Tolerancia para criterio con la norma del gradiente mxitr: Máximo número de iteraciones use_BB1: Inidica si se debe usar la fórmula BB1 sino se usa BB2 kwargs: f_kwargs: Diccionario con parámetros extra para la función objetivo g_kwargs: Diccionario con parámetros extra para la derivada de la función objetivo """ self.__clear() x_k = X g_k = g(x_k, **kwargs.get('g_kwargs', {})) H_k = h(x_k, **kwargs.get('h_kwargs', {})) self.x_log.append(x_k) self.g_norm_log.append(np.linalg.norm(g_k)) self.f_log.append(f(x_k, **kwargs.get('f_kwargs', {}))) while self.g_norm_log[-1] > tol_g and self.iters < mxitr: alpha= g_k.dot(g_k)/g_k@H_k@g_k x_k = x_k - alpha* g_k g_k = g(x_k, **kwargs.get('g_kwargs', {})) H_k = h(x_k, **kwargs.get('h_kwargs', {})) self.x_log.append(x_k) self.g_norm_log.append(np.linalg.norm(g_k)) self.f_log.append(f(x_k, **kwargs.get('f_kwargs', {}))) H_k = h(x_k, **kwargs.get('h_kwargs', {})) self.iters +=1 self.x_best = x_k def optimize_v1(self, X: np.array, f: Callable[[np.array], np.array], g: Callable[[np.array], np.array], h: np.array=None, a0: float = 0.001, t1: float = 0.1, t2: float = 1, tol_g: float=1e-12, mxitr: int=1000, **kwargs): """ Implementación del método optimizador para el método de ANGM Args: X: Punto inicial f: función objetivo g: Derivada de la función objetivo a0: Valor de tamaño de paso alpha inicial t1: Valor de tao 1 para el nuevo monotone stepsize BB2 t2: Valor de tao 2 para el nuevo monotone stepsize BB2 tol_g: Tolerancia para criterio con la norma del gradiente mxitr: Máximo número de iteraciones use_BB1: Inidica si se debe usar la fórmula BB1 sino se usa BB2 kwargs: f_kwargs: Diccionario con parámetros extra para la función objetivo g_kwargs: Diccionario con parámetros extra para la derivada de la función objetivo """ self.__clear() x_k = X g_k = g(x_k, **kwargs.get('g_kwargs', {})) H_k = h(x_k, **kwargs.get('h_kwargs', {})) x_k_prev = None gk_prev= None qk_prev = None qk = None alpha_k = None alpha_k_prev = None alpha_bb2 = None alpha_mg= self.__get_alpha_mg(g_k, H_k) ak_bb2 = None ak_bb2_prev = None ak_bb1=None self.x_log.append(x_k) self.g_norm_log.append(np.linalg.norm(g_k)) self.f_log.append(f(x_k, **kwargs.get('f_kwargs', {}))) while self.g_norm_log[-1] > tol_g and self.iters < mxitr: alpha_ok = a0 if self.iters >= 1: qk_prev = qk qk = self.__get_q(g_k, gk_prev) sk= x_k - x_k_prev yk= g_k - gk_prev ak_bb1 = sk.dot(sk)/sk.dot(yk) ak_bb2_prev=ak_bb2 ak_bb2 = sk.dot(yk)/yk.dot(yk) alpha_k_prev = alpha_k alpha_k = self.__get_alpha_k(qk, H_k) alpha_ok = ak_bb1 if self.iters >= 2: alpha_bb2 = self.__get_alpha_bb2(qk_prev, H_k, g_k, alpha_k_prev, alpha_mg) if ak_bb2 < t1*ak_bb1 and self.g_norm_log[-2] < t2*self.g_norm_log[-1]: alpha_ok = min(ak_bb2, ak_bb2_prev) elif ak_bb2 < t1*ak_bb1 and self.g_norm_log[-2] >= t2*self.g_norm_log[-1]: alpha_ok = alpha_bb2 else: alpha_ok = ak_bb1 x_k_prev = x_k x_k = x_k - alpha_ok * g_k gk_prev = g_k g_k = g(x_k, **kwargs.get('g_kwargs', {})) H_k = h(x_k, **kwargs.get('h_kwargs', {})) alpha_mg= self.__get_alpha_mg(g_k, H_k) self.x_log.append(x_k) self.g_norm_log.append(np.linalg.norm(g_k)) self.f_log.append(f(x_k, **kwargs.get('f_kwargs', {}))) self.iters +=1 self.x_best = x_k def optimize_v2(self, X: np.array, f: Callable[[np.array], np.array], g: Callable[[np.array], np.array], h: np.array=None, a0: float = 0.001, t1: float = 0.1, t2: float = 1, tol_g: float=1e-12, mxitr: int=1000, **kwargs): """ Implementación del método optimizador para ANGR1 Args: X: Punto inicial f: función objetivo g: Derivada de la función objetivo a0: Valor de tamaño de paso alpha inicial t1: Valor de tao 1 para el nuevo monotone stepsize BB2 t2: Valor de tao 2 para el nuevo monotone stepsize BB2 tol_g: Tolerancia para criterio con la norma del gradiente mxitr: Máximo número de iteraciones use_BB1: Inidica si se debe usar la fórmula BB1 sino se usa BB2 kwargs: f_kwargs: Diccionario con parámetros extra para la función objetivo g_kwargs: Diccionario con parámetros extra para la derivada de la función objetivo """ self.__clear() x_k = X g_k = g(x_k, **kwargs.get('g_kwargs', {})) H_k = h(x_k, **kwargs.get('h_kwargs', {})) x_k_prev = None gk_prev= None qk_pprev = None qk_prev = None qk = None alpha_k = None alpha_k_prev = None alpha_k_pprev= None alpha_bb2 = None alpha_mg= self.__get_alpha_mg(g_k, H_k) H_k_prev= None alpha_ok =None alpha_ok_prev=None ak_bb2 = None ak_bb2_prev = None ak_bb1=None self.x_log.append(x_k) self.g_norm_log.append(np.linalg.norm(g_k)) self.f_log.append(f(x_k, **kwargs.get('f_kwargs', {}))) while self.g_norm_log[-1] > tol_g and self.iters < mxitr: alpha_ok = a0 if self.iters >= 1: qk_pprev = qk_prev qk_prev = qk qk = self.__get_q(g_k, gk_prev) sk= x_k - x_k_prev yk= g_k - gk_prev ak_bb1 = sk.dot(sk)/sk.dot(yk) ak_bb2_prev=ak_bb2 ak_bb2 = sk.dot(yk)/yk.dot(yk) alpha_k_pprev = alpha_k_prev alpha_k_prev = alpha_k alpha_k = self.__get_alpha_k(qk, H_k) alpha_ok = ak_bb1 if self.iters >= 3: alpha_bb2 = self.__get_alpha_bb2(qk_pprev, H_k_prev, gk_prev, alpha_k_pprev, ak_bb2) if ak_bb2 < t1*ak_bb1 and self.g_norm_log[-2] < t2*self.g_norm_log[-1]: alpha_ok = min(ak_bb2, ak_bb2_prev) elif ak_bb2 < t1*ak_bb1 and self.g_norm_log[-2] >= t2*self.g_norm_log[-1]: alpha_ok = alpha_bb2 else: alpha_ok = ak_bb1 x_k_prev = x_k x_k = x_k - alpha_ok * g_k gk_prev = g_k g_k = g(x_k, **kwargs.get('g_kwargs', {})) H_k_prev = H_k H_k = h(x_k, **kwargs.get('h_kwargs', {})) self.x_log.append(x_k) self.g_norm_log.append(np.linalg.norm(g_k)) self.f_log.append(f(x_k, **kwargs.get('f_kwargs', {}))) self.iters +=1 self.x_best = x_k def optimize_v3(self, X: np.array, f: Callable[[np.array], np.array], g: Callable[[np.array], np.array], h: np.array=None, a0: float = 0.001, t1: float = 0.1, t2: float = 1, tol_g: float=1e-12, mxitr: int=1000, **kwargs): """ Implementación del método optimizador para ANGR2 Args: X: Punto inicial f: función objetivo g: Derivada de la función objetivo a0: Valor de tamaño de paso alpha inicial t1: Valor de tao 1 para el nuevo monotone stepsize BB2 t2: Valor de tao 2 para el nuevo monotone stepsize BB2 tol_g: Tolerancia para criterio con la norma del gradiente mxitr: Máximo número de iteraciones use_BB1: Inidica si se debe usar la fórmula BB1 sino se usa BB2 kwargs: f_kwargs: Diccionario con parámetros extra para la función objetivo g_kwargs: Diccionario con parámetros extra para la derivada de la función objetivo """ self.__clear() x_k = X g_k = g(x_k, **kwargs.get('g_kwargs', {})) H_k = h(x_k, **kwargs.get('h_kwargs', {})) x_k_prev = None gk_prev= None qk_prev = None qk = None alpha_k = None alpha_k_prev = None alpha_k_pprev=None alpha_bb2 = None alpha_mg= self.__get_alpha_mg(g_k, H_k) alpha_ok_prev = None ak_bb2 = None ak_bb2_prev = None ak_bb1=None alpha_ok = None self.x_log.append(x_k) self.g_norm_log.append(np.linalg.norm(g_k)) self.f_log.append(f(x_k, **kwargs.get('f_kwargs', {}))) while self.g_norm_log[-1] > tol_g and self.iters < mxitr: alpha_ok_prev = alpha_ok alpha_ok = a0 if self.iters >= 1: qk_prev = qk qk = self.__get_q(g_k, gk_prev) sk= x_k - x_k_prev yk= g_k - gk_prev ak_bb1 = sk.dot(sk)/sk.dot(yk) ak_bb2_prev=ak_bb2 ak_bb2 = sk.dot(yk)/yk.dot(yk) alpha_k_pprev = alpha_k_prev alpha_k_prev = alpha_k #alpha_k = self.__get_alpha_k(qk, H_k) alpha_k = alpha_ok_prev * qk.dot(qk - gk_prev) / (np.dot(qk - gk_prev,qk - gk_prev )) alpha_ok = ak_bb1 if self.iters >= 3: #alpha_bb2 = self.__get_alpha_bb2(qk_prev, H_k, g_k, alpha_k_prev, alpha_mg) if ak_bb2 < t1*ak_bb1 and self.g_norm_log[-2] < t2*self.g_norm_log[-1]: alpha_ok = min(ak_bb2, ak_bb2_prev) elif ak_bb2 < t1*ak_bb1 and self.g_norm_log[-2] >= t2*self.g_norm_log[-1]: alpha_ok = min (ak_bb2, alpha_k_pprev) else: alpha_ok = ak_bb1 x_k_prev = x_k x_k = x_k - alpha_ok * g_k gk_prev = g_k g_k = g(x_k, **kwargs.get('g_kwargs', {})) H_k = h(x_k, **kwargs.get('h_kwargs', {})) alpha_mg= self.__get_alpha_mg(g_k, H_k) self.x_log.append(x_k) self.g_norm_log.append(np.linalg.norm(g_k)) self.f_log.append(f(x_k, **kwargs.get('f_kwargs', {}))) self.iters +=1 self.x_best = x_k ###Output _____no_output_____ ###Markdown Prueba wood ###Code X = np.array([-3, -1, -3, -1], dtype=np.float64) xop = np.ones(4) B_0 = wood.hessian(X) H_0 = np.linalg.inv(B_0) B_0 = np.identity(X.shape[0]) angm = ANGM() for i in range(5): if i==0: print('BB1') params = { 'X': X, 'f': wood.function, 'g': wood.gradient, 'h': wood.hessian, 'use_BB1': False, 'a0': 0.001, 'tol_g': 1e-6, 'mxitr': 10000, 't1': 0.4, 't2': 1, } start_time = time() angm.optimize_BB_standard(**params) elapsed_time = time() - start_time if i==1: print('BB2') params = { 'X': X, 'f': wood.function, 'g': wood.gradient, 'h': wood.hessian, 'use_BB1': True, 'a0': 0.001, 'tol_g': 1e-6, 'mxitr': 10000, 't1': 0.4, 't2': 1, } start_time = time() angm.optimize_BB_standard(**params) elapsed_time = time() - start_time if i==2: print('ANGM') start_time = time() angm.optimize_v1(**params) elapsed_time = time() - start_time if i== 3: print('ANGR1') start_time = time() angm.optimize_v2(**params) elapsed_time = time() - start_time if i== 4: print('ANGR2') start_time = time() angm.optimize_v3(**params) elapsed_time = time() - start_time print("iters: %d" % angm.iters) print("g norm", np.linalg.norm(angm.g_norm_log[-1])) print("f error", angm.f_log[-1] - wood.function(xop)) print("tiempo", elapsed_time) fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4)) ax1.plot(angm.g_norm_log) ax1.set(xlabel='Iteraciones', ylabel='Valor') ax2.plot(angm.f_log) ax2.set(xlabel='Iteraciones', ylabel='Valor') plt.show() angm.x_best ###Output BB1 iters: 7234 g norm 8.965142796802929e-07 f error 5.579265043733195e-13 tiempo 0.33501482009887695 ###Markdown Prueba Wood 100 iteraciones ###Code angm = ANGM() angmv2 = ANGM() angmv3 = ANGM() t1=np.array([0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9]) print("Iter promedio, G_norm promedio, Tiempo promedio") for j in range(t1.shape[0]): ng_w1=[] it_w1=[] t_w1=[] ng_w2=[] it_w2=[] t_w2=[] ng_w3=[] it_w3=[] t_w3=[] for i in range(100): X = np.random.rand(4) params = { 'X': X, 'f': wood.function, 'g': wood.gradient, 'h': wood.hessian, 'use_BB1': False, 'a0': 0.001, 'tol_g': 1e-6, 'mxitr': 10000, 't1': t1[j], 't2': 1, } start_time = time() angm.optimize_v1(**params) elapsed_time = time() - start_time ng_w1.append(np.linalg.norm(angm.g_norm_log[-1])) it_w1.append(angm.iters) t_w1.append(elapsed_time) start_time = time() angmv2.optimize_v2(**params) elapsed_time = time() - start_time ng_w2.append(np.linalg.norm(angmv2.g_norm_log[-1])) it_w2.append(angmv2.iters) t_w2.append(elapsed_time) start_time = time() angmv3.optimize_v3(**params) elapsed_time = time() - start_time ng_w3.append(np.linalg.norm(angmv3.g_norm_log[-1])) it_w3.append(angmv3.iters) t_w3.append(elapsed_time) print('\multicolumn{1}{|c|}{\\textit{',t1[j],'}} & \multicolumn{1}{c|}{',np.mean(it_w1),'} &', '\multicolumn{1}{c|}{',format(np.mean(ng_w1),'.3e'),'} &','\multicolumn{1}{c|}{',format(np.mean(t_w1),'.3e'), '}& \multicolumn{1}{c|}{',np.mean(it_w2),'} &', '\multicolumn{1}{c|}{',format(np.mean(ng_w2),'.3e'),'} &','\multicolumn{1}{c|}{',format(np.mean(t_w2),'.3e'), '}& \multicolumn{1}{c|}{',np.mean(it_w3),'} &', '\multicolumn{1}{c|}{',format(np.mean(ng_w3),'.3e'),'} &','\multicolumn{1}{c|}{',format(np.mean(t_w3),'.3e'),'} \\\\ \hline') angmbb1 = ANGM() angmbb2 = ANGM() ng_w1=[] it_w1=[] t_w1=[] ng_w2=[] it_w2=[] t_w2=[] print("Iter promedio, G_norm promedio, Tiempo promedio") for i in range(100): X = np.random.rand(4) params = { 'X': X, 'f': wood.function, 'g': wood.gradient, 'h': wood.hessian, 'use_BB1': True, 'a0': 0.001, 'tol_g': 1e-6, 'mxitr': 10000, 't1': 0.4, 't2': 1, } params2 = { 'X': X, 'f': wood.function, 'g': wood.gradient, 'h': wood.hessian, 'use_BB1': False, 'a0': 0.001, 'tol_g': 1e-6, 'mxitr': 10000, 't1': 0.4, 't2': 1, } start_time = time() angmbb1.optimize_BB_standard(**params) elapsed_time = time() - start_time ng_w1.append(np.linalg.norm(angmbb1.g_norm_log[-1])) it_w1.append(angmbb1.iters) t_w1.append(elapsed_time) start_time = time() angmbb2.optimize_BB_standard(**params2) elapsed_time = time() - start_time ng_w2.append(np.linalg.norm(angmbb2.g_norm_log[-1])) it_w2.append(angmbb2.iters) t_w2.append(elapsed_time) print(np.mean(it_w1), '&', format(np.mean(ng_w1),'.3e'), '& \multicolumn{1}{c|}{', format(np.mean(t_w1),'.3e'), '} &' ,np.mean(it_w2), '& \multicolumn{1}{c|}{', format(np.mean(ng_w2),'.3e'),'} &',' \multicolumn{1}{c|}{', format(np.mean(t_w2),'.3e'), '} \\\\ \hline') ###Output Iter promedio, G_norm promedio, Tiempo promedio 385.14 & 4.745e-07 & \multicolumn{1}{c|}{ 1.448e-02 } & 128.41 & \multicolumn{1}{c|}{ 5.337e-07 } & \multicolumn{1}{c|}{ 4.844e-03 } \\ \hline ###Markdown Prueba Rosembrock ###Code X = np.ones(100, dtype=np.float128) X[0] = X[-2] = -1.2 #X = np.ones(100) + np.random.normal(size=100) xop = np.ones(4) B_0 = wood.hessian(X) H_0 = np.linalg.inv(B_0) B_0 = np.identity(X.shape[0]) angm = ANGM() for i in range(5): if i==0: print('BB1') params = { 'X': X, 'f': rosembrock.function, 'g': rosembrock.gradient, 'h': rosembrock.hessian, 'use_BB1': False, 'a0': 0.001, 'tol_g': 1e-6, 'mxitr': 10000, 't1': 0.4, 't2': 1, } start_time = time() angm.optimize_BB_standard(**params) elapsed_time = time() - start_time if i==1: print('BB2') params = { 'X': X, 'f': rosembrock.function, 'g': rosembrock.gradient, 'h': rosembrock.hessian, 'use_BB1': True, 'a0': 0.001, 'tol_g': 1e-6, 'mxitr': 10000, 't1': 0.4, 't2': 1, } start_time = time() angm.optimize_BB_standard(**params) elapsed_time = time() - start_time if i==2: print('ANGM') start_time = time() angm.optimize_v1(**params) elapsed_time = time() - start_time if i== 3: print('ANGR1') start_time = time() angm.optimize_v2(**params) elapsed_time = time() - start_time if i== 4: print('ANGR2') start_time = time() angm.optimize_v3(**params) elapsed_time = time() - start_time print("iters: %d" % angm.iters) print("g norm", np.linalg.norm(angm.g_norm_log[-1])) print("f error", angm.f_log[-1] - wood.function(xop)) print("tiempo", elapsed_time) fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4)) ax1.plot(angm.g_norm_log) ax1.set(xlabel='Iteraciones', ylabel='Valor') ax2.plot(angm.f_log) ax2.set(xlabel='Iteraciones', ylabel='Valor') plt.show() ###Output BB1 iters: 1087 g norm 7.1881146028523370487e-07 f error 3.9866238543014484487 tiempo 1.4007575511932373
examples/notebooks/Friedman-RA.ipynb
###Markdown A Friedmanesque Stochastic Growth ModelFriedman (1957) proposed that consumers understand that some components of income are transitory and others are permanent. This turns out to be a pretty good description of both micro and macro income dynamics, and a particularly clear way to think about the dynamics of income and consumption.Consider an economy with the following features:1. There is a permanent component of aggregate labor productivity that grows by a stochastic factor $\Psi$ and is subject to mean one IID shocks:\begin{eqnarray}P_{t+1} & = & \Psi_{t+1} P_{t}\end{eqnarray}1. "Efficiency units" of labor are hours worked $N$ multiplied by productivity per hour $P$ multiplied by a transitory shock $\Theta$: $N P \Theta$. Labor is supplied inelastically, so we can conveniently normalize the number of hours to $N = 1$. The transitory and permanent productivity shocks are assumed to be mean-one lognormally distributed variables, $\mathbb{E}_{t}[\Psi_{t+n}]=\mathbb{E}_{t}[\Theta_{t+n}]=1~\forall~n>0$.1. We define assets after all actions have been accomplished in period $t$ as the portion of market resources that have not been consumed. The assets with which the consumer ends the period are therefore\begin{eqnarray}A_{t} & = & M_{t}-C_{t}\end{eqnarray}1. Gross output is generated by a Cobb-Douglas production function, where the unconsumed assets $A_{t}$ from the previous period constitute the capital stock; the process of production is what causes depreciation. Combining these, next period's "Market resources" (current income plus what remains of capital after production) are\begin{eqnarray}M_{t+1} & = & A_{t}^{\alpha}(\Theta_{t+1} P_{t+1} N_{t+1})^{1-\alpha} + (1-\delta) A_{t}\end{eqnarray}Assuming no population growth and normalizing to $N=1$, problem of a representative consumer with Constant Relative Risk Aversion felicity $u(c)=c^{1-\rho}/(1-\rho)$ is therefore to\begin{eqnarray}V_{t}(M_{t},P_{t}) & = & \max_{C_{t}}~\left(\frac{C_{t}^{1-\rho}}{1-\rho}\right) + \beta \mathbb{E}_{t}[V_{t+1}(M_{t+1})]\\ & \text{s.t.} & \\A_{t} & = & M_{t}-C_{t} \\M_{t+1} & = & A_{t}^{\alpha}(\Theta_{t+1} P_{t+1})^{1-\alpha} + (1-\delta) A_{t}\end{eqnarray} Now consider the related problem:\begin{eqnarray}v_{t}(m_{t}) & = & \max_{c_{t}}~\left(\frac{c_{t}^{1-\rho}}{1-\rho}\right) + \beta \mathbb{E}_{t}[\Psi_{t+1}^{1-\rho}v_{t+1}(m_{t+1})]\\ & \text{s.t.} & \\a_{t} & = & m_{t}-c_{t} \\m_{t+1} & = & (a_{t}/\Psi_{t+1})^{\alpha}\Theta_{t+1}^{1-\alpha}+(1-\delta) a_{t}/\Psi_{t+1}\end{eqnarray}whose full details are specified in the companion dolo model file. (In that file, the first equation appears in the "definitions" block, and the second constitutes the "transition" equation.)It can be shown (never mind the algebra) that \begin{eqnarray}V_{t}(M_{t},P_{t}) & = & P_{t}^{1-\rho}v_{t}(m_{t})\end{eqnarray}where $m_{t}=M_{t}/P_{t}$ and $c_{t}=C_{t}/P_{t}$so that the solution to the latter problem $c_{t}(m_{t})$ yields the solution to the former problem via $C_{t}(M_{t},P_{t}) = P_{t} c_{t}(M_{t}/P_{t})$. So when we solve the simpler problem with one state variable, we have also solved the harder one with two states.In the solution, it is useful to have an expression for the expected value of next period's state at the end of the current period, $\mathfrak{v}_{t}(a_{t})=\mathbb{E}_{t}[\Psi_{t+1}^{1-\rho} v_{t+1}(m_{t+1})]$. Substituting the definition of $m_{t+1}$ then differentiating the end-of-period value function \begin{eqnarray}\mathfrak{v}_{t}(a_{t}) & = & \mathbb{E}_{t}[\Psi_{t+1}^{1-\rho}v_{t+1}(\overbrace{(a_{t}/\Psi_{t+1})^{\alpha}\Theta_{t+1}^{1-\alpha}+(1-\delta) a_{t}/\Psi_{t+1}}^{m_{t+1}})]\\ \mathfrak{v}^{a}_{t}(a_{t}) & = & \mathbb{E}_{t}\left[\Psi_{t+1}^{1-\rho}\underbrace{\left((\alpha/\Psi_{t+1})(a_{t}/\Psi_{t+1})^{\alpha-1}\Theta_{t+1}^{1-\alpha}+(1-\delta)/\Psi_{t+1}) \right)}_{\equiv R_{t+1}=dm_{t+1}/da_{t}}v^{m}_{t+1}(m_{t+1})\right]\\ & = & \mathbb{E}_{t}\left[\Psi_{t+1}^{-\rho}\left(\alpha(a_{t}/\Psi_{t+1})^{\alpha-1}\Theta_{t+1}^{1-\alpha}+(1-\delta)) \right)u^{\prime}(c_{t+1})\right]\end{eqnarray}where the last step uses the Envelope relationship $v^{m}(m_{t})=u^{\prime}(c_{t+1})$. This expression constitutes the "expectation" equation in dolo.The first order condition is:\begin{eqnarray}c_{t}^{-\rho} & = & \beta \mathbb{E}_{t}[\Psi_{t+1}^{-\rho}\left(\alpha(a_{t}/\Psi_{t+1})^{\alpha-1}\Theta_{t+1}^{1-\alpha}+(1-\delta)) \right)(c_{t+1}^{-\rho})]\\ & = & \mathbb{E}_{t}[\left(\alpha(a_{t}/\Psi_{t})^{\alpha-1}\Theta_{t+1}^{1-\alpha}+(1-\delta)\right)(c_{t+1}\Psi_{t+1})^{-\rho}]\end{eqnarray}The endogenous gridpoints method uses the fact that\begin{eqnarray}c_{t} & = & \left(\beta \mathfrak{v}^{\prime}_{t}(a_{t})\right)^{-1/\rho}\end{eqnarray}so that if we pick a grid of values of $a_{t,i}$ then from that we can generate the corresponding $c_{t,i}$ and $m_{t,i}=a_{t,i}+c_{t,i}$ without any numerical search.A convenient alternative way of expressing the Euler equation is \begin{eqnarray}0 & = & 1-\mathbb{E}_{t}[\left(\alpha(a_{t}/\Psi_{t})^{\alpha-1}\Theta_{t+1}^{1-\alpha}+(1-\delta)\right)(c_{t+1}\Psi_{t+1}/c_{t})^{-\rho}]\end{eqnarray}which constitutes the "arbitrage" equation in dolo.To solve this model in dolo we need to provide a starting point. A good starting point is the nonstochastic steady-state: ($P = \Theta = N = \ell = 1$):\begin{eqnarray}1 & = & \beta(1-\delta+ \alpha k^{\alpha-1}) \\ \beta^{-1}+\delta-1 & = & \alpha k^{\alpha-1} \\\left(\frac{\alpha}{\beta^{-1}+\delta-1}\right)^{1/(1-\alpha)} & = & k\end{eqnarray} ###Code import numpy as np from matplotlib import pyplot as plt ###Output _____no_output_____ ###Markdown Solving the Friedman RBC modelThis worksheet demonstrates how to solve the rbc_friedman model with the [dolo](http://econforge.github.io/dolo/) library and how to generate impulse responses and stochastic simulations from the solution.- This notebook is distributed with dolo in : ``examples\notebooks\``. The notebook was opened and run from that directory.- The model file is in : ``examples\global_models\``First we import the dolo library. ###Code from dolo import * ###Output _____no_output_____ ###Markdown Importing the model The RBC model is defined in a [YAML](http://www.yaml.org/spec/1.2/spec.htmlIntroduction) file which we can read locally or pull off the web. ###Code # filename = ('https://raw.githubusercontent.com/EconForge/dolo' # '/master/examples/models/compat/rbc.yaml') filename='../models/rbc_friedman_k-as-state.yaml' filename='../models/rbc_friedman_m-as-state.yaml' %cat $filename ###Output name: Friedman-RA symbols: exogenous: [lΨ, lΘ] # Ψ is the persistent shock, Θ is transitory, l means log states: [lP, m] controls: [c] expectations: [μ] values: [V] parameters: [β, ρ, δ, α, lPmean, σ_lΨ, lΘmean, σ_lΘ] rewards: [u] definitions: Ψ: exp(lΨ) Θ: exp(lΘ) P: exp(lP) a: m-c equations: arbitrage: - 1 - β*(1-δ+α*((a/Ψ(1))^(α-1))*(Θ(1)^(1-α)))*(Ψ(1)*c(1)/c)^(-ρ) | 0.0 <= c <= m # Liquidity constraint transition: - lP = lP(-1) + lΨ - m = ((a(-1)/exp(lΨ))^α)*exp(lΘ)^(α-1)+(1-δ)*(a(-1)/exp(lΨ)) # oddly, can't sub Θ(1) for exp(lΘ(1)) (same with Ψ) though it works in arbitrage value: - V = (c^(1-ρ))/(1-ρ) + β*V(1) felicity: - u = (c^(1-ρ))/(1-ρ) # Turned off because causes a strange error about how numba can't tell what type a is # expectation: # - μ =(1-δ+α*((a/exp(lΨ(1)))^(α-1))*(exp(lΘ(1))^(1-α)))*(exp(lΨ(1))*c(1)/c)^(-ρ) calibration: # parameters β : 0.99 δ : 0.025 α : 0.33 ρ: 5 σ_lΨ: 0.01 lPmean: 0 σ_lΘ: 0.01 lΘ: 0.00 lΘmean: 0.00 c_i: 1.5 c_y: 0.5 lΨ: 0.0 # endogenous variables initial values for solution (many unused) lP: lPmean r: 1/β-1 R: 1+r w: (1-α)*(Θ^(1-α))*(k/(Θ))^(α) k: (α/((1/β)+δ-1))^(1/(1-α)) y: k^α*(Θ)^(1-α)-δ*k c: y u: c^(1-ρ)/(1-ρ) V: u/(1-β) μ: (R*β)*c^(-ρ) m: (k^α)*(exp(lΘ)^(1-α))+(1-δ)*k exogenous: !Normal Sigma: [[σ_lΨ^2, 0.00] ,[0.00 , σ_lΘ^2]] domain: lP: [-2*σ_lΨ^0.5, 2*σ_lΨ^0.5] m: [ m*0.5, m*1.5] options: grid: !Cartesian n: [20, 20] # options: # grid: !Smolyak # mu: 3 # # orders: [5, 50] ###Markdown `yaml_import(filename)` reads the YAML file and generates a model object. The model file already has values for steady-state variables stated in the calibration section so we can go ahead and check that they are correct by computing the model equations at the steady state. ###Code model.residuals() ###Output _____no_output_____ ###Markdown Printing the model also lets us have a look at all the model equations and check that all residual errors are 0 at the steady-state, but with less display prescision. ###Code # print( model ) ###Output Model: ------ name: "Real Business Cycle - No Labor Choice, Permanent shocks" type: "dtcc" file: "/Volumes/Data/GitHub/llorracc/dolo/examples/models/rbc_cdc-to_030-Add-Transitory-Shocks.yaml Equations: ---------- transition 1 : 0.0000 : lP(0) == (ω) * (lP(-(1))) + e_lP(0) 2 : 0.0000 : k(0) == ((1) - (δ)) * (k(-(1))) + i(-(1)) arbitrage 1 : 0.0000 : (1) - (((β) * (((c(0)) / (c(1))) ** (ρ))) * ((1) - (δ) + rk(1))) definitions 1 : y = k**α*(exp(lP)*exp(e_lT)*n)**(1-α) 2 : c = y - i 3 : rk = α*y/k 4 : w = (1-α)*y/(n*exp(lP)*exp(e_lT)) ###Markdown Next we compute a solution to the model using a first order perturbation method (see the source for the [approximate_controls](https://github.com/EconForge/dolo/blob/master/dolo/algos/perturbation.py) function). The result is a decsion rule object. By decision rule we refer to any object that is callable and maps states to decisions. This particular decision rule object is a TaylorExpansion (see the source for the [TaylorExpansion](https://github.com/EconForge/dolo/blob/master/dolo/numeric/taylor_expansion.py) class). ###Code # This cell is for debugging purposes and can be ignored tool is needed to inspect the decision rules after they have been constructed import inspect import copy record = [] def record_dr(): """This function is called at each iteration and looks at its surrounding to record decision rules at each iteration.""" frame = inspect.currentframe().f_back dr = frame.f_locals['mdr'] it = frame.f_locals['it'] record.append((it,copy.copy(dr))) filename='../models/rbc_friedman_m-as-state.yaml' model = yaml_import(filename) model.residuals() dr_pert = perturbate(model) record = [] dr_global = time_iteration(model, hook=record_dr, initial_guess=dr_pert,verbose=False) tabs = [tabulate(model, dr_global, 'm') for it,dr in record] #plt.plot(tabs[0]['k'],tabs[0]['k'],linestyle='--',color='black') # this one approximates, #plt.plot(tabs[0]['k'],1+0*tabs[0]['m'],linestyle='--',color='black') for i,t in enumerate(tabs): if i%10==0: plt.plot(t['m'],t['c'], alpha=0.1, color='red') plt.show() tab_global = tabulate(model, dr_global, 'm') tab_pert = tabulate(model, dr_pert, 'm') from matplotlib import pyplot as plt plt.figure(figsize=(8,3.5)) plt.subplot(121) plt.plot(tab_global['m'], tab_global['c'], label='Global') plt.plot(tab_pert['m'], tab_pert['c'], label='Perturbation') plt.ylabel('c') plt.title('Consumption') plt.legend() # plt.subplot(122) # plt.plot(tab_global['m'], tab_global['n'], label='Global') # plt.plot(tab_pert['m'], tab_pert['n'], label='Perturbation') # plt.ylabel('n') # plt.title('Labour') # plt.legend() plt.tight_layout() original_delta = model.calibration['δ'] drs = [] delta_values = np.linspace(0.01, 0.04,5) for val in delta_values: model.set_calibration(δ=val) drs.append(time_iteration(model,verbose=False)) plt.figure(figsize=(5,3)) for i,dr in enumerate(drs): sim = tabulate(model, dr,'m') plt.plot(sim['m'],sim['c'], label='$\delta={}$'.format(delta_values[i])) plt.ylabel('c') plt.title('Consumption') plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) model.set_calibration(δ=original_delta) ###Output _____no_output_____ ###Markdown Decision ruleHere we plot optimal investment and labour for different levels of capital (see the source for the [plot_decision_rule](https://github.com/EconForge/dolo/blob/master/dolo/algos/simulations.py) function). It would seem, according to this, that second order perturbation does very well for the RBC model. We will revisit this issue more rigorously when we explore the deviations from the model's arbitrage section equations.Let us repeat the calculation of investment decisions for various values of the depreciation rate, $\delta$. Note that this is a comparative statics exercise, even though the models compared are dynamic. We find that more durable capital leads to higher steady state investment and slows the rate of convergence for capital (the slopes are roughly the same, which implies that relative to steady state capital investment responds stronger at higher $\delta$; this is in addition to the direct effect of depreciation). Use the model to simulate We will use the deterministic steady-state as a starting point. ###Code s0 = model.calibration['states'] print(str(model.symbols['states'])+'='+str(s0)) ###Output ['lP', 'm']=[ 0. 30.65503629] ###Markdown We also get the covariance matrix just in case. This is a one shock model so all we have is the variance of $e_z$. ###Code sigma2_ez = model.exogenous.Sigma sigma2_ez ###Output _____no_output_____ ###Markdown Impulse response functionsConsider a 10% shock to productivity. ###Code s1 = s0.copy() s1[0] *= 1.1 print(str(model.symbols['states'])+'='+str(s1)) ###Output ['lP', 'm']=[ 0. 30.65503629] ###Markdown The `simulate` function is used both to trace impulse response functions and to compute stochastic simulations. Choosing `n_exp>=1`, will result in that many "stochastic" simulations. With `n_exp = 0`, we get one single simulation without any stochastic shock (see the source for the [simulate](https://github.com/EconForge/dolo/blob/master/dolo/algos/simulations.py) function). The output is a panda table of size $H \times n_v$ where $n_v$ is the number of variables in the model and $H$ the number of dates. ###Code simulate(model, dr, N=50, T=350) from dolo.algos.simulations import response m0 = model.calibration["exogenous"] s0 = model.calibration["states"] dr.eval_ms(m0, s0) irf = response(model,dr, 'lΨ') ###Output _____no_output_____ ###Markdown Let us plot the response of consumption and assets. Note that a positive shock to the level of productivity _reduces_ the values of the variables, because they are all expressed as _ratios_ to the level of productivity. ###Code plt.figure(figsize=(8,4)) plt.subplot(221) plt.plot(irf.sel(V='lP')) plt.title('Productivity') plt.grid() plt.subplot(222) plt.plot(irf.sel(V='a')) plt.title('Assets') plt.grid() #plt.subplot(223) #plt.plot(irf.sel(V='n')) #plt.grid() #plt.title('Labour') plt.subplot(224) plt.plot(irf.sel(V='c')) plt.title('Consumption') plt.grid() plt.tight_layout() ###Output _____no_output_____ ###Markdown Note that the plotting is made using the wonderful [matplotlib](http://matplotlib.org/users/pyplot_tutorial.html) library. Read the online [tutorials](http://matplotlib.org/users/beginner.html) to learn how to customize the plots to your needs (e.g., using [latex](http://matplotlib.org/users/usetex.html) in annotations). If instead you would like to produce charts in Matlab, you can easily export the impulse response functions, or any other matrix, to a `.mat` file. ###Code # it is also possible (and fun) to use the graph visualization altair lib instead: # it is not part of dolo dependencies. To install `conda install -c conda-forge altair` import altair as alt alt.renderers.enable('notebook') df = irf.drop('N').to_pandas().reset_index() # convert to flat database base = alt.Chart(df).mark_line() ch1 = base.encode(x='T', y='lP') ch2 = base.encode(x='T', y='a') ch3 = base.encode(x='T', y='n') ch4 = base.encode(x='T', y='c') (ch1|ch2)& \ (ch2|ch4) irf_array = np.array( irf ) import scipy.io scipy.io.savemat("export.mat", {'table': irf_array} ) ###Output _____no_output_____ ###Markdown Stochastic simulationsNow we run 1000 random simulations. The result is an array of size $T\times N \times n_v$ where - $T$ the number of dates- $N$ the number of simulations- $n_v$ is the number of variables ###Code sim = simulate(model, dr_global, N=1000, T=40 ) print(sim.shape) ###Output (40, 1000, 9) ###Markdown We plot the responses of consumption, investment and labour to the stochastic path of productivity. ###Code plt.figure(figsize=(8,4)) for i in range(1000): plt.subplot(221) plt.plot(sim.sel(N=i,V='lP'), color='red', alpha=0.1) plt.subplot(222) plt.plot(sim.sel(N=i,V='a'), color='red', alpha=0.1) plt.subplot(223) plt.plot(sim.sel(N=i,V='m'), color='red', alpha=0.1) plt.subplot(224) plt.plot(sim.sel(N=i,V='c'), color='red', alpha=0.1) plt.subplot(221) plt.title('Productivity') plt.subplot(222) plt.title('Investment') plt.subplot(223) plt.title('Labour') plt.subplot(224) plt.title('Consumption') plt.tight_layout() ###Output MatplotlibDeprecationWarning:/Volumes/Sync/Sys/OSX/linked/root/usr/local/bin/anaconda/lib/python3.6/site-packages/matplotlib/figure.py:98 Adding an axes using the same arguments as a previous axes currently reuses the earlier instance. In a future version, a new instance will always be created and returned. Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance. ###Markdown We find that while the distribution of investment and labour converges quickly to the ergodic distribution, that of consumption takes noticeably longer. This is indicative of higher persistence in consumption, which in turn could be explained by permanent income considerations. Descriptive statisticsA common way to evaluate the success of the RBC model is in its ability to mimic patterns in the descriptive statistics of the real economy. Let us compute some of these descriptive statistics from our sample of stochastic simulations. First we compute growth rates: ###Code dsim = sim / sim.shift(T=1) ###Output _____no_output_____ ###Markdown Then we compute the volatility of growth rates for each simulation: ###Code volat = dsim.std(axis=1) print(volat.shape) volat ###Output _____no_output_____ ###Markdown Then we compute the mean and a confidence interval for each variable. In the generated table the first column contains the standard deviations of growth rates. The second and third columns contain the lower and upper bounds of the 95% confidence intervals, respectively. ###Code table = np.column_stack([ volat.mean(axis=0), volat.mean(axis=0)-1.96*volat.std(axis=0), volat.mean(axis=0)+1.96*volat.std(axis=0) ]) table ###Output _____no_output_____ ###Markdown We can use the [pandas](http://pandas.pydata.org/pandas-docs/stable/10min.html) library to present the results in a nice table. ###Code import pandas df = pandas.DataFrame(table, index=sim.V, columns=['Growth rate std.', 'Lower 95% bound', 'Upper 95% bound' ]) pandas.set_option('precision', 4) df ###Output _____no_output_____ ###Markdown Error measuresMarked textIt is always important to get a handle on the accuracy of the solution. The `omega` function computes and aggregates the errors for the model's arbitrage section equations. For the RBC model these are the investment demand and labor supply equations. For each equation it reports the maximum error over the domain and the mean error using ergodic distribution weights (see the source for the [omega](https://github.com/EconForge/dolo/blob/master/dolo/algos/fg/accuracy.py) function). ###Code from dolo.algos.accuracy import omega print("Perturbation solution") err_pert = omega(model, dr_pert) err_pert print("Global solution") err_global=omega(model, dr_global) err_global ###Output Global solution ###Markdown The result of `omega` is a subclass of `dict`. `omega` fills that dict with some useful information that the default print does not reveal: ###Code err_pert.keys() ###Output _____no_output_____ ###Markdown In particular the domain field contains information, like bounds and shape, that we can use to plot the spatial pattern of errors. ###Code a = err_pert['domain'].a b = err_pert['domain'].b orders = err_pert['domain'].orders errors = concatenate((err_pert['errors'].reshape( orders.tolist()+[-1] ), err_global['errors'].reshape( orders.tolist()+[-1] )), 2) figure(figsize=(8,6)) titles=["Investment demand pertubation errors", "Labor supply pertubation errors", "Investment demand global errors", "Labor supply global errors"] for i in range(4): subplot(2,2,i+1) imgplot = imshow(errors[:,:,i], origin='lower', extent=( a[0], b[0], a[1], b[1]), aspect='auto') imgplot.set_clim(0,3e-4) colorbar() xlabel('z') ylabel('k') title(titles[i]) tight_layout() ###Output _____no_output_____
Data-Science-HYD-2k19/Day-based/Day 20.ipynb
###Markdown Day 20: ###Code import pandas as pd import numpy as np ###Output _____no_output_____ ###Markdown Random number distribution: by using Normal Distribution [check]: ###Code from numpy.random import randn as rn np.random.seed(101) # To make a fixed state after generating the random series matrix_data = rn(5,4) # 5 rows, 4 columns row_labels = ['A','B','C','D','E'] # for the 5 rows col_headings = ['W','X','Y','Z'] # for the 4 columns df = pd.DataFrame(data=matrix_data, index = row_labels, columns = col_headings) df df ###Output _____no_output_____ ###Markdown Creating a new column: ###Code df['New'] = df['X'] + df['Y'] df type(df['New']) ###Output _____no_output_____ ###Markdown Deleting a column: ###Code df = df.drop('New',axis=1) #Axis = 1 for columns, Axis = 0 for rows/index df #Dropping multiple columns: df['NewXY'] = df['X'] + df['Y'] df['NewYZ'] = df['Y'] + df['Z'] df['NewXZ'] = df['X'] + df['Z'] df df = df.drop(["NewXY","NewYZ","NewXZ"],axis=1) df ###Output _____no_output_____ ###Markdown Deleting a row: ###Code df = df.drop('A') #By default the axis = 0 which is for the index df ###Output _____no_output_____ ###Markdown using inplace="True" that acts as df = df.drop(...) instead of actually writing df = : ###Code df.drop('B') df #The df is not affected #Therefore, we can use inplace that acts as df = df.drop(---) df.drop('B',axis=0,inplace = True) df ###Output _____no_output_____ ###Markdown Indexing and slicing: ###Code df ###Output _____no_output_____ ###Markdown For the columns: ###Code df['X'] type(df['X']) df.X type(df.X) df[['X']] type(df[['X']]) df[['X','Z']] type(df[['X','Z']]) ###Output _____no_output_____ ###Markdown For the rows: .loc method is for the labels(originally labels are indexes from 0,1,2..; since we have changed them to 'A','B',..'E', we use this method) ###Code df.loc['C'] # loc = location for the label(rows) df.iloc[2] #i = index, loc = index at that loc, since indexes start from 0, here C's index = 2 df.loc[['B','C']] df.iloc[['1','2']] ###Output _____no_output_____ ###Markdown For a particular element(s) by addressing both row and column: ###Code df.loc['C','Y'] #Type-I df.loc['B':'E':2,'X'::2] #Type-II df.loc[['B','D'],['X','Z']] ###Output _____no_output_____ ###Markdown Randomly getting df by re-executing the command as shown: ###Code #np.random.seed(101) matrix_data = rn(5,4) # 5 rows, 4 columns row_labels = ['A','B','C','D','E'] # for the 5 rows col_headings = ['W','X','Y','Z'] # for the 4 columns df = pd.DataFrame(data=matrix_data, index = row_labels, columns = col_headings) df #np.random.seed(101) matrix_data = rn(5,4) # 5 rows, 4 columns row_labels = ['A','B','C','D','E'] # for the 5 rows col_headings = ['W','X','Y','Z'] # for the 4 columns df = pd.DataFrame(data=matrix_data, index = row_labels, columns = col_headings) df np.random.seed(101) # To make a fixed state after generating the random series matrix_data = rn(5,4) # 5 rows, 4 columns row_labels = ['A','B','C','D','E'] # for the 5 rows col_headings = ['W','X','Y','Z'] # for the 4 columns df = pd.DataFrame(data=matrix_data, index = row_labels, columns = col_headings) df np.random.seed(101) # To make a fixed state after generating the random series matrix_data = rn(5,4) # 5 rows, 4 columns row_labels = ['A','B','C','D','E'] # for the 5 rows col_headings = ['W','X','Y','Z'] # for the 4 columns df = pd.DataFrame(data=matrix_data, index = row_labels, columns = col_headings) df ###Output _____no_output_____ ###Markdown Comparision operators: ###Code df>0 df.loc[['A','B','C']]>0 ###Output _____no_output_____ ###Markdown Q. Replacing the negative values: ###Code df booldf = df>0 bool2df = df<0 df[booldf] df[booldf] = "Pos" df[bool2df] = "Neg" df ###Output _____no_output_____ ###Markdown Creating matrix data: ###Code mat = np.matrix("22,66,140;42,70,148;30,62,125;35,68,160") mat row_label = ['A','B','C','D'] col_head = ['Age','Height','Weight'] df = pd.DataFrame(data = mat, index = row_label, columns = col_head) df ###Output _____no_output_____ ###Markdown To extract info from the matrix col wise: ###Code df['Height']>65 df1 = df['Height'][df['Height']>65] df1 ###Output _____no_output_____ ###Markdown To extract info from the matrix col wise plus other col data: ###Code df1 = df[df['Height']>65] df1 df ###Output _____no_output_____ ###Markdown Extracting info using Logical operators: ###Code booldf1 = df['Height']>65 booldf2 = df['Weight']>145 df[(booldf1)&(booldf2)] booldf1 ###Output _____no_output_____ ###Markdown Extract info from a matrix by operating on one column but excluding it in the result: ###Code df[booldf1] df[booldf1][['Age','Weight']] ###Output _____no_output_____ ###Markdown Reset the index(labels) back to 0,1,2...: ###Code df.reset_index() ###Output _____no_output_____ ###Markdown Now we have an extra column called index, the original indices have been replaced Reset the index(labels) back to 0,1,2.. and drop the extra column index_name generated : ###Code df.reset_index(drop = True) df #but here the index is retained which should not have been the case ###Output _____no_output_____ ###Markdown Creating a new column using .split() function (of numpy): ###Code df['Profession'] = "Teacher Engineer Doctor Nurse".split() df ###Output _____no_output_____ ###Markdown Replace the index by using set_index(..) method: ###Code df.set_index("Profession") ###Output _____no_output_____ ###Markdown Multi-indexing: ###Code outside = ['G1','G1','G1','G2','G2','G2'] inside = [1,2,3,1,2,3] higher_index = list(zip(outside,inside)) higher_index type(higher_index) higher_index = pd.MultiIndex.from_tuples(higher_index) higher_index type(higher_index) ###Output _____no_output_____ ###Markdown np.round(matrix_name/any_number,round_till_this_digit) method: ###Code #rn is the alias for the random given at the starting of this class (check Day 20) np.random.seed(101) df1 = pd.DataFrame(data = np.round(rn(6,3),2),index = higher_index,columns = ['A','B','C']) df1 #CHECK THE .round method: np.random.seed(101) df2 = pd.DataFrame(data = np.round(rn(6,3),5),index = higher_index,columns = ['A','B','C']) df2 pd.__version__ ###Output _____no_output_____ ###Markdown Indexing and slicing: ###Code df1.loc['G1'] df1.loc['G2'] df1.loc['G1'].loc[[1,3],['A','C']] df2.loc['G2'].loc[[2],['B']] df1.loc['G1'].loc[[1,3]][['A','C']] df1 ###Output _____no_output_____ ###Markdown Giving the names to the outside and inside indices: ###Code df1.index.names = ["outside","inner"] df1 ###Output _____no_output_____ ###Markdown Day 20: ###Code import pandas as pd import numpy as np ###Output _____no_output_____ ###Markdown Random number distribution: by using Normal Distribution [check]: ###Code from numpy.random import randn as rn np.random.seed(101) # To make a fixed state after generating the random series matrix_data = rn(5,4) # 5 rows, 4 columns row_labels = ['A','B','C','D','E'] # for the 5 rows col_headings = ['W','X','Y','Z'] # for the 4 columns df = pd.DataFrame(data=matrix_data, index = row_labels, columns = col_headings) df df ###Output _____no_output_____ ###Markdown Creating a new column: ###Code df['New'] = df['X'] + df['Y'] df type(df['New']) ###Output _____no_output_____ ###Markdown Deleting a column: ###Code df = df.drop('New',axis=1) #Axis = 1 for columns, Axis = 0 for rows/index df #Dropping multiple columns: df['NewXY'] = df['X'] + df['Y'] df['NewYZ'] = df['Y'] + df['Z'] df['NewXZ'] = df['X'] + df['Z'] df df = df.drop(["NewXY","NewYZ","NewXZ"],axis=1) df ###Output _____no_output_____ ###Markdown Deleting a row: ###Code df = df.drop('A') #By default the axis = 0 which is for the index df ###Output _____no_output_____ ###Markdown using inplace="True" that acts as df = df.drop(...) instead of actually writing df = : ###Code df.drop('B') df #The df is not affected #Therefore, we can use inplace that acts as df = df.drop(---) df.drop('B',axis=0,inplace = True) df ###Output _____no_output_____ ###Markdown Indexing and slicing: ###Code df ###Output _____no_output_____ ###Markdown For the columns: ###Code df['X'] type(df['X']) df.X type(df.X) df[['X']] type(df[['X']]) df[['X','Z']] type(df[['X','Z']]) ###Output _____no_output_____ ###Markdown For the rows: .loc method is for the labels(originally labels are indexes from 0,1,2..; since we have changed them to 'A','B',..'E', we use this method) ###Code df.loc['C'] # loc = location for the label(rows) df.iloc[2] #i = index, loc = index at that loc, since indexes start from 0, here C's index = 2 df.loc[['B','C']] df.iloc[['1','2']] ###Output _____no_output_____ ###Markdown For a particular element(s) by addressing both row and column: ###Code df.loc['C','Y'] #Type-I df.loc['B':'E':2,'X'::2] #Type-II df.loc[['B','D'],['X','Z']] ###Output _____no_output_____ ###Markdown Randomly getting df by re-executing the command as shown: ###Code #np.random.seed(101) matrix_data = rn(5,4) # 5 rows, 4 columns row_labels = ['A','B','C','D','E'] # for the 5 rows col_headings = ['W','X','Y','Z'] # for the 4 columns df = pd.DataFrame(data=matrix_data, index = row_labels, columns = col_headings) df #np.random.seed(101) matrix_data = rn(5,4) # 5 rows, 4 columns row_labels = ['A','B','C','D','E'] # for the 5 rows col_headings = ['W','X','Y','Z'] # for the 4 columns df = pd.DataFrame(data=matrix_data, index = row_labels, columns = col_headings) df np.random.seed(101) # To make a fixed state after generating the random series matrix_data = rn(5,4) # 5 rows, 4 columns row_labels = ['A','B','C','D','E'] # for the 5 rows col_headings = ['W','X','Y','Z'] # for the 4 columns df = pd.DataFrame(data=matrix_data, index = row_labels, columns = col_headings) df np.random.seed(101) # To make a fixed state after generating the random series matrix_data = rn(5,4) # 5 rows, 4 columns row_labels = ['A','B','C','D','E'] # for the 5 rows col_headings = ['W','X','Y','Z'] # for the 4 columns df = pd.DataFrame(data=matrix_data, index = row_labels, columns = col_headings) df ###Output _____no_output_____ ###Markdown Comparision operators: ###Code df>0 df.loc[['A','B','C']]>0 ###Output _____no_output_____ ###Markdown Q. Replacing the negative values: ###Code df booldf = df>0 bool2df = df<0 df[booldf] df[booldf] = "Pos" df[bool2df] = "Neg" df ###Output _____no_output_____ ###Markdown Creating matrix data: ###Code mat = np.matrix("22,66,140;42,70,148;30,62,125;35,68,160") mat row_label = ['A','B','C','D'] col_head = ['Age','Height','Weight'] df = pd.DataFrame(data = mat, index = row_label, columns = col_head) df ###Output _____no_output_____ ###Markdown To extract info from the matrix col wise: ###Code df['Height']>65 df1 = df['Height'][df['Height']>65] df1 ###Output _____no_output_____ ###Markdown To extract info from the matrix col wise plus other col data: ###Code df1 = df[df['Height']>65] df1 df ###Output _____no_output_____ ###Markdown Extracting info using Logical operators: ###Code booldf1 = df['Height']>65 booldf2 = df['Weight']>145 df[(booldf1)&(booldf2)] booldf1 ###Output _____no_output_____ ###Markdown Extract info from a matrix by operating on one column but excluding it in the result: ###Code df[booldf1] df[booldf1][['Age','Weight']] ###Output _____no_output_____ ###Markdown Reset the index(labels) back to 0,1,2...: ###Code df.reset_index() ###Output _____no_output_____ ###Markdown Now we have an extra column called index, the original indices have been replaced Reset the index(labels) back to 0,1,2.. and drop the extra column index_name generated : ###Code df.reset_index(drop = True) df #but here the index is retained which should not have been the case ###Output _____no_output_____ ###Markdown Creating a new column using .split() function (of numpy): ###Code df['Profession'] = "Teacher Engineer Doctor Nurse".split() df ###Output _____no_output_____ ###Markdown Replace the index by using set_index(..) method: ###Code df.set_index("Profession") ###Output _____no_output_____ ###Markdown Multi-indexing: ###Code outside = ['G1','G1','G1','G2','G2','G2'] inside = [1,2,3,1,2,3] higher_index = list(zip(outside,inside)) higher_index type(higher_index) higher_index = pd.MultiIndex.from_tuples(higher_index) higher_index type(higher_index) ###Output _____no_output_____ ###Markdown np.round(matrix_name/any_number,round_till_this_digit) method: ###Code #rn is the alias for the random given at the starting of this class (check Day 20) np.random.seed(101) df1 = pd.DataFrame(data = np.round(rn(6,3),2),index = higher_index,columns = ['A','B','C']) df1 #CHECK THE .round method: np.random.seed(101) df2 = pd.DataFrame(data = np.round(rn(6,3),5),index = higher_index,columns = ['A','B','C']) df2 pd.__version__ ###Output _____no_output_____ ###Markdown Indexing and slicing: ###Code df1.loc['G1'] df1.loc['G2'] df1.loc['G1'].loc[[1,3],['A','C']] df2.loc['G2'].loc[[2],['B']] df1.loc['G1'].loc[[1,3]][['A','C']] df1 ###Output _____no_output_____ ###Markdown Giving the names to the outside and inside indices: ###Code df1.index.names = ["outside","inner"] df1 ###Output _____no_output_____
Curso Pandas/extras/.ipynb_checkpoints/Criando Estrutura de Dados-checkpoint.ipynb
###Markdown Series Construindo a partir de uma lista ###Code data = [1,2,3,4,5] # Criação de Lista s = pd.Series(data) # Transforma em Serie s index = ['Linha' + str(i) for i in range(5)] # Constroi um rotulo para o indice index s = pd.Series(data, index) # Constroi a variável para leitura da lista s ###Output _____no_output_____ ###Markdown Constroi a partir de um dicionário ###Code data = {'Linha'+ str(i) : i + 1 for i in range (5)} data s = pd.Series(data) s ###Output _____no_output_____ ###Markdown Alterando os valores do Dicionário utilizando operadores matemáticos ###Code s1 = s + 2 s1 s2 = s + s1 s2 ###Output _____no_output_____
M02_A-Data_Preparation_Lecture.ipynb
###Markdown [View in Colaboratory](https://colab.research.google.com/github/schwaaweb/aimlds1_02/blob/master/M02_A-Data_Preparation_Lecture.ipynb) ###Code import numpy as np import pandas as pd # reading a .csv df = pd.read_csv('https://www.dropbox.com/s/uly87t2jwhbshtu/example1.csv?raw=1') print(df) ###Output a b c d message 0 1 2 3 4 hello 1 5 6 7 8 world 2 9 10 11 12 foo ###Markdown First step of cleaning: Skip rows with known bad dataOr, use `comment=""` to ignore commented lines ###Code e4 = pd.read_csv('https://www.dropbox.com/s/xcqdya9svj04kwc/example4.csv?raw=1', skiprows=[0, 2, 3]) print(e4) e4_1 = pd.read_csv('https://www.dropbox.com/s/xcqdya9svj04kwc/example4.csv?raw=1', comment="#") print(e4_1) ###Output a b c d message 0 1 2 3 4 hello 1 5 6 7 8 world 2 9 10 11 12 foo a b c d message 0 1 2 3 4 hello 1 5 6 7 8 world 2 9 10 11 12 foo ###Markdown Reading large filesWe don't want all the data, say, from a 10TB data file, lets just get the first 15 ###Code pd.options.display.max_rows = 6 e6 = pd.read_csv('https://www.dropbox.com/s/ymn5eqkckz4h204/example6.csv?raw=1') print(e6) # Creating data cleaning algorithms for a small subset will not be perfect e6_short = pd.read_csv('https://www.dropbox.com/s/ymn5eqkckz4h204/example6.csv?raw=1',nrows=10) print(e6_short) ###Output one two three four key 0 0.467976 -0.038649 -0.295344 -1.824726 L 1 -0.358893 1.404453 0.704965 -0.200638 B 2 -0.501840 0.659254 -0.421691 -0.057688 G ... ... ... ... ... .. 9997 0.523331 0.787112 0.486066 1.093156 K 9998 -0.362559 0.598894 -1.843201 0.887292 G 9999 -0.096376 -1.012999 -0.657431 -0.573315 0 [10000 rows x 5 columns] one two three four key 0 0.467976 -0.038649 -0.295344 -1.824726 L 1 -0.358893 1.404453 0.704965 -0.200638 B 2 -0.501840 0.659254 -0.421691 -0.057688 G .. ... ... ... ... .. 7 -0.913135 1.530624 -0.572657 0.477252 K 8 0.358480 -0.497572 -0.367016 0.507702 S 9 -1.740877 -1.160417 -1.637830 2.172201 G [10 rows x 5 columns] ###Markdown Reading chunks ###Code read_chunk = pd.read_csv('https://www.dropbox.com/s/ymn5eqkckz4h204/example6.csv?raw=1', chunksize=1000) total_dataset = pd.Series([]) for section in read_chunk: pd.options.display.max_rows = 10 print(section) total_dataset = total_dataset.add(section['key'].value_counts(), fill_value=0) print(total_dataset.shape) print(total_dataset.sum()) ###Output one two three four key 0 0.467976 -0.038649 -0.295344 -1.824726 L 1 -0.358893 1.404453 0.704965 -0.200638 B 2 -0.501840 0.659254 -0.421691 -0.057688 G 3 0.204886 1.074134 1.388361 -0.982404 R 4 0.354628 -0.133116 0.283763 -0.837063 Q .. ... ... ... ... .. 995 2.311896 -0.417070 -1.409599 -0.515821 M 996 -0.479893 -0.650419 0.745152 -0.646038 H 997 0.523331 0.787112 0.486066 1.093156 D 998 -0.362559 0.598894 -1.843201 0.887292 W 999 -0.096376 -1.012999 -0.657431 -0.573315 K [1000 rows x 5 columns] one two three four key 1000 0.467976 -0.038649 -0.295344 -1.824726 T 1001 -0.358893 1.404453 0.704965 -0.200638 J 1002 -0.501840 0.659254 -0.421691 -0.057688 R 1003 0.204886 1.074134 1.388361 -0.982404 S 1004 0.354628 -0.133116 0.283763 -0.837063 B ... ... ... ... ... .. 1995 2.311896 -0.417070 -1.409599 -0.515821 L 1996 -0.479893 -0.650419 0.745152 -0.646038 J 1997 0.523331 0.787112 0.486066 1.093156 V 1998 -0.362559 0.598894 -1.843201 0.887292 W 1999 -0.096376 -1.012999 -0.657431 -0.573315 D [1000 rows x 5 columns] one two three four key 2000 0.467976 -0.038649 -0.295344 -1.824726 1 2001 -0.358893 1.404453 0.704965 -0.200638 H 2002 -0.501840 0.659254 -0.421691 -0.057688 F 2003 0.204886 1.074134 1.388361 -0.982404 L 2004 0.354628 -0.133116 0.283763 -0.837063 E ... ... ... ... ... .. 2995 2.311896 -0.417070 -1.409599 -0.515821 H 2996 -0.479893 -0.650419 0.745152 -0.646038 U 2997 0.523331 0.787112 0.486066 1.093156 A 2998 -0.362559 0.598894 -1.843201 0.887292 Y 2999 -0.096376 -1.012999 -0.657431 -0.573315 F [1000 rows x 5 columns] one two three four key 3000 0.467976 -0.038649 -0.295344 -1.824726 H 3001 -0.358893 1.404453 0.704965 -0.200638 Y 3002 -0.501840 0.659254 -0.421691 -0.057688 0 3003 0.204886 1.074134 1.388361 -0.982404 Z 3004 0.354628 -0.133116 0.283763 -0.837063 U ... ... ... ... ... .. 3995 2.311896 -0.417070 -1.409599 -0.515821 W 3996 -0.479893 -0.650419 0.745152 -0.646038 E 3997 0.523331 0.787112 0.486066 1.093156 Q 3998 -0.362559 0.598894 -1.843201 0.887292 A 3999 -0.096376 -1.012999 -0.657431 -0.573315 M [1000 rows x 5 columns] one two three four key 4000 0.467976 -0.038649 -0.295344 -1.824726 H 4001 -0.358893 1.404453 0.704965 -0.200638 Z 4002 -0.501840 0.659254 -0.421691 -0.057688 2 4003 0.204886 1.074134 1.388361 -0.982404 B 4004 0.354628 -0.133116 0.283763 -0.837063 1 ... ... ... ... ... .. 4995 2.311896 -0.417070 -1.409599 -0.515821 X 4996 -0.479893 -0.650419 0.745152 -0.646038 M 4997 0.523331 0.787112 0.486066 1.093156 5 4998 -0.362559 0.598894 -1.843201 0.887292 T 4999 -0.096376 -1.012999 -0.657431 -0.573315 U [1000 rows x 5 columns] one two three four key 5000 0.467976 -0.038649 -0.295344 -1.824726 1 5001 -0.358893 1.404453 0.704965 -0.200638 Z 5002 -0.501840 0.659254 -0.421691 -0.057688 3 5003 0.204886 1.074134 1.388361 -0.982404 H 5004 0.354628 -0.133116 0.283763 -0.837063 B ... ... ... ... ... .. 5995 2.311896 -0.417070 -1.409599 -0.515821 1 5996 -0.479893 -0.650419 0.745152 -0.646038 Y 5997 0.523331 0.787112 0.486066 1.093156 F 5998 -0.362559 0.598894 -1.843201 0.887292 0 5999 -0.096376 -1.012999 -0.657431 -0.573315 3 [1000 rows x 5 columns] one two three four key 6000 0.467976 -0.038649 -0.295344 -1.824726 I 6001 -0.358893 1.404453 0.704965 -0.200638 X 6002 -0.501840 0.659254 -0.421691 -0.057688 A 6003 0.204886 1.074134 1.388361 -0.982404 C 6004 0.354628 -0.133116 0.283763 -0.837063 S ... ... ... ... ... .. 6995 2.311896 -0.417070 -1.409599 -0.515821 P 6996 -0.479893 -0.650419 0.745152 -0.646038 9 6997 0.523331 0.787112 0.486066 1.093156 L 6998 -0.362559 0.598894 -1.843201 0.887292 5 6999 -0.096376 -1.012999 -0.657431 -0.573315 O [1000 rows x 5 columns] one two three four key 7000 0.467976 -0.038649 -0.295344 -1.824726 1 7001 -0.358893 1.404453 0.704965 -0.200638 I 7002 -0.501840 0.659254 -0.421691 -0.057688 H 7003 0.204886 1.074134 1.388361 -0.982404 P 7004 0.354628 -0.133116 0.283763 -0.837063 D ... ... ... ... ... .. 7995 2.311896 -0.417070 -1.409599 -0.515821 A 7996 -0.479893 -0.650419 0.745152 -0.646038 6 7997 0.523331 0.787112 0.486066 1.093156 R 7998 -0.362559 0.598894 -1.843201 0.887292 R 7999 -0.096376 -1.012999 -0.657431 -0.573315 2 [1000 rows x 5 columns] one two three four key 8000 0.467976 -0.038649 -0.295344 -1.824726 7 8001 -0.358893 1.404453 0.704965 -0.200638 W 8002 -0.501840 0.659254 -0.421691 -0.057688 C 8003 0.204886 1.074134 1.388361 -0.982404 S 8004 0.354628 -0.133116 0.283763 -0.837063 H ... ... ... ... ... .. 8995 2.311896 -0.417070 -1.409599 -0.515821 W 8996 -0.479893 -0.650419 0.745152 -0.646038 N 8997 0.523331 0.787112 0.486066 1.093156 Q 8998 -0.362559 0.598894 -1.843201 0.887292 R 8999 -0.096376 -1.012999 -0.657431 -0.573315 M [1000 rows x 5 columns] one two three four key 9000 0.467976 -0.038649 -0.295344 -1.824726 B 9001 -0.358893 1.404453 0.704965 -0.200638 M 9002 -0.501840 0.659254 -0.421691 -0.057688 N 9003 0.204886 1.074134 1.388361 -0.982404 N 9004 0.354628 -0.133116 0.283763 -0.837063 Y ... ... ... ... ... .. 9995 2.311896 -0.417070 -1.409599 -0.515821 L 9996 -0.479893 -0.650419 0.745152 -0.646038 E 9997 0.523331 0.787112 0.486066 1.093156 K 9998 -0.362559 0.598894 -1.843201 0.887292 G 9999 -0.096376 -1.012999 -0.657431 -0.573315 0 [1000 rows x 5 columns] (36,) 10000.0 ###Markdown You got the data, what to do with it? ###Code #total_dataset.index.values = np.vectorize(ord)(total_dataset.index.values) sorted_array = total_dataset.sort_values(ascending=False) print(sorted_array) import matplotlib.pyplot as plt #print(sorted_array.iloc[0:]) print(total_dataset.index.values) plt.plot(total_dataset.index.values,total_dataset.values) sorted_array.plot.bar() ###Output E 368.0 X 364.0 L 346.0 O 343.0 Q 340.0 M 338.0 J 337.0 F 335.0 K 334.0 H 330.0 V 328.0 I 327.0 U 326.0 P 324.0 D 320.0 A 320.0 R 318.0 Y 314.0 G 308.0 S 308.0 N 306.0 W 305.0 T 304.0 B 302.0 Z 288.0 C 286.0 4 171.0 6 166.0 7 164.0 8 162.0 3 162.0 5 157.0 2 152.0 0 151.0 9 150.0 1 146.0 dtype: float64 ['0' '1' '2' '3' '4' '5' '6' '7' '8' '9' 'A' 'B' 'C' 'D' 'E' 'F' 'G' 'H' 'I' 'J' 'K' 'L' 'M' 'N' 'O' 'P' 'Q' 'R' 'S' 'T' 'U' 'V' 'W' 'X' 'Y' 'Z'] ###Markdown Accessing specific rows ###Code result = pd.read_csv('https://www.dropbox.com/s/9cljswede6r25ho/example5.csv?raw=1', index_col='something') print(result) print(result[:10]) print(result[3:10]) print(result.loc[['one','two'],['a','b']]) ###Output a b c d message something one 1 2 3.0 4 NaN two 5 6 NaN 8 world three 9 10 11.0 12 foo a b c d message something one 1 2 3.0 4 NaN two 5 6 NaN 8 world three 9 10 11.0 12 foo Empty DataFrame Columns: [a, b, c, d, message] Index: [] a b something one 1 2 two 5 6 ###Markdown Treat and De-Duplicate ###Code result = pd.read_csv('https://www.dropbox.com/s/9cljswede6r25ho/example5.csv?raw=1', index_col='something') print(result) print(result.isnull()) result.loc['one','message'] = 'blank' print(result) filled = result.fillna(0) print(filled) filled = result.fillna({'c': 1}) filled = filled.fillna({'message': 'blank'}) print(filled) print(filled.isnull()) result = pd.read_csv('https://www.dropbox.com/s/9cljswede6r25ho/example5.csv?raw=1', index_col='something') print(result) filled = result.fillna(method = 'ffill') print(filled) filled = filled.fillna({'message': 'blank'}) print(filled) result = pd.read_csv('https://www.dropbox.com/s/9cljswede6r25ho/example5.csv?raw=1', index_col='something') print(result.isnull().sum()) dropped = result.dropna() print(dropped) print(result.dropna(axis=1)) print(result.dropna(how="all")) ###Output a b c d message something three 9 10 11.0 12 foo a b d something one 1 2 4 two 5 6 8 three 9 10 12 a b c d message something one 1 2 3.0 4 NaN two 5 6 NaN 8 world three 9 10 11.0 12 foo ###Markdown Removing Duplicates ###Code DataFrame_obj = pd.DataFrame({'column 1': [4, 4, 5, 5, 6, 6, 6], 'column 2': ['x', 'x', 'y', 'y', 'z', 'z', 'z'], 'column 3': ['X', 'X', 'Y', 'Y', 'Z', 'Z', 'Z']}) DataFrame_obj print(DataFrame_obj.duplicated()) print(DataFrame_obj.drop_duplicates()) ###Output _____no_output_____
Python Code Challenges/Sum_of_digits _digital_root.ipynb
###Markdown Resources Python[Python 3 Documentation](https://docs.python.org/3/library/) General[Stackoverflow](https://stackoverflow.com/) YouTube vids[Kalle Hallden](https://www.youtube.com/channel/UCWr0mx597DnSGLFk1WfvSkQ)[PyCon 2019](https://www.youtube.com/channel/UCxs2IIVXaEHHA4BtTiWZ2mQ)[Tech With Tim](https://www.youtube.com/channel/UC4JX40jDee_tINbkjycV4Sg)[Python Programmer](https://www.youtube.com/user/consumerchampion)[sentdex](https://www.youtube.com/user/sentdex) Markdown links[Markdown Cheatsheet](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet)[Markdown Guide](https://www.markdownguide.org/)[Markdown Table Generator](https://www.tablesgenerator.com/markdown_tables) Code```df.reset_index(self, level=None, drop=False, inplace=False, col_level=0, col_fill='')``````df = pd.DataFrame(np.random.randint(500,4000,size=(200, 1)), columns=list('A'))``````df['randNumCol'] = np.random.randint(1, 6, df.shape[0])`````` Declare a list that is to be converted into a column tradcounthvac = xyzhvac.x.count()tradehvac = tradcounthvac * ['hvac'] tradcountelec = xyzelec.x.count()tradeelec = tradcountelec * ['elec'] Using 'Trade' as the column name and equating it to the list xyzhvac['Trade'] = tradehvacxyzelec['Trade'] = tradeelec``` Packages```! pip install pandas-profiling``````! pip install plotly``````! pip install cufflinks``````! pip install plotly==4.2.1``````!pip install dovpanda``````import numpy as np``````import pandas as pd``````import pandas_profiling``````import plotly.graph_objects as go``````import dovpanda``` pandas[What can you do with the new ‘Pandas’?](https://towardsdatascience.com/what-can-you-do-with-the-new-pandas-2d24cf8d8b4b)[Reordering Pandas DataFrame Columns: Thumbs Down On Standard Solutions](https://towardsdatascience.com/reordering-pandas-dataframe-columns-thumbs-down-on-standard-solutions-1ff0bc2941d5)[pandas Documentation](https://pandas.pydata.org/pandas-docs/stable/)[7 practical pandas tips when you start working with the library](https://towardsdatascience.com/7-practical-pandas-tips-when-you-start-working-with-the-library-e4a9205eb443)[dataframe transpose](https://www.geeksforgeeks.org/python-pandas-dataframe-transpose/)[Combining DataFrames with Pandas](https://datacarpentry.org/python-ecology-lesson/05-merging-data/)[dovpanda](https://github.com/dovpanda-dev/dovpanda)[Selecting Subsets of Data in Pandas: Part 1](https://medium.com/dunder-data/selecting-subsets-of-data-in-pandas-6fcd0170be9c)[10 simple Python tips to speed up your data analysis](https://thenextweb.com/syndication/2020/10/12/10-simple-python-tips-to-speed-up-your-data-analysis/)[15 Tips and Tricks to use in Jupyter Notebooks](https://towardsdatascience.com/15-tips-and-tricks-to-use-jupyter-notebook-more-efficiently-ef05ede4e4b9)```result = df.transpose() ```5 functions to examine your data: ```df.head()', df.describe(), df.info(), df.shape, df.sum(), df['Trade'].value_counts() ```Reports: ```pandas_profiling.ProfileReport(df)```Import: ```import pandas_profiling```Save a dataframe to a csv```df.to_csv```Create a Pandas Dataframe```df = pd.DataFrame(data) ```Read a csv file```pd.read_csv('')```Read a excel file```pd.read_excel('')```All rows that have a sepal length greater than 6 are dangerous ```df['is_dangerous'] = np.where(df['sepal length (cm)']>6, 'yes', 'no')```Max columns option ```pd.set_option('display.max_columns', 500)```Max row option ```pd.set_option('display.max_rows', 500)```to see columns ```df.columns```replace strings ```df.columns = df.columns.str.replace(' \(cm\)', '').str.replace(' ', '_')``` plotly[plotly Graphing Libraries](https://plot.ly/python/)[Different Colors for Bars in Barchart by their Value](https://community.plot.ly/t/different-colors-for-bars-in-barchart-by-their-value/6527) Scikit-Learn[A beginner’s guide to Linear Regression in Python with Scikit-Learn](https://towardsdatascience.com/a-beginners-guide-to-linear-regression-in-python-with-scikit-learn-83a8f7ae2b4f) Notes ###Code # Codewars # https://www.codewars.com/kata/541c8630095125aba6000c00/solutions/python # Sum of Digits / Digital Root # https://stackoverflow.com/questions/10411085/converting-integer-to-binary-in-python def digital_root(n): while n > 9: n = sum([int(i) for i in str(n)]) return n ###Output _____no_output_____
car_damage_classification/car_damage_preprocess.ipynb
###Markdown Car damage dataset preprocessorThis notebook will prepare the car damage dataset for the Peltarion platform.Note: This notebook requires installation of Sidekick. To install the package within the notebook, run the following code:`import sys!{sys.executable} -m pip install git+https://github.com/Peltarion/sidekickegg=sidekick`For more information about Sidekick, see:https://github.com/Peltarion/sidekickThe raw dataset is available at: https://storage.cloud.google.com/bucket-8732/car_damage/raw.zip--- ###Code import functools from glob import glob import resource import os import pandas as pd from PIL import Image import sidekick from sklearn.model_selection import train_test_split ###Output _____no_output_____ ###Markdown Set paths ###Code # Path to the raw dataset (unzipped) input_path = './raw' # Path to the zip output output_path = './preprocessed.zip' ###Output _____no_output_____ ###Markdown Get list of paths to all files ###Code images_rel_path = glob(input_path + '/*/*.jpg') + glob(input_path + '/*/*.png') print("Images found: ", len(images_rel_path)) ###Output Images found: 1538 ###Markdown Create DataframeThe class column values are derived from the names of the subfolders in the `input_path`.The image column contains the relative path to the images in the subfolders. Create image and class columns ###Code df = pd.DataFrame({'image': images_rel_path}) df['class'] = df['image'].apply(lambda path: os.path.basename(os.path.dirname(path))) df.head() ###Output _____no_output_____ ###Markdown Filter imagesFilter out non-RGB images Create temporary ``image_mode`` column ###Code def get_mode(path): im = Image.open(path) im.close() return im.mode df['image_mode'] = df['image'].apply(lambda path: get_mode(path)) df['image_mode'].value_counts() df = df[df.image_mode =='RGB'] df['image_mode'].value_counts() ###Output _____no_output_____ ###Markdown Remove the temporary column ###Code df = df.drop(['image_mode'], axis=1) df['class'].value_counts() ###Output _____no_output_____ ###Markdown Create subsets for training and validation ###Code def create_subsets(df, col='class', validation_size=0.20): train_data, validate_data = train_test_split(df, test_size=validation_size, random_state=42, stratify=df[[col]]) train_data.insert(loc=2, column='subset', value='T') validate_data.insert(loc=2, column='subset', value='V') return train_data.append(validate_data, ignore_index=True) df = create_subsets(df) df['subset'].value_counts() ###Output _____no_output_____ ###Markdown Upsampling Upsampling (duplicating samples) can be used to prevent bias in an ubalanced dataset ###Code max_size = df[df['subset']=='T']['class'].value_counts().max() lst = [df] for class_index, group in df[df['subset']=='T'].groupby('class'): lst.append(group.sample(max_size-len(group), replace=True)) df = pd.concat(lst) #df['class'].value_counts() print('\nTraining:') print(df[df['subset']=='T']['class'].value_counts()) print('\nValidation:') print(df[df['subset']=='V']['class'].value_counts()) ###Output Training: glass_shatter 439 door_scratch 439 bumper_dent 439 door_dent 439 tail_lamp 439 unknown 439 head_lamp 439 bumper_scratch 439 Name: class, dtype: int64 Validation: unknown 110 door_dent 39 door_scratch 31 tail_lamp 27 glass_shatter 27 head_lamp 27 bumper_dent 26 bumper_scratch 16 Name: class, dtype: int64 ###Markdown Create dataset bundle ###Code df.head() image_processor = functools.partial(sidekick.process_image, mode='crop_and_resize', size=(224, 224), file_format='jpeg') sidekick.create_dataset( output_path, df, path_columns=['image'], preprocess={ 'image': image_processor } ) # The duplicated images in the upsampled class will cause warnings ###Output /usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/zipfile.py:1470: UserWarning: Duplicate name: 'image/1068.jpeg' return self._open_to_write(zinfo, force_zip64=force_zip64) /usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/zipfile.py:1470: UserWarning: Duplicate name: 'image/586.jpeg' return self._open_to_write(zinfo, force_zip64=force_zip64) /usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/zipfile.py:1470: UserWarning: Duplicate name: 'image/531.jpeg' return self._open_to_write(zinfo, force_zip64=force_zip64) /usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/zipfile.py:1470: UserWarning: Duplicate name: 'image/413.jpeg' return self._open_to_write(zinfo, force_zip64=force_zip64) /usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/zipfile.py:1470: UserWarning: Duplicate name: 'image/1058.jpeg' return self._open_to_write(zinfo, force_zip64=force_zip64) /usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/zipfile.py:1470: UserWarning: Duplicate name: 'image/389.jpeg' return self._open_to_write(zinfo, force_zip64=force_zip64) /usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/zipfile.py:1470: UserWarning: Duplicate name: 'image/629.jpeg' return self._open_to_write(zinfo, force_zip64=force_zip64) /usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/zipfile.py:1470: UserWarning: Duplicate name: 'image/41.jpeg' return self._open_to_write(zinfo, force_zip64=force_zip64) /usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/zipfile.py:1470: UserWarning: Duplicate name: 'image/578.jpeg' return self._open_to_write(zinfo, force_zip64=force_zip64) /usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/zipfile.py:1470: UserWarning: Duplicate name: 'image/814.jpeg' return self._open_to_write(zinfo, force_zip64=force_zip64) /usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/zipfile.py:1470: UserWarning: Duplicate name: 'image/802.jpeg' return self._open_to_write(zinfo, force_zip64=force_zip64) /usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/zipfile.py:1470: UserWarning: Duplicate name: 'image/159.jpeg' return self._open_to_write(zinfo, force_zip64=force_zip64) /usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/zipfile.py:1470: UserWarning: Duplicate name: 'image/991.jpeg' return self._open_to_write(zinfo, force_zip64=force_zip64) /usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/zipfile.py:1470: UserWarning: Duplicate name: 'image/1135.jpeg' return self._open_to_write(zinfo, force_zip64=force_zip64) /usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/zipfile.py:1470: UserWarning: Duplicate name: 'image/701.jpeg' return self._open_to_write(zinfo, force_zip64=force_zip64) /usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/zipfile.py:1470: UserWarning: Duplicate name: 'image/1092.jpeg' return self._open_to_write(zinfo, force_zip64=force_zip64) /usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/zipfile.py:1470: UserWarning: Duplicate name: 'image/11.jpeg' return self._open_to_write(zinfo, force_zip64=force_zip64) /usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/zipfile.py:1470: UserWarning: Duplicate name: 'image/888.jpeg' return self._open_to_write(zinfo, force_zip64=force_zip64) /usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/zipfile.py:1470: UserWarning: Duplicate name: 'image/1055.jpeg' return self._open_to_write(zinfo, force_zip64=force_zip64) /usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/zipfile.py:1470: UserWarning: Duplicate name: 'image/234.jpeg' return self._open_to_write(zinfo, force_zip64=force_zip64) /usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/zipfile.py:1470: UserWarning: Duplicate name: 'image/346.jpeg' return self._open_to_write(zinfo, force_zip64=force_zip64) /usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/zipfile.py:1470: UserWarning: Duplicate name: 'image/324.jpeg' return self._open_to_write(zinfo, force_zip64=force_zip64) /usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/zipfile.py:1470: UserWarning: Duplicate name: 'image/222.jpeg' return self._open_to_write(zinfo, force_zip64=force_zip64) /usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/zipfile.py:1470: UserWarning: Duplicate name: 'image/667.jpeg' return self._open_to_write(zinfo, force_zip64=force_zip64) /usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/zipfile.py:1470: UserWarning: Duplicate name: 'image/561.jpeg' return self._open_to_write(zinfo, force_zip64=force_zip64) /usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/zipfile.py:1470: UserWarning: Duplicate name: 'image/17.jpeg' return self._open_to_write(zinfo, force_zip64=force_zip64) /usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/zipfile.py:1470: UserWarning: Duplicate name: 'image/962.jpeg' return self._open_to_write(zinfo, force_zip64=force_zip64) /usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/zipfile.py:1470: UserWarning: Duplicate name: 'image/874.jpeg' return self._open_to_write(zinfo, force_zip64=force_zip64) /usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/zipfile.py:1470: UserWarning: Duplicate name: 'image/103.jpeg' return self._open_to_write(zinfo, force_zip64=force_zip64) /usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/zipfile.py:1470: UserWarning: Duplicate name: 'image/977.jpeg' return self._open_to_write(zinfo, force_zip64=force_zip64) /usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/zipfile.py:1470: UserWarning: Duplicate name: 'image/369.jpeg' return self._open_to_write(zinfo, force_zip64=force_zip64) /usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/zipfile.py:1470: UserWarning: Duplicate name: 'image/966.jpeg' return self._open_to_write(zinfo, force_zip64=force_zip64) /usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/zipfile.py:1470: UserWarning: Duplicate name: 'image/666.jpeg' return self._open_to_write(zinfo, force_zip64=force_zip64) /usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/zipfile.py:1470: UserWarning: Duplicate name: 'image/598.jpeg' return self._open_to_write(zinfo, force_zip64=force_zip64) /usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/zipfile.py:1470: UserWarning: Duplicate name: 'image/815.jpeg' return self._open_to_write(zinfo, force_zip64=force_zip64) /usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/zipfile.py:1470: UserWarning: Duplicate name: 'image/133.jpeg' return self._open_to_write(zinfo, force_zip64=force_zip64) /usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/zipfile.py:1470: UserWarning: Duplicate name: 'image/916.jpeg' return self._open_to_write(zinfo, force_zip64=force_zip64) /usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/zipfile.py:1470: UserWarning: Duplicate name: 'image/46.jpeg' return self._open_to_write(zinfo, force_zip64=force_zip64) /usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/zipfile.py:1470: UserWarning: Duplicate name: 'image/86.jpeg' return self._open_to_write(zinfo, force_zip64=force_zip64) /usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/zipfile.py:1470: UserWarning: Duplicate name: 'image/915.jpeg' return self._open_to_write(zinfo, force_zip64=force_zip64) /usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/zipfile.py:1470: UserWarning: Duplicate name: 'image/1002.jpeg' return self._open_to_write(zinfo, force_zip64=force_zip64) /usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/zipfile.py:1470: UserWarning: Duplicate name: 'image/703.jpeg' return self._open_to_write(zinfo, force_zip64=force_zip64)
JupyterNotebook/coded_correspondence.ipynb
###Markdown Casual Coded Correspondence: The ProjectIn this project, you will be working to code and decode various messages between you and your fictional cryptography enthusiast pen pal Vishal. You and Vishal have been exchanging letters for quite some time now and have started to provide a puzzle in each one of your letters. Here is his most recent letter: Hey there! How have you been? I've been great! I just learned about this really cool type of cipher called a Caesar Cipher. Here's how it works: You take your message, something like "hello" and then you shift all of the letters by a certain offset. For example, if I chose an offset of 3 and a message of "hello", I would code my message by shifting each letter 3 places to the left (with respect to the alphabet). So "h" becomes "e", "e" becomes, "b", "l" becomes "i", and "o" becomes "l". Then I have my coded message,"ebiil"! Now I can send you my message and the offset and you can decode it. The best thing is that Julius Caesar himself used this cipher, that's why it's called the Caesar Cipher! Isn't that so cool! Okay, now I'm going to send you a longer coded message that you have to decode yourself! xuo jxuhu! jxyi yi qd unqcfbu ev q squiqh syfxuh. muhu oek qrbu je tusetu yj? y xefu ie! iudt cu q cuiiqwu rqsa myjx jxu iqcu evviuj! This message has an offset of 10. Can you decode it? Step 1: Decode Vishal's MessageIn the cell below, use your Python skills to decode Vishal's message and print the result. Hint: you can account for shifts that go past the end of the alphabet using the modulus operator, but I'll let you figure out how! ###Code alphabet = "abcdefghijklmnopqrstuvwxyz" punctuation = ".,?'! " message = "xuo jxuhu! jxyi yi qd unqcfbu ev q squiqh syfxuh. muhu oek qrbu je tusetu yj? y xefu ie! iudt cu q cuiiqwu rqsa myjx jxu iqcu evviuj!" translated_message = "" for letter in message: if not letter in punctuation: letter_value = alphabet.find(letter) translated_message += alphabet[(letter_value + 10) % 26] else: translated_message += letter print(translated_message) ###Output hey there! this is an example of a caesar cipher. were you able to decode it? i hope so! send me a message back with the same offset! ###Markdown Step 2: Send Vishal a Coded MessageGreat job! Now send Vishal back a message using the same offset. Your message can be anything you want! Remember, coding happens in opposite direction of decoding. ###Code message_for_v = "hey vishal! This is a super cool cipher, thanks for showing me! What else you got?" translated_message = "" for letter in message_for_v: if not letter in punctuation: letter_value = alphabet.find(letter) translated_message += alphabet[(letter_value - 10) % 26] else: translated_message += letter print(translated_message) ###Output xuo lyixqb! pxyi yi q ikfuh seeb syfxuh, jxqdai veh ixemydw cu! pxqj ubiu oek wej? ###Markdown Step 3: Make functions for decoding and coding Vishal sent over another reply, this time with two coded messages! You're getting the hang of this! Okay here are two more messages, the first one is coded just like before with an offset of ten, and it contains the hint for decoding the second message! First message: jxu evviuj veh jxu iusedt cuiiqwu yi vekhjuud. Second message: bqdradyuzs ygxfubxq omqemd oubtqde fa oapq kagd yqeemsqe ue qhqz yadq eqogdq! Decode both of these messages. If you haven't already, define two functions `decoder(message, offset)` and `coder(message, offset)` that can be used to quickly decode and code messages given any offset. ###Code # both of these functions need the strings `alphabet` and `punctuation` defined before being run def decoder(message, offset): translated_message = "" for letter in message: if not letter in punctuation: letter_value = alphabet.find(letter) translated_message += alphabet[(letter_value + offset) % 26] else: translated_message += letter return translated_message def coder(message, offset): translated_message = "" for letter in message: if not letter in punctuation: letter_value = alphabet.find(letter) translated_message += alphabet[(letter_value - offset) % 26] else: translated_message += letter return translated_message message_one = "jxu evviuj veh jxu iusedt cuiiqwu yi vekhjuud." # Now we'll print the output of `decoder` for the first message with an offset of 10 print(decoder(message_one, 10)) # Now we know what offset to use for the second message, so we use that to solve. message_two = "bqdradyuzs ygxfubxq omqemd oubtqde fa oapq kagd yqeemsqe ue qhqz yadq eqogdq!" print(decoder(message_two, 14)) ###Output performing multiple caesar ciphers to code your messages is even more secure! ###Markdown Step 4: Solving a Caesar Cipher without knowing the shift valueAwesome work! While you were working to decode his last two messages, Vishal sent over another letter! He's really been bitten by the crytpo-bug. Read it and see what interesting task he has lined up for you this time. Hello again friend! I knew you would love the Caesar Cipher, it's a cool simple way to encrypt messages. Did you know that back in Caesar's time, it was considered a very secure way of communication and it took a lot of effort to crack if you were unaware of the value of the shift? That's all changed with computers! Now we can brute force these kinds of ciphers very quickly, as I'm sure you can imagine. To test your cryptography skills, this next coded message is going to be harder than the last couple to crack. It's still going to be coded with a Caesar Cipher but this time I'm not going to tell you the value of the shift. You'll have to brute force it yourself. Here's the coded message: vhfinmxkl atox kxgwxkxw tee hy maxlx hew vbiaxkl tl hulhexmx. px'ee atox mh kxteer lmxi ni hnk ztfx by px ptgm mh dxxi hnk fxlltzxl ltyx. Good luck! Decode Vishal's most recent message and see what it says! ###Code coded_message = "vhfinmxkl atox kxgwxkxw tee hy maxlx hew vbiaxkl tl hulhexmx. px'ee atox mh kxteer lmxi ni hnk ztfx by px ptgm mh dxxi hnk fxlltzxl ltyx." # The easiest way to break this code is to simply brute force though all of the possible shifts. # We'll only need to try 25 different shifts, so it's not computationally expensive. Then we can # look through all of the outputs and look for the one that in english, and we've decoded our message! for i in range(1,26): print("offset: " + str(i)) print("\t " + decoder(coded_message, i) + "\n") ###Output offset: 1 wigjonylm bupy lyhxylyx uff iz nbymy ifx wcjbylm um ivmifyny. qy'ff bupy ni lyuffs mnyj oj iol augy cz qy quhn ni eyyj iol gymmuaym muzy. offset: 2 xjhkpozmn cvqz mziyzmzy vgg ja ocznz jgy xdkczmn vn jwnjgzoz. rz'gg cvqz oj mzvggt nozk pk jpm bvhz da rz rvio oj fzzk jpm hznnvbzn nvaz. offset: 3 ykilqpano dwra najzanaz whh kb pdaoa khz yeldano wo kxokhapa. sa'hh dwra pk nawhhu opal ql kqn cwia eb sa swjp pk gaal kqn iaoowcao owba. offset: 4 zljmrqbop exsb obkaboba xii lc qebpb lia zfmebop xp lyplibqb. tb'ii exsb ql obxiiv pqbm rm lro dxjb fc tb txkq ql hbbm lro jbppxdbp pxcb. offset: 5 amknsrcpq fytc pclbcpcb yjj md rfcqc mjb agnfcpq yq mzqmjcrc. uc'jj fytc rm pcyjjw qrcn sn msp eykc gd uc uylr rm iccn msp kcqqyecq qydc. offset: 6 bnlotsdqr gzud qdmcdqdc zkk ne sgdrd nkc bhogdqr zr narnkdsd. vd'kk gzud sn qdzkkx rsdo to ntq fzld he vd vzms sn jddo ntq ldrrzfdr rzed. offset: 7 computers have rendered all of these old ciphers as obsolete. we'll have to really step up our game if we want to keep our messages safe. offset: 8 dpnqvufst ibwf sfoefsfe bmm pg uiftf pme djqifst bt pctpmfuf. xf'mm ibwf up sfbmmz tufq vq pvs hbnf jg xf xbou up lffq pvs nfttbhft tbgf. offset: 9 eqorwvgtu jcxg tgpfgtgf cnn qh vjgug qnf ekrjgtu cu qduqngvg. yg'nn jcxg vq tgcnna uvgr wr qwt icog kh yg ycpv vq mggr qwt oguucigu uchg. offset: 10 frpsxwhuv kdyh uhqghuhg doo ri wkhvh rog flskhuv dv revrohwh. zh'oo kdyh wr uhdoob vwhs xs rxu jdph li zh zdqw wr nhhs rxu phvvdjhv vdih. offset: 11 gsqtyxivw lezi virhivih epp sj xliwi sph gmtlivw ew sfwspixi. ai'pp lezi xs vieppc wxit yt syv keqi mj ai aerx xs oiit syv qiwwekiw weji. offset: 12 htruzyjwx mfaj wjsijwji fqq tk ymjxj tqi hnumjwx fx tgxtqjyj. bj'qq mfaj yt wjfqqd xyju zu tzw lfrj nk bj bfsy yt pjju tzw rjxxfljx xfkj. offset: 13 iusvazkxy ngbk xktjkxkj grr ul znkyk urj iovnkxy gy uhyurkzk. ck'rr ngbk zu xkgrre yzkv av uax mgsk ol ck cgtz zu qkkv uax skyygmky yglk. offset: 14 jvtwbalyz ohcl yluklylk hss vm aolzl vsk jpwolyz hz vizvslal. dl'ss ohcl av ylhssf zalw bw vby nhtl pm dl dhua av rllw vby tlzzhnlz zhml. offset: 15 kwuxcbmza pidm zmvlmzml itt wn bpmam wtl kqxpmza ia wjawtmbm. em'tt pidm bw zmittg abmx cx wcz oium qn em eivb bw smmx wcz umaaioma ainm. offset: 16 lxvydcnab qjen anwmnanm juu xo cqnbn xum lryqnab jb xkbxuncn. fn'uu qjen cx anjuuh bcny dy xda pjvn ro fn fjwc cx tnny xda vnbbjpnb bjon. offset: 17 mywzedobc rkfo boxnobon kvv yp droco yvn mszrobc kc ylcyvodo. go'vv rkfo dy bokvvi cdoz ez yeb qkwo sp go gkxd dy uooz yeb wocckqoc ckpo. offset: 18 nzxafepcd slgp cpyopcpo lww zq espdp zwo ntaspcd ld zmdzwpep. hp'ww slgp ez cplwwj depa fa zfc rlxp tq hp hlye ez vppa zfc xpddlrpd dlqp. offset: 19 oaybgfqde tmhq dqzpqdqp mxx ar ftqeq axp oubtqde me aneaxqfq. iq'xx tmhq fa dqmxxk efqb gb agd smyq ur iq imzf fa wqqb agd yqeemsqe emrq. offset: 20 pbzchgref unir eraqrerq nyy bs gurfr byq pvcuref nf bofbyrgr. jr'yy unir gb ernyyl fgrc hc bhe tnzr vs jr jnag gb xrrc bhe zrffntrf fnsr. offset: 21 qcadihsfg vojs fsbrsfsr ozz ct hvsgs czr qwdvsfg og cpgczshs. ks'zz vojs hc fsozzm ghsd id cif uoas wt ks kobh hc yssd cif asggousg gots. offset: 22 rdbejitgh wpkt gtcstgts paa du iwtht das rxewtgh ph dqhdatit. lt'aa wpkt id gtpaan hite je djg vpbt xu lt lpci id ztte djg bthhpvth hput. offset: 23 secfkjuhi xqlu hudtuhut qbb ev jxuiu ebt syfxuhi qi eriebuju. mu'bb xqlu je huqbbo ijuf kf ekh wqcu yv mu mqdj je auuf ekh cuiiqwui iqvu. offset: 24 tfdglkvij yrmv iveuvivu rcc fw kyvjv fcu tzgyvij rj fsjfcvkv. nv'cc yrmv kf ivrccp jkvg lg fli xrdv zw nv nrek kf bvvg fli dvjjrxvj jrwv. offset: 25 ugehmlwjk zsnw jwfvwjwv sdd gx lzwkw gdv uahzwjk sk gtkgdwlw. ow'dd zsnw lg jwsddq klwh mh gmj ysew ax ow osfl lg cwwh gmj ewkksywk ksxw. ###Markdown Step 5: The Vigenère CipherGreat work! While you were working on the brute force cracking of the cipher, Vishal sent over another letter. That guy is a letter machine! Salutations! As you can see, technology has made brute forcing simple ciphers like the Caesar Cipher extremely easy, and us crypto-enthusiasts have had to get more creative and use more complicated ciphers. This next cipher I'm going to teach you is the Vigenère Cipher, invented by an Italian cryptologist named Giovan Battista Bellaso (cool name eh?) in the 16th century, but named after another cryptologist from the 16th century, Blaise de Vigenère. The Vigenère Cipher is a polyalphabetic substitution cipher, as opposed to the Caesar Cipher which was a monoalphabetic substitution cipher. What this means is that opposed to having a single shift that is applied to every letter, the Vigenère Cipher has a different shift for each individual letter. The value of the shift for each letter is determined by a given keyword. Consider the message barry is the spy If we want to code this message, first we choose a keyword. For this example, we'll use the keyword dog Now we use the repeat the keyword over and over to generate a _keyword phrase_ that is the same length as the message we want to code. So if we want to code the message "barry is the spy" our _keyword phrase_ is "dogdo gd ogd ogd". Now we are ready to start coding our message. We shift the each letter of our message by the place value of the corresponding letter in the keyword phrase, assuming that "a" has a place value of 0, "b" has a place value of 1, and so forth. Remember, we zero-index because this is Python we're talking about! message: b a r r y i s t h e s p y keyword phrase: d o g d o g d o g d o g d resulting place value: 4 14 15 12 16 24 11 21 25 22 22 17 5 So we shift "b", which has an index of 1, by the index of "d", which is 3. This gives us an place value of 4, which is "e". Then continue the trend: we shift "a" by the place value of "o", 14, and get "o" again, we shift "r" by the place value of "g", 15, and get "x", shift the next "r" by 12 places and "u", and so forth. Once we complete all the shifts we end up with our coded message: eoxum ov hnh gvb As you can imagine, this is a lot harder to crack without knowing the keyword! So now comes the hard part. I'll give you a message and the keyword, and you'll see if you can figure out how to crack it! Ready? Okay here's my message: dfc aruw fsti gr vjtwhr wznj? vmph otis! cbx swv jipreneo uhllj kpi rahjib eg fjdkwkedhmp! and the keyword to decode my message is friends Because that's what we are! Good luck friend! And there it is. Vishal has given you quite the assignment this time! Try to decode his message. It may be helpful to create a function that takes two parameters, the coded message and the keyword and then work towards a solution from there.**NOTE:** Watch out for spaces and punctuation! When there's a space or punctuation mark in the original message, there should be a space/punctuation mark in the corresponding repeated-keyword string as well! ###Code def vigenere_decoder(coded_message, keyword): letter_pointer = 0 keyword_final = '' for i in range(0,len(coded_message)): if coded_message[i] in punctuation: keyword_final += coded_message[i] else: keyword_final += keyword[letter_pointer] letter_pointer = (letter_pointer+1)%len(keyword) translated_message = '' for i in range(0,len(coded_message)): if not coded_message[i] in punctuation: ln = alphabet.find(coded_message[i]) - alphabet.find(keyword_final[i]) translated_message += alphabet[ln % 26] else: translated_message += coded_message[i] return translated_message message = "dfc aruw fsti gr vjtwhr wznj? vmph otis! cbx swv jipreneo uhllj kpi rahjib eg fjdkwkedhmp!" keyword = "friends" print(vigenere_decoder(message, keyword)) ###Output you were able to decode this? nice work! you are becoming quite the expert at crytography! ###Markdown Step 6: Send a message with the Vigenère CipherGreat work decoding the message. For your final task, write a function that can encode a message using a given keyword and write out a message to send to Vishal!*As a bonus, try calling your decoder function on the result of your encryption function. You should get the original message back!* ###Code def vigenere_coder(message, keyword): letter_pointer = 0 keyword_final = '' for i in range(0,len(message)): if message[i] in punctuation: keyword_final += message[i] else: keyword_final += keyword[letter_pointer] letter_pointer = (letter_pointer+1)%len(keyword) translated_message = '' for i in range(0,len(message)): if message[i] not in punctuation: ln = alphabet.find(message[i]) + alphabet.find(keyword_final[i]) translated_message += alphabet[ln % 26] else: translated_message += message[i] return translated_message message_for_v = "thanks for teaching me all these cool ciphers! you really are the best!" keyword = "besties" print(vigenere_coder(message_for_v,keyword)) print(vigenere_decoder(vigenere_coder(message_for_v, keyword), keyword)) ###Output ulsgsw xpv lxigzjry fm edm xzxai upsd vqtzfvk! rwy jfedeg ejf xzx jiku! thanks for teaching me all these cool ciphers! you really are the best!
3_FactorDecoupling/FactorDecoupling.ipynb
###Markdown Current Factor Decoupling ###Code import pandas as pd import numpy as np import matplotlib.pyplot as plt import datetime as dt from matplotlib import style import matplotlib as mpl import matplotlib.font_manager as fm style.use('ggplot') font = fm.FontProperties(fname='Font/helvetica.ttf') mpl.rcParams['font.family'] = font.get_name() import warnings warnings.filterwarnings('ignore') my_colors = {'DBlue':'#424f64', 'LBlue':'#a4afc0', 'BrBlue':'#85c7f2', 'DGrey':'#4c4c4c', 'MGrey':'#636363', 'DRed':'#961e19', 'LGrey':'#d1d1d1'} ###Output _____no_output_____ ###Markdown Last time we were talking about alpha, beta, and smart beta as the core principles of investment analysis.We saw that we could create market neutral factor portfolios based on certain desirable properties of stocks, e.g., Value vs. Growth, Size, etc.In this post, I suggest taking a closer look at the recent behavior of the Value factor (measured as HML factor as per Fama and French (1992)), Profitability factor (RMW in Fama and French (2015)), and the Deutsche Bank Quality Index.compared to the equity premium (Mkt-RF). HML and RMW performance In the previous post, we concluded that, for example, the Value factor provides positive or negative returns depending on whether the market rewards Value or Growth of companies. Let us see how the HML factor performed in 2010 – 2018. ###Code # Load factors df = pd.read_csv('Data/F-F_Research_Data_5_Factors_2x3_daily.CSV', index_col=0 ,parse_dates=True) #Keep relevant years df_old = df.loc['2000':'2009'] df_new = df.loc['2010':'2018'] # Create compound ret_old = (1+ df_old/100).cumprod() - 1 ret_new = (1+ df_new/100).cumprod() - 1 #Plot _ = plt.plot(ret_old['HML'], color=my_colors['BrBlue'], label = 'HML') _ = plt.plot(ret_old['Mkt-RF'], color='black', label = 'Mkt-RF') _ = plt.xlim('2000','2009') _ = plt.suptitle('Compound return HML vs. Mkt-RF factors', fontsize=18) _ = plt.title('(2000 - 2009)', fontsize= 12) _ = plt.legend() # Save _= plt.savefig('Graphs/HML_comp_00_09.png', dpi=300) _ = plt.plot(ret_new['HML'], color=my_colors['BrBlue'], label = 'HML') _ = plt.plot(ret_new['Mkt-RF'], color='black', label = 'Mkt-RF') _ = plt.xlim('2010','2019') _ = plt.suptitle('Compound return HML vs. Mkt-RF factors', fontsize=18) _ = plt.title('(2010 - 2018)', fontsize= 12) _ = plt.legend() # Save _= plt.savefig('Graphs/HML_comp_10_18.png', dpi=300) ###Output _____no_output_____ ###Markdown Almost flat compared to booming market factor.What about the Profitability (RMW) factor? ###Code _ = plt.plot(ret_old['RMW'], color=my_colors['BrBlue'], label = 'RMW') _ = plt.plot(ret_old['Mkt-RF'], color='black', label = 'Mkt-RF') _ = plt.xlim('2000','2009') _ = plt.suptitle('Compound return RMW vs. Mkt-RF factors', fontsize=18) _ = plt.title('(2000 - 2009)', fontsize= 12) _ = plt.legend() # Save _= plt.savefig('Graphs/RMW_comp_00_09.png', dpi=300) _ = plt.plot(ret_new['RMW'], color=my_colors['BrBlue'], label = 'RMW') _ = plt.plot(ret_new['Mkt-RF'], color='black', label = 'Mkt-RF') _ = plt.xlim('2010','2018') _ = plt.suptitle('Compound return RMW vs. Mkt-RF factors', fontsize=18) _ = plt.title('(2010 - 2018)', fontsize= 12) _ = plt.legend() # Save _= plt.savefig('Graphs/RMW_comp_10_18.png', dpi=300) ###Output _____no_output_____ ###Markdown Pretty much the same picture. Quality Index Finally, let's look at the Deutsche Bank Equity Sector-Neutral Quality Factor. You can read more about the index composition here (https://index.db.com/dbiqweb2/servlet/indexsummary?redirect=benchmarkIndexSummary&indexid=99000242&currencyreturntype=EUR-Local&rebalperiod=2&pricegroup=STD&history=4&reportingfrequency=1&returncategory=ER&indexStartDate=20150813&priceDate=20180813&isnew=true).In brief, it is a market neutral index that is supposed to measure the quality of the companies by investing into companies whose return on invested capital (ROIC) is higher than the average for the sector and selling short stocks of the companies whose ROIC underperforms sector average.Here we use USD denominated market neutral index.First, let’s see how the index performed in 2000 – 2009. ###Code #Combine index and X-rate dbq_usd = pd.read_csv('Data/DBGLSNQU.csv', index_col=0, parse_dates=True) dbq_usd.columns = ['DBGLSNQU'] # Calculate return dbq_usd = dbq_usd['DBGLSNQU'].pct_change() dbq_usd = pd.DataFrame(dbq_usd) #Add market dbq_usd = dbq_usd.join(df['Mkt-RF']/100, how='right') dbq_usd = dbq_usd.iloc[1:,] # Divide into periods dbq_old = dbq_usd.loc['2000':'2009'] dbq_new = dbq_usd.loc['2010':'2018'] # Create compound dbq_ret_old = (1+ dbq_old).cumprod() - 1 dbq_ret_new = (1+ dbq_new).cumprod() - 1 #Plot _ = plt.plot(dbq_ret_old['DBGLSNQU'], color=my_colors['BrBlue'], label = 'DBGLSNQU') _ = plt.plot(dbq_ret_old['Mkt-RF'], color='black', label = 'Mkt-RF') _ = plt.xlim('2000','2009') _ = plt.suptitle('Compound return DBGLSQU vs. Mkt-RF factors', fontsize=18) _ = plt.title('(2000 - 2009)', fontsize= 12) _ = plt.legend() # Save _= plt.savefig('Graphs/DBQ_comp_00_09.png', dpi=300) ###Output _____no_output_____ ###Markdown Now, let us look at recent years. ###Code _ = plt.plot(dbq_ret_new['DBGLSNQU'], color=my_colors['BrBlue'], label = 'DBGLSNQU') _ = plt.plot(dbq_ret_new['Mkt-RF'], color='black', label = 'Mkt-RF') _ = plt.xlim('2010','2018') _ = plt.suptitle('Compound return DBGLSQU vs. Mkt-RF factors', fontsize=18) _ = plt.title('(2010 - 2018)', fontsize= 12) _ = plt.legend() # Save _= plt.savefig('Graphs/DBQ_comp_10_18.png', dpi=300) ###Output _____no_output_____
practice_notes_copies/Weather_Database.ipynb
###Markdown Create set of 2,000 random latitudes and longitudes. ###Code # Create a set of random latitude and longitude combinations. lats = np.random.uniform(low=-90.000, high=90.000, size=2000) lngs = np.random.uniform(low=-180.000, high=180.000, size=2000) lat_lngs = zip(lats, lngs) lat_lngs # Add the latitudes and longitudes to a list. coordinates = list(lat_lngs) ###Output _____no_output_____ ###Markdown Get the nearest city using the citipy module. ###Code # Use the citipy module to determine city based on latitude and longitude. from citipy import citipy # Create a list for holding the cities. cities = [] # Identify the nearest city for each latitude and longitude combination. for coordinate in coordinates: city = citipy.nearest_city(coordinate[0], coordinate[1]).city_name # If the city is unique, then we will add it to the cities list. if city not in cities: cities.append(city) # Print the city count to confirm sufficient count. len(cities) ###Output _____no_output_____ ###Markdown Perform an API call with the OpenWeatherMap. ###Code # Import the requests library. import requests # Import the API key. from config import weather_api_key # Starting URL for Weather Map API Call. url = "http://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=" + weather_api_key # Import the datetime module from the datetime library. from datetime import datetime # Create an empty list to hold the weather data. city_data = [] # Print the beginning of the logging. print("Beginning Data Retrieval ") print("-----------------------------") # Create counters. record_count = 1 set_count = 1 ###Output Beginning Data Retrieval ----------------------------- ###Markdown Retrieve the weather information from the API call ###Code # Loop through all the cities in the list. for i, city in enumerate(cities): # Group cities in sets of 50 for logging purposes. if (i % 50 == 0 and i >= 50): set_count += 1 record_count = 1 # Create endpoint URL with each city. city_url = url + "&q=" + city.replace(" ","+") # Log the URL, record, and set numbers and the city. print(f"Processing Record {record_count} of Set {set_count} | {city}") # Add 1 to the record count. record_count += 1 # Run an API request for each of the cities. try: # Parse the JSON and retrieve data. city_weather = requests.get(city_url).json() # Parse out the needed data. city_lat = city_weather["coord"]["lat"] city_lng = city_weather["coord"]["lon"] city_max_temp = city_weather["main"]["temp_max"] city_humidity = city_weather["main"]["humidity"] city_clouds = city_weather["clouds"]["all"] city_wind = city_weather["wind"]["speed"] city_country = city_weather["sys"]["country"] city_description = city_weather["weather"][0]["description"] # Convert the date to ISO standard. city_date = datetime.utcfromtimestamp(city_weather["dt"]).strftime('%Y-%m-%d %H:%M:%S') # Append the city information into city_data list. city_data.append({"City": city.title(), "Lat": city_lat, "Lng": city_lng, "Max Temp": city_max_temp, "Humidity": city_humidity, "Cloudiness": city_clouds, "Wind Speed": city_wind, "Weather Description" : city_description, "Country": city_country, "Date": city_date}) # If an error is experienced, skip the city. except: print("City not found. Skipping...") pass # Indicate that Data Loading is complete. print("-----------------------------") print("Data Retrieval Complete ") print("-----------------------------") ###Output Processing Record 1 of Set 1 | bethel Processing Record 2 of Set 1 | yar-sale Processing Record 3 of Set 1 | rikitea Processing Record 4 of Set 1 | vaini Processing Record 5 of Set 1 | kaili Processing Record 6 of Set 1 | samusu City not found. Skipping... Processing Record 7 of Set 1 | thompson Processing Record 8 of Set 1 | tyup Processing Record 9 of Set 1 | vila Processing Record 10 of Set 1 | waipawa Processing Record 11 of Set 1 | banda aceh Processing Record 12 of Set 1 | grand gaube Processing Record 13 of Set 1 | zhangye Processing Record 14 of Set 1 | barstow Processing Record 15 of Set 1 | tuktoyaktuk Processing Record 16 of Set 1 | mataura Processing Record 17 of Set 1 | kahului Processing Record 18 of Set 1 | avarua Processing Record 19 of Set 1 | ushuaia Processing Record 20 of Set 1 | mar del plata Processing Record 21 of Set 1 | botwood Processing Record 22 of Set 1 | san quintin Processing Record 23 of Set 1 | cherskiy Processing Record 24 of Set 1 | nicolas bravo Processing Record 25 of Set 1 | sataua City not found. Skipping... Processing Record 26 of Set 1 | hithadhoo Processing Record 27 of Set 1 | saint george Processing Record 28 of Set 1 | illoqqortoormiut City not found. Skipping... Processing Record 29 of Set 1 | bengkulu Processing Record 30 of Set 1 | lyubinskiy Processing Record 31 of Set 1 | muros Processing Record 32 of Set 1 | emerald Processing Record 33 of Set 1 | longyearbyen Processing Record 34 of Set 1 | musoma Processing Record 35 of Set 1 | aswan Processing Record 36 of Set 1 | half moon bay Processing Record 37 of Set 1 | nikolskoye Processing Record 38 of Set 1 | dikson Processing Record 39 of Set 1 | jieshi Processing Record 40 of Set 1 | turukhansk Processing Record 41 of Set 1 | east london Processing Record 42 of Set 1 | paamiut Processing Record 43 of Set 1 | tuatapere Processing Record 44 of Set 1 | urgut Processing Record 45 of Set 1 | wembley Processing Record 46 of Set 1 | kapaa Processing Record 47 of Set 1 | redcar Processing Record 48 of Set 1 | krasnyy yar Processing Record 49 of Set 1 | punta arenas Processing Record 50 of Set 1 | eureka Processing Record 1 of Set 2 | chumikan Processing Record 2 of Set 2 | taolanaro City not found. Skipping... Processing Record 3 of Set 2 | tabiauea City not found. Skipping... Processing Record 4 of Set 2 | avera Processing Record 5 of Set 2 | busselton Processing Record 6 of Set 2 | haines junction Processing Record 7 of Set 2 | houma Processing Record 8 of Set 2 | kaitangata Processing Record 9 of Set 2 | erenhot Processing Record 10 of Set 2 | belyy yar Processing Record 11 of Set 2 | new norfolk Processing Record 12 of Set 2 | hilo Processing Record 13 of Set 2 | lebu Processing Record 14 of Set 2 | port alfred Processing Record 15 of Set 2 | jamestown Processing Record 16 of Set 2 | saskylakh Processing Record 17 of Set 2 | bambous virieux Processing Record 18 of Set 2 | airai Processing Record 19 of Set 2 | sargodha Processing Record 20 of Set 2 | lata Processing Record 21 of Set 2 | husavik Processing Record 22 of Set 2 | barrow Processing Record 23 of Set 2 | whitefish Processing Record 24 of Set 2 | yucca valley Processing Record 25 of Set 2 | san cristobal Processing Record 26 of Set 2 | pemangkat Processing Record 27 of Set 2 | atar Processing Record 28 of Set 2 | gravdal Processing Record 29 of Set 2 | albany Processing Record 30 of Set 2 | puerto ayora Processing Record 31 of Set 2 | grand river south east City not found. Skipping... Processing Record 32 of Set 2 | cape town Processing Record 33 of Set 2 | carnarvon Processing Record 34 of Set 2 | portland Processing Record 35 of Set 2 | itapirapua Processing Record 36 of Set 2 | nacala Processing Record 37 of Set 2 | weihai Processing Record 38 of Set 2 | beira Processing Record 39 of Set 2 | isabela Processing Record 40 of Set 2 | asfi Processing Record 41 of Set 2 | manadhoo Processing Record 42 of Set 2 | kavieng Processing Record 43 of Set 2 | bredasdorp Processing Record 44 of Set 2 | khandyga Processing Record 45 of Set 2 | qaanaaq Processing Record 46 of Set 2 | udachnyy Processing Record 47 of Set 2 | castro Processing Record 48 of Set 2 | isangel Processing Record 49 of Set 2 | mandera Processing Record 50 of Set 2 | fairbanks Processing Record 1 of Set 3 | tasiilaq Processing Record 2 of Set 3 | saint-philippe Processing Record 3 of Set 3 | butaritari Processing Record 4 of Set 3 | umm lajj Processing Record 5 of Set 3 | saint anthony Processing Record 6 of Set 3 | kashary Processing Record 7 of Set 3 | namatanai Processing Record 8 of Set 3 | lolua City not found. Skipping... Processing Record 9 of Set 3 | wattegama Processing Record 10 of Set 3 | hobyo Processing Record 11 of Set 3 | naftah City not found. Skipping... Processing Record 12 of Set 3 | karlstad Processing Record 13 of Set 3 | bluff Processing Record 14 of Set 3 | gratkorn Processing Record 15 of Set 3 | hermanus Processing Record 16 of Set 3 | nouadhibou Processing Record 17 of Set 3 | along Processing Record 18 of Set 3 | chuy Processing Record 19 of Set 3 | tsihombe City not found. Skipping... Processing Record 20 of Set 3 | ola Processing Record 21 of Set 3 | huilong Processing Record 22 of Set 3 | yellowknife Processing Record 23 of Set 3 | khatanga Processing Record 24 of Set 3 | sibu Processing Record 25 of Set 3 | lagoa Processing Record 26 of Set 3 | caravelas Processing Record 27 of Set 3 | padang Processing Record 28 of Set 3 | itarema Processing Record 29 of Set 3 | idlib Processing Record 30 of Set 3 | salalah Processing Record 31 of Set 3 | aurich Processing Record 32 of Set 3 | borzya Processing Record 33 of Set 3 | trujillo Processing Record 34 of Set 3 | constitucion Processing Record 35 of Set 3 | mys shmidta City not found. Skipping... Processing Record 36 of Set 3 | vardo Processing Record 37 of Set 3 | quatre cocos Processing Record 38 of Set 3 | hamilton Processing Record 39 of Set 3 | ouadda Processing Record 40 of Set 3 | donskoye Processing Record 41 of Set 3 | naujamiestis Processing Record 42 of Set 3 | amontada Processing Record 43 of Set 3 | kiunga Processing Record 44 of Set 3 | nefteyugansk Processing Record 45 of Set 3 | beringovskiy Processing Record 46 of Set 3 | ngunguru Processing Record 47 of Set 3 | georgetown Processing Record 48 of Set 3 | nandyal Processing Record 49 of Set 3 | tessalit Processing Record 50 of Set 3 | kruisfontein Processing Record 1 of Set 4 | torbay Processing Record 2 of Set 4 | dingle Processing Record 3 of Set 4 | namibe Processing Record 4 of Set 4 | chapais Processing Record 5 of Set 4 | victoria Processing Record 6 of Set 4 | la rioja Processing Record 7 of Set 4 | rawson Processing Record 8 of Set 4 | sitka Processing Record 9 of Set 4 | egvekinot Processing Record 10 of Set 4 | weligama Processing Record 11 of Set 4 | tukrah Processing Record 12 of Set 4 | carballo Processing Record 13 of Set 4 | harper Processing Record 14 of Set 4 | belushya guba City not found. Skipping... Processing Record 15 of Set 4 | cabo san lucas Processing Record 16 of Set 4 | sinnamary Processing Record 17 of Set 4 | mount gambier Processing Record 18 of Set 4 | tiksi Processing Record 19 of Set 4 | moscow Processing Record 20 of Set 4 | bathsheba Processing Record 21 of Set 4 | umea Processing Record 22 of Set 4 | provideniya Processing Record 23 of Set 4 | sao jose da coroa grande Processing Record 24 of Set 4 | cuenca Processing Record 25 of Set 4 | tombouctou Processing Record 26 of Set 4 | shingu Processing Record 27 of Set 4 | hofn Processing Record 28 of Set 4 | kaihua Processing Record 29 of Set 4 | port elizabeth Processing Record 30 of Set 4 | leningradskiy Processing Record 31 of Set 4 | chokurdakh Processing Record 32 of Set 4 | ararat Processing Record 33 of Set 4 | mnogovershinnyy Processing Record 34 of Set 4 | aksu Processing Record 35 of Set 4 | tawkar City not found. Skipping... Processing Record 36 of Set 4 | port-gentil Processing Record 37 of Set 4 | mahebourg Processing Record 38 of Set 4 | barentsburg City not found. Skipping... Processing Record 39 of Set 4 | kieta Processing Record 40 of Set 4 | alto araguaia Processing Record 41 of Set 4 | barawe ###Markdown Add the data to a new DataFrame. ###Code # Convert the array of dictionaries to a Pandas DataFrame. city_data_df = pd.DataFrame(city_data) city_data_df.head(10) new_column_order = ["City", "Country", "Lat","Lng", "Max Temp", "Humidity","Cloudiness", "Wind Speed", "Weather Description"] city_data_df = city_data_df[new_column_order] city_data_df.head(10) ###Output _____no_output_____ ###Markdown Export the DataFrame as a CSV file ###Code # Create the output file (CSV). output_data_file = "Weather_Database/WeatherPy_Database.csv" # Export the City_Data into a CSV. city_data_df.to_csv(output_data_file, index_label="City_ID") ###Output _____no_output_____
Machine_Learning_Scratch/PCA/principal_component_analysis.ipynb
###Markdown Principal Component Analysis in 3 Simple Steps Principal Component Analysis (PCA) is a simple yet popular and useful linear transformation technique that is used in numerous applications, such as stock market predictions, the analysis of gene expression data, and many more. In this tutorial, we will see that PCA is not just a "black box", and we are going to unravel its internals in 3 basic steps. This article just got a complete overhaul, the original version is still available at [principal_component_analysis_old.ipynb](http://nbviewer.ipython.org/github/rasbt/pattern_classification/blob/master/dimensionality_reduction/projection/principal_component_analysis.ipynb). Sections - [Introduction](Introduction) - [PCA Vs. LDA](PCA-Vs.-LDA) - [PCA and Dimensionality Reduction](PCA-and-Dimensionality-Reduction) - [A Summary of the PCA Approach](A-Summary-of-the-PCA-Approach)- [Preparing the Iris Dataset](Preparing-the-Iris-Dataset) - [About Iris](About-Iris) - [Loading the Dataset](Loading-the-Dataset) - [Exploratory Visualization](Exploratory-Visualization) - [Standardizing](Standardizing)- [1 - Eigendecomposition - Computing Eigenvectors and Eigenvalues](1---Eigendecomposition---Computing-Eigenvectors-and-Eigenvalues) - [Covariance Matrix](Covariance-Matrix) - [Correlation Matrix](Correlation-Matrix) - [Singular Vector Decomposition](Singular-Vector-Decomposition)- [2 - Selecting Principal Components](2---Selecting-Principal-Components) - [Sorting Eigenpairs](Sorting-Eigenpairs) - [Explained Variance](Explained-Variance) - [Projection Matrix](Projection-Matrix)- [3 - Projection Onto the New Feature Space](3---Selecting-Principal-Components)- [Shortcut - PCA in scikit-learn](Shortcut---PCA-in-scikit-learn) Introduction [[back to top](Sections)] The sheer size of data in the modern age is not only a challenge for computer hardware but also a main bottleneck for the performance of many machine learning algorithms. The main goal of a PCA analysis is to identify patterns in data; PCA aims to detect the correlation between variables. If a strong correlation between variables exists, the attempt to reduce the dimensionality only makes sense. In a nutshell, this is what PCA is all about: Finding the directions of maximum variance in high-dimensional data and project it onto a smaller dimensional subspace while retaining most of the information. PCA Vs. LDA [[back to top](Sections)] Both Linear Discriminant Analysis (LDA) and PCA are linear transformation methods. PCA yields the directions (principal components) that maximize the variance of the data, whereas LDA also aims to find the directions that maximize the separation (or discrimination) between different classes, which can be useful in pattern classification problem (PCA "ignores" class labels). ***In other words, PCA projects the entire dataset onto a different feature (sub)space, and LDA tries to determine a suitable feature (sub)space in order to distinguish between patterns that belong to different classes.*** PCA and Dimensionality Reduction [[back to top](Sections)] Often, the desired goal is to reduce the dimensions of a $d$-dimensional dataset by projecting it onto a $(k)$-dimensional subspace (where $k\;<\;d$) in order to increase the computational efficiency while retaining most of the information. An important question is "what is the size of $k$ that represents the data 'well'?"Later, we will compute eigenvectors (the principal components) of a dataset and collect them in a projection matrix. Each of those eigenvectors is associated with an eigenvalue which can be interpreted as the "length" or "magnitude" of the corresponding eigenvector. If some eigenvalues have a significantly larger magnitude than others that the reduction of the dataset via PCA onto a smaller dimensional subspace by dropping the "less informative" eigenpairs is reasonable. A Summary of the PCA Approach [[back to top](Sections)] - Standardize the data.- Obtain the Eigenvectors and Eigenvalues from the covariance matrix or correlation matrix, or perform Singular Vector Decomposition.- Sort eigenvalues in descending order and choose the $k$ eigenvectors that correspond to the $k$ largest eigenvalues where $k$ is the number of dimensions of the new feature subspace ($k \le d$)/.- Construct the projection matrix $\mathbf{W}$ from the selected $k$ eigenvectors.- Transform the original dataset $\mathbf{X}$ via $\mathbf{W}$ to obtain a $k$-dimensional feature subspace $\mathbf{Y}$. Preparing the Iris Dataset [[back to top](Sections)] About Iris [[back to top](Sections)] For the following tutorial, we will be working with the famous "Iris" dataset that has been deposited on the UCI machine learning repository ([https://archive.ics.uci.edu/ml/datasets/Iris](https://archive.ics.uci.edu/ml/datasets/Iris)).The iris dataset contains measurements for 150 iris flowers from three different species.The three classes in the Iris dataset are:1. Iris-setosa (n=50)2. Iris-versicolor (n=50)3. Iris-virginica (n=50)And the four features of in Iris dataset are:1. sepal length in cm2. sepal width in cm3. petal length in cm4. petal width in cm Loading the Dataset [[back to top](Sections)] In order to load the Iris data directly from the UCI repository, we are going to use the superb [pandas](http://pandas.pydata.org) library. If you haven't used pandas yet, I want encourage you to check out the [pandas tutorials](http://pandas.pydata.org/pandas-docs/stable/tutorials.html). If I had to name one Python library that makes working with data a wonderfully simple task, this would definitely be pandas! ###Code import pandas as pd df = pd.read_csv( filepath_or_buffer='https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data', header=None, sep=',') df.columns=['sepal_len', 'sepal_wid', 'petal_len', 'petal_wid', 'class'] df.dropna(how="all", inplace=True) # drops the empty line at file-end df.tail() # split data table into data X and class labels y X = df.ix[:,0:4].values y = df.ix[:,4].values ###Output _____no_output_____ ###Markdown Our iris dataset is now stored in form of a $150 \times 4$ matrix where the columns are the different features, and every row represents a separate flower sample.Each sample row $\mathbf{x}$ can be pictured as a 4-dimensional vector $\mathbf{x^T} = \begin{pmatrix} x_1 \\ x_2 \\ x_3 \\ x_4 \end{pmatrix} = \begin{pmatrix} \text{sepal length} \\ \text{sepal width} \\\text{petal length} \\ \text{petal width} \end{pmatrix}$ Exploratory Visualization [[back to top](Sections)] To get a feeling for how the 3 different flower classes are distributes along the 4 different features, let us visualize them via histograms. ###Code from matplotlib import pyplot as plt import numpy as np import math label_dict = {1: 'Iris-Setosa', 2: 'Iris-Versicolor', 3: 'Iris-Virgnica'} feature_dict = {0: 'sepal length [cm]', 1: 'sepal width [cm]', 2: 'petal length [cm]', 3: 'petal width [cm]'} with plt.style.context('seaborn-whitegrid'): plt.figure(figsize=(8, 6)) for cnt in range(4): plt.subplot(2, 2, cnt+1) for lab in ('Iris-setosa', 'Iris-versicolor', 'Iris-virginica'): plt.hist(X[y==lab, cnt], label=lab, bins=10, alpha=0.3,) plt.xlabel(feature_dict[cnt]) plt.legend(loc='upper right', fancybox=True, fontsize=8) plt.tight_layout() plt.show() ###Output _____no_output_____ ###Markdown Standardizing [[back to top](Sections)] Whether to standardize the data prior to a PCA on the covariance matrix depends on the measurement scales of the original features. Since PCA yields a feature subspace that maximizes the variance along the axes, it makes sense to standardize the data, especially, if it was measured on different scales. Although, all features in the Iris dataset were measured in centimeters, let us continue with the transformation of the data onto unit scale (mean=0 and variance=1), which is a requirement for the optimal performance of many machine learning algorithms. ###Code from sklearn.preprocessing import StandardScaler X_std = StandardScaler().fit_transform(X) ###Output _____no_output_____ ###Markdown 1 - Eigendecomposition - Computing Eigenvectors and Eigenvalues [[back to top](Sections)] The eigenvectors and eigenvalues of a covariance (or correlation) matrix represent the "core" of a PCA: The eigenvectors (principal components) determine the directions of the new feature space, and the eigenvalues determine their magnitude. In other words, the eigenvalues explain the variance of the data along the new feature axes. Covariance Matrix [[back to top](Sections)] The classic approach to PCA is to perform the eigendecomposition on the covariance matrix $\Sigma$, which is a $d \times d$ matrix where each element represents the covariance between two features. The covariance between two features is calculated as follows:$\sigma_{jk} = \frac{1}{n-1}\sum_{i=1}^{N}\left( x_{ij}-\bar{x}_j \right) \left( x_{ik}-\bar{x}_k \right).$We can summarize the calculation of the covariance matrix via the following matrix equation: $\Sigma = \frac{1}{n-1} \left( (\mathbf{X} - \mathbf{\bar{x}})^T\;(\mathbf{X} - \mathbf{\bar{x}}) \right)$ where $\mathbf{\bar{x}}$ is the mean vector $\mathbf{\bar{x}} = \sum\limits_{i=1}^n x_{i}.$ The mean vector is a $d$-dimensional vector where each value in this vector represents the sample mean of a feature column in the dataset. ###Code import numpy as np mean_vec = np.mean(X_std, axis=0) cov_mat = (X_std - mean_vec).T.dot((X_std - mean_vec)) / (X_std.shape[0]-1) print('Covariance matrix \n%s' %cov_mat) import numpy as np mean_vec = np.mean(X_std, axis=0) cov_mat = (X_std - mean_vec).T.dot((X_std - mean_vec)) / (X_std.shape[0]-1) print('Covariance matrix \n%s' %cov_mat) ###Output Covariance matrix [[ 1.00671141 -0.11010327 0.87760486 0.82344326] [-0.11010327 1.00671141 -0.42333835 -0.358937 ] [ 0.87760486 -0.42333835 1.00671141 0.96921855] [ 0.82344326 -0.358937 0.96921855 1.00671141]] ###Markdown The more verbose way above was simply used for demonstration purposes, equivalently, we could have used the numpy `cov` function: ###Code print('NumPy covariance matrix: \n%s' %np.cov(X_std.T)) ###Output NumPy covariance matrix: [[ 1.00671141 -0.11010327 0.87760486 0.82344326] [-0.11010327 1.00671141 -0.42333835 -0.358937 ] [ 0.87760486 -0.42333835 1.00671141 0.96921855] [ 0.82344326 -0.358937 0.96921855 1.00671141]] ###Markdown Next, we perform an eigendecomposition on the covariance matrix: ###Code cov_mat = np.cov(X_std.T) eig_vals, eig_vecs = np.linalg.eig(cov_mat) print('Eigenvectors \n%s' %eig_vecs) print('\nEigenvalues \n%s' %eig_vals) ###Output Eigenvectors [[ 0.52237162 -0.37231836 -0.72101681 0.26199559] [-0.26335492 -0.92555649 0.24203288 -0.12413481] [ 0.58125401 -0.02109478 0.14089226 -0.80115427] [ 0.56561105 -0.06541577 0.6338014 0.52354627]] Eigenvalues [ 2.93035378 0.92740362 0.14834223 0.02074601] ###Markdown Correlation Matrix [[back to top](Sections)] Especially, in the field of "Finance," the correlation matrix typically used instead of the covariance matrix. However, the eigendecomposition of the covariance matrix (if the input data was standardized) yields the same results as a eigendecomposition on the correlation matrix, since the correlation matrix can be understood as the normalized covariance matrix. Eigendecomposition of the standardized data based on the correlation matrix: ###Code cor_mat1 = np.corrcoef(X_std.T) eig_vals, eig_vecs = np.linalg.eig(cor_mat1) print('Eigenvectors \n%s' %eig_vecs) print('\nEigenvalues \n%s' %eig_vals) ###Output Eigenvectors [[ 0.52237162 -0.37231836 -0.72101681 0.26199559] [-0.26335492 -0.92555649 0.24203288 -0.12413481] [ 0.58125401 -0.02109478 0.14089226 -0.80115427] [ 0.56561105 -0.06541577 0.6338014 0.52354627]] Eigenvalues [ 2.91081808 0.92122093 0.14735328 0.02060771] ###Markdown Eigendecomposition of the raw data based on the correlation matrix: ###Code cor_mat2 = np.corrcoef(X.T) eig_vals, eig_vecs = np.linalg.eig(cor_mat2) print('Eigenvectors \n%s' %eig_vecs) print('\nEigenvalues \n%s' %eig_vals) ###Output Eigenvectors [[ 0.52237162 -0.37231836 -0.72101681 0.26199559] [-0.26335492 -0.92555649 0.24203288 -0.12413481] [ 0.58125401 -0.02109478 0.14089226 -0.80115427] [ 0.56561105 -0.06541577 0.6338014 0.52354627]] Eigenvalues [ 2.91081808 0.92122093 0.14735328 0.02060771] ###Markdown We can clearly see that all three approaches yield the same eigenvectors and eigenvalue pairs: - Eigendecomposition of the covariance matrix after standardizing the data.- Eigendecomposition of the correlation matrix.- Eigendecomposition of the correlation matrix after standardizing the data. Singular Vector Decomposition [[back to top](Sections)] While the eigendecomposition of the covariance or correlation matrix may be more intuitiuve, most PCA implementations perform a Singular Vector Decomposition (SVD) to improve the computational efficiency. So, let us perform an SVD to confirm that the result are indeed the same: ###Code u,s,v = np.linalg.svd(X_std.T) print('Vectors U:\n', u) ###Output Vectors U: [[-0.52237162 -0.37231836 0.72101681 0.26199559] [ 0.26335492 -0.92555649 -0.24203288 -0.12413481] [-0.58125401 -0.02109478 -0.14089226 -0.80115427] [-0.56561105 -0.06541577 -0.6338014 0.52354627]] ###Markdown 2 - Selecting Principal Components [[back to top](Sections)] Sorting Eigenpairs [[back to top](Sections)] The typical goal of a PCA is to reduce the dimensionality of the original feature space by projecting it onto a smaller subspace, where the eigenvectors will form the axes. However, the eigenvectors only define the directions of the new axis, since they have all the same unit length 1, which can confirmed by the following two lines of code: ###Code for ev in eig_vecs: np.testing.assert_array_almost_equal(1.0, np.linalg.norm(ev)) print('Everything ok!') ###Output Everything ok! ###Markdown In order to decide which eigenvector(s) can dropped without losing too much informationfor the construction of lower-dimensional subspace, we need to inspect the corresponding eigenvalues: The eigenvectors with the lowest eigenvalues bear the least information about the distribution of the data; those are the ones can be dropped. In order to do so, the common approach is to rank the eigenvalues from highest to lowest in order choose the top $k$ eigenvectors. ###Code # Make a list of (eigenvalue, eigenvector) tuples eig_pairs = [(np.abs(eig_vals[i]), eig_vecs[:,i]) for i in range(len(eig_vals))] # Sort the (eigenvalue, eigenvector) tuples from high to low eig_pairs.sort(key=lambda x: x[0], reverse=True) # Visually confirm that the list is correctly sorted by decreasing eigenvalues print('Eigenvalues in descending order:') for i in eig_pairs: print(i[0]) ###Output Eigenvalues in descending order: 2.91081808375 0.921220930707 0.147353278305 0.0206077072356 ###Markdown Explained Variance [[back to top](Sections)] After sorting the eigenpairs, the next question is "how many principal components are we going to choose for our new feature subspace?" A useful measure is the so-called "explained variance," which can be calculated from the eigenvalues. The explained variance tells us how much information (variance) can be attributed to each of the principal components. ###Code tot = sum(eig_vals) var_exp = [(i / tot)*100 for i in sorted(eig_vals, reverse=True)] cum_var_exp = np.cumsum(var_exp) with plt.style.context('seaborn-whitegrid'): plt.figure(figsize=(6, 4)) plt.bar(range(4), var_exp, alpha=0.5, align='center', label='individual explained variance') plt.step(range(4), cum_var_exp, where='mid', label='cumulative explained variance') plt.ylabel('Explained variance ratio') plt.xlabel('Principal components') plt.legend(loc='best') plt.tight_layout() plt.savefig('/Users/Sebastian/Desktop/pca2.pdf') ###Output _____no_output_____ ###Markdown The plot above clearly shows that most of the variance (72.77% of the variance to be precise) can be explained by the first principal component alone. The second principal component still bears some information (23.03%) while the third and fourth principal components can safely be dropped without losing to much information. Together, the first two principal components contain 95.8% of the information. Projection Matrix [[back to top](Sections)] It's about time to get to the really interesting part: The construction of the projection matrix that will be used to transform the Iris data onto the new feature subspace. Although, the name "projection matrix" has a nice ring to it, it is basically just a matrix of our concatenated top *k* eigenvectors.Here, we are reducing the 4-dimensional feature space to a 2-dimensional feature subspace, by choosing the "top 2" eigenvectors with the highest eigenvalues to construct our $d \times k$-dimensional eigenvector matrix $\mathbf{W}$. ###Code matrix_w = np.hstack((eig_pairs[0][1].reshape(4,1), eig_pairs[1][1].reshape(4,1))) print('Matrix W:\n', matrix_w) ###Output Matrix W: [[ 0.52237162 -0.37231836] [-0.26335492 -0.92555649] [ 0.58125401 -0.02109478] [ 0.56561105 -0.06541577]] ###Markdown 3 - Projection Onto the New Feature Space [[back to top](Sections)] In this last step we will use the $4 \times 2$-dimensional projection matrix $\mathbf{W}$ to transform our samples onto the new subspace via the equation $\mathbf{Y} = \mathbf{X} \times \mathbf{W}$, where $\mathbf{Y}$ is a $150\times 2$ matrix of our transformed samples. ###Code Y = X_std.dot(matrix_w) with plt.style.context('seaborn-whitegrid'): plt.figure(figsize=(6, 4)) for lab, col in zip(('Iris-setosa', 'Iris-versicolor', 'Iris-virginica'), ('blue', 'red', 'green')): plt.scatter(Y[y==lab, 0], Y[y==lab, 1], label=lab, c=col) plt.xlabel('Principal Component 1') plt.ylabel('Principal Component 2') plt.legend(loc='lower center') plt.tight_layout() plt.savefig('/Users/Sebastian/Desktop/pca1.pdf') ###Output _____no_output_____ ###Markdown Shortcut - PCA in scikit-learn [[back to top](Sections)] For educational purposes, we went a long way to apply the PCA to the Iris dataset. But luckily, there is already implementation in scikit-learn. ###Code from sklearn.decomposition import PCA as sklearnPCA sklearn_pca = sklearnPCA(n_components=2) Y_sklearn = sklearn_pca.fit_transform(X_std) with plt.style.context('seaborn-whitegrid'): plt.figure(figsize=(6, 4)) for lab, col in zip(('Iris-setosa', 'Iris-versicolor', 'Iris-virginica'), ('blue', 'red', 'green')): plt.scatter(Y_sklearn[y==lab, 0], Y_sklearn[y==lab, 1], label=lab, c=col) plt.xlabel('Principal Component 1') plt.ylabel('Principal Component 2') plt.legend(loc='lower center') plt.tight_layout() plt.show() ###Output _____no_output_____
HI_70/notebook2/flo_test/3.2. model hao diameter.ipynb
###Markdown 1. Bagging ###Code # This is a grid search for three parameters in the Bagging algorithm. # Parameters are: max_depth, n_estimators, random_state. # This gives the best combination of the three parameters for the smallest mean squared error. min_mae = 99999 min_i, min_j, min_k = 0, 0, 0 for i in tqdm(range(1, 21)): for j in range(1, 21): for k in range(5, 50, 5): B_regr = BaggingRegressor(base_estimator=DecisionTreeRegressor(max_depth=i), n_estimators=j, random_state=k) B_regr.fit(X_train, np.ravel(Y_train)) B_Y_pred = B_regr.predict(X_test) mae = mean_absolute_error(Y_test, B_Y_pred) if (min_mae > mae): min_mae = mae min_i = i min_j = j min_k = k print(min_mae, min_i, min_j, min_k) ###Output 100%|██████████| 20/20 [01:15<00:00, 3.77s/it] ###Markdown 2. Decision Trees ###Code # This is a grid search for three parameters in the Decision Trees algorithm. # Parameters are: max_depth, max_features, random_state. # This gives the best combination of the three parameters for the smallest mean squared error. min_mae = 99999 min_i, min_j, min_k = 0, 0, 0 for i in tqdm(range(1, 21)): for j in range(1, 21): for k in range(5, 40, 2): DT_regr = DecisionTreeRegressor(max_depth=i, max_features=j, random_state=k) DT_regr.fit(X_train, Y_train) DT_Y_pred = DT_regr.predict(X_test) mae = mean_absolute_error(Y_test, DT_Y_pred) if (min_mae > mae): min_mae = mae min_i = i min_j = j min_k = k print(min_mae, min_i, min_j, min_k) ###Output 100%|██████████| 20/20 [00:42<00:00, 2.10s/it] ###Markdown 3. Random Forrest ###Code # This is a grid search for three parameters in the Random Forest algorithm. # Parameters are: max_depth, n_estimators, max_features. # Random_state is set to 45. # This gives the best combination of the three parameters for the smallest mean squared error. min_mae = 99999 min_i, min_j, min_k = 0, 0, 0 for i in tqdm(range(1, 21)): for j in range(1, 21): for k in range(2, 50, 2): RF_regr = RandomForestRegressor(max_depth=i, n_estimators=j, max_features=k, random_state=45 ) RF_regr.fit(X_train, np.ravel(Y_train)) RF_Y_pred = RF_regr.predict(X_test) mae = mean_absolute_error(Y_test, RF_Y_pred) if (min_mae > mae): min_mae = mae min_i = i min_j = j min_k = k print(min_mae, min_i, min_j, min_k) ###Output 100%|██████████| 20/20 [02:46<00:00, 8.32s/it] ###Markdown 4. Extra Trees ###Code # This is a grid search for three parameters in the Extra Trees algorithm. # Parameters are: random_state, n_estimators, max_features. # This gives the best combination of the three parameters for the smallest mean squared error. min_mae = 99999 min_i, min_j, min_k = 0, 0, 0 for i in tqdm(range(1, 21)): for j in range(1, 21): for k in range(2, 50, 1): ET_regr = ExtraTreesRegressor(n_estimators=i, max_features=j, random_state=k ) ET_regr.fit(X_train, np.ravel(Y_train)) ET_Y_pred = ET_regr.predict(X_test) mae = mean_absolute_error(Y_test, ET_Y_pred) if (min_mae > mae): min_mae = mae min_i = i min_j = j min_k = k print(min_mae, min_i, min_j, min_k) ###Output 100%|██████████| 20/20 [04:29<00:00, 13.49s/it] ###Markdown 5. Gradient Boosting ###Code min_mae = 999 min_i, min_j, min_k, min_l = 0, 0, 0.0, 0 for i in tqdm(range(300, 400, 10)): for j in range(2, 40, 2): for k in np.arange(0.04, 0.22, 0.02): for l in range(2, 10, 2): GB_regr = GradientBoostingRegressor(n_estimators=i, max_depth=j, learning_rate=k, random_state=l) GB_regr.fit(X_train, np.ravel(Y_train)) GB_Y_pred = GB_regr.predict(X_test) mae = mean_absolute_error(Y_test, GB_Y_pred) if (min_mae > mae): min_mae = mae min_i = i min_j = j min_k = k min_l = l print(min_mae, min_i, min_j, min_k, min_l) ###Output 10%|█ | 1/10 [02:47<25:08, 167.65s/it] ###Markdown 6. Others ###Code REGRESSIONS = { "K-nn": KNeighborsRegressor(), "Ridge": RidgeCV(), "Lasso": Lasso(), "ElasticNet": ElasticNet(random_state=0), } # mean absolute error is used to evaluate the performance of all regressions. for name, reg in REGRESSIONS.items(): reg.fit(X_train, Y_train) Y_pred = pd.DataFrame(reg.predict(X_test)) print(name) mae = mean_absolute_error(Y_test, Y_pred) print(' MAE for diameter is ', mae, '\n') ###Output K-nn MAE for diameter is 0.7563636363636366 Ridge MAE for diameter is 0.6253231781201205 Lasso MAE for diameter is 0.6448976800902813 ElasticNet MAE for diameter is 0.6564879495126625 ###Markdown Conclusion Bagging has the best performance ###Code ET_regr = ExtraTreesRegressor(n_estimators=1, max_features=16, random_state=25 ) ET_regr.fit(X_train, np.ravel(Y_train)) ET_Y_pred = ET_regr.predict(X_test) joblib.dump(ET_regr, "./model_aug_diameter_ExtraTrees.joblib") ###Output _____no_output_____
notebooks/code/20 - Train a neural network with backpropagation.ipynb
###Markdown Inicialización de la red Utilizaremos pesos generados de forma aleatoria. ###Code # Inicialización de una red con 1 capa de entrada, 1 capa oculta y 1 capa de salida def init_network(n_inputs, n_hidden, n_outputs): """ Inicialización de la red. :param n_inputs: (int) Número de variables de entrada a la red. :param n_hidden: (int) Número de neuronas en la capa oculta. :param n_outputs: (int) Número de neuronas en la capa de salida. """ # Inicializamos una variable de tipo lista, donde iremos almacenando las capas que generemos network = list() # CREACIÓN DE LA CAPA OCULTA # Para cada neurona de la capa oculta, generamos tantos pesos como n_inputs haya, más uno que corresponde al bias # El bias es equivalente a otro peso más, solo que no se multiplicará por ninguna de los valores que recibe la neurona # (Tener siempre en cuenta que, en cada lista de pesos, el último elemento será, por tanto, el bias) hidden_layer = [{"weights": [random() for i in range(n_inputs + 1)]} for i in range(n_hidden)] network.append(hidden_layer) # CREACIÓN DE LA CAPA DE SALIDA # Para cada neurona de la capa de salida, generamos tantos pesos como n_hidden haya, más uno que corresponde al bias output_layer = [{"weights": [random() for i in range(n_hidden + 1)]} for i in range(n_outputs)] network.append(output_layer) return network # Plantamos una semilla para que los valores aleatorios siempre sean los mismos seed(1) # Vamos a probar la inicialización de una red con 2 neuronas en la capa de entrada, 1 en la capa oculta y 2 en la de salida init_network(2, 1, 2) ###Output _____no_output_____ ###Markdown La arquitectura anterior corresponde a una red como la siguiente:![Neural_network.png](attachment:Neural_network.png) Al inicializar la red vemos que se genera una lista de listas, en la que:- La primera lista contiene los pesos de la única neurona de la capa oculta, más el bias asociado (que es el último elemento de esta lista de 3 pesos). Es decir, los valores *0.13436424411240122* y *0.8474337369372327* son los pesos que recibe la neurona, asociados a los valores de la capa de entrada, mientras que *0.763774618976614* es el bias (que no se multiplicará por ninguno de los valores de la capa de entrada).- La segunda lista contiene, a su vez, dos diccionarios de pesos: - Uno con el peso que conecta la neurona de la capa oculta con una de las neuronas de salida, más el bias (que es el último elemento de esta lista de 2 pesos). - Otro con el peso que conecta la neurona de la capa oculta con la otra neurona de salida, más el bias (que es el último elemento de esta lista de 2 pesos). ![Neural_network2.png](attachment:Neural_network2.png) Pase hacia delante La salida de la neurona de la capa oculta (a la que asociaremos el subíndice **h**, de *hidden*) se puede calcular de la siguiente manera:`output_h = activation_function(weight_i1 * input_i1 + weight_i2 * input_i2 + bias_h)`Donde **i1** e **i2** son los subíndices asociados a las neuronas de la capa de entrada (*input*).Es decir, necesitamos calcular la suma ponderada de las entradas, a la que añadiremos también el valor del bias:`output_h = activation_function(sum(weight_i * input_i) + bias)`Para ello, vamos a definir dos funciones: una que permitirá calcular sumas ponderadas y otra que permitirá aplicar una función de activación a una suma ponderada ya calculada. ###Code def weighted_sum(weights, inputs): """ Cálculo de la suma ponderada dentro de una neurona en concreto. :param weights: (list) Lista de pesos asociados a las entradas que recibe la neurona. :param inputs: (list) Lista de entradas que recibe la neurona. """ # En primer lugar, añadimos el bias a la suma ponderada, ya que no hay que multiplicarlo por ninguna entrada # (Recordemos que es el último elemento de la lista de pesos) suma_ponderada = weights[-1] # Para el resto de pesos de la lista for i in range(len(weights) - 1): # Se añade a la suma ponderada la multiplicación de cada peso por su respectiva entrada suma_ponderada += weights[i] * inputs[i] return suma_ponderada ###Output _____no_output_____ ###Markdown Para este ejemplo, se utilizará la función de activación sigmoide: $$\sigma(x) = \frac{1}{1 + e^{-x}}$$ ###Code def activation_function(suma_ponderada): """ Aplicación de una función de activación. :param suma_ponderada: (float) Suma ponderada de las entradas que recibe una neurona. """ # Función sigmoide (logística) return 1.0 / (1.0 + np.exp(-suma_ponderada)) ###Output _____no_output_____ ###Markdown Recordemos cómo funciona el pase hacia delante: ![Neural_network_d.png](attachment:Neural_network_d.png) ###Code def forward_propagation(network, row): """ Pase hacia delante en una red neuronal. :param network: (list) Lista de pesos asociados a las entradas. :param row: (list) Lista de entradas. """ # Las primeras entradas que recibe la red son los datos de la fila del dataset que introducimos inputs = row # Inicializamos un contador de capas, para controlar en qué punto de la red estamos # Empezamos en la capa 1 (la de entrada) layer_idx = 1 # Para cada capa en la red for layer in network: # Sumamos 1 al contador de capas (ya que empezamos a analizar la primera capa oculta) layer_idx += 1 # Vamos a ver qué pesos tienen asociados todas las neuronas de la capa print(f"Pesos de las neuronas de la capa {layer_idx}: {layer}") # Las entradas de cada capa irán cambiando # Las entradas de la última capa, en este caso, serán las salidas de la capa oculta new_inputs = list() # Inicializamos un contador de neuronas para la capa considerada neuron_idx = 1 # Para cada neurona de la capa que estamos considerando for neuron in layer: # Vamos a ver los pesos que tiene asociados la neurona print(f"Pesos de las entradas que recibe la neurona {neuron_idx} de la capa {layer_idx}: {neuron}") # Calculamos la salida en esta neurona: # a) Suma ponderada suma = weighted_sum(neuron["weights"], inputs) # b) Aplicación de la función de activación a la suma ponderada neuron["output"] = activation_function(suma) # Vamos a ver el resultado de las operaciones anteriores, que es la salida de la neurona print(f"Salida de la neurona {neuron_idx} de la capa {layer_idx}: {neuron['output']}") print("\n") # Almacenamos la salida de esta neurona, que será una de las entradas de la capa siguiente new_inputs.append(neuron["output"]) # Sumamos una unidad al contador de neuronas de esta capa neuron_idx += 1 # Las entrada de la capa siguiente serán las salidas de esta capa inputs = new_inputs return inputs ###Output _____no_output_____ ###Markdown Vamos a comprobar cómo funciona el pase hacia delante, haciendo uso de las funciones que hemos definido hasta ahora. ###Code # Fijamos la semilla para que los resultados random siempre sean los mismos seed(1) # Inicializamos la red, guardando la estructura generada en una variable network = init_network(2, 1, 2) # Mostramos la red generada, con pesos inicializados de forma aleatoria network # Nos inventamos una fila de datos, que serán las entradas de la red en la primera capa row = [1, 0] # Probamos cómo funciona el pase hacia delante en la red, introduciendo la fila de datos que nos hemos inventado output = forward_propagation(network, row) output ###Output Pesos de las neuronas de la capa 2: [{'weights': [0.13436424411240122, 0.8474337369372327, 0.763774618976614], 'output': 0.7105668883115941}] Pesos de las entradas que recibe la neurona 1 de la capa 2: {'weights': [0.13436424411240122, 0.8474337369372327, 0.763774618976614], 'output': 0.7105668883115941} Salida de la neurona 1 de la capa 2: 0.7105668883115941 Pesos de las neuronas de la capa 3: [{'weights': [0.2550690257394217, 0.49543508709194095], 'output': 0.6629970129852887}, {'weights': [0.4494910647887381, 0.651592972722763], 'output': 0.7253160725279748}] Pesos de las entradas que recibe la neurona 1 de la capa 3: {'weights': [0.2550690257394217, 0.49543508709194095], 'output': 0.6629970129852887} Salida de la neurona 1 de la capa 3: 0.6629970129852887 Pesos de las entradas que recibe la neurona 2 de la capa 3: {'weights': [0.4494910647887381, 0.651592972722763], 'output': 0.7253160725279748} Salida de la neurona 2 de la capa 3: 0.7253160725279748 ###Markdown Pase hacia atrásPara poder hacer el pase hacia atrás, necesitamos calcular el error entre la salida de la red (predicción) y el valor real. Una vez calculado el error en la salida, este se puede retropropagar hacia las capas anteriores, actualizando los pesos de la forma que sea necesaria para reducir el error en la siguiente iteración del entrenamiento de la red. Cálculo de la derivada de la función de activaciónRecordemos cómo era la función sigmoide:$$\sigma(x) = \frac{1}{1 + e^{-x}}$$La derivada de esta función será, por tanto:$${\sigma(x)}' = \frac{e^{-x}}{^{(1+e^{-x})^{2}}}$$Que también se puede expresar de la siguiente manera:$${\sigma(x)}' = \sigma(x)(1 - \sigma(x))$$ ###Code def activ_func_derivative(active_output): """ Cálculo de la pendiente, dado un valor de salida de una neurona. :param active_output: (float) El resultado de aplicar la función de activación a una suma ponderada en una neurona. """ derivative = active_output * (1.0 - active_output) return derivative ###Output _____no_output_____ ###Markdown Retropropagación de erroresLo primero que tenemos que hacer para poder retropropagar los errores es calcular el error para cada neurona de salida. Para ello, en primer lugar, recordemos el funcionamiento de la propagación hacia delante: ![Neural_network_d.png](attachment:Neural_network_d.png) Dado que el aprendizaje es de tipo supervisado, podemos calcular el error para una neurona *n* de la capa de salida de la siguiente manera:`error_n = (expected_value - neuron_output) * activ_func_derivative(neuron_output)` En la capa oculta, la señal de error de calcula de forma un poco distinta. En este caso, la señal de error de cada neurona es el error ponderado de cada neurona en la capa de salida.Para entenderlo mejor, es útil imaginar que el error viaja de vuelta desde la capa de salida hasta la capa oculta, recorriendo los pesos que las unen. La señal de error retropropagada se acumula y se utiliza para calcular el error de una neurona *n* en la capa oculta:`error_n = (weight_k * error_j) * activ_func_derivative(output_n)`Donde:- *error_j* es la señal de error de la j-ésima neurona en la capa de salida- *weight_k* es el peso que conecta la k-ésima neurona a la neurona actual- *output_n* es la salida de la neurona actualLa señal de error calculada para cada neurona se almacena con el nombre *delta* para reflejar el cambio que implica el error en la neurona. ###Code def backpropagation_error(network, expected_values): """ Pase hacia atrás en una red neuronal. :param network: (list) Lista con la estructura de una red inicializada. :param expected: (list) Lista de etiquetas (valores esperados para una fila de datos). """ # Se empieza a trabajar desde la última capa de la red hasta la primera # Para cada capa de la red, empezando por la de salida: for i in reversed(range(len(network))): # Tomamos la capa layer = network[i] # Inicializamos los errores de esa capa layer_errors = list() # Si no estamos en la capa de salida if i != len(network) - 1: # Para cada neurona de la capa for j in range(len(layer)): # Inicializamos el error de la neurona neuron_error = 0.0 # Para cada neurona de la siguiente capa for neuron in network[i +1]: # Se le suma a la neurona en estudio una señal de error distinta # Señal de error = peso j de la neurona * delta de la neurona neuron_error += (neuron["weights"][j] * neuron["delta"]) # Se almacena la señal de error de la neurona en los errores de esta capa layer_errors.append(neuron_error) # Si estamos en la capa de salida else: # Para cada neurona en la capa de salida for j in range(len(layer)): # Tomamos la neurona neuron = layer[j] # Almacenamos el error # El error de calcula como la diferencia entre el valor predicho # y el valor esperado para la neurona en cuestión layer_errors.append(expected_values[j] - neuron["output"]) # Para cada neurona de la capa en la que estemos: for j in range(len(layer)): # Tomamos la neurona neuron = layer[j] # Se almacena la señal de error (delta) de la neurona # El delta de la neurona se calcula como el error de la neurona # por la derivada de la f.activ aplicada sobre la salida de dicha neurona. neuron["delta"] = layer_errors[j] * activ_func_derivative(neuron["output"]) ###Output _____no_output_____ ###Markdown Vamos a comprobar cómo funciona el pase hacia atrás: ###Code # Ya habíamos inicializado la red network # Nos inventamos unos valores esperados expected_values = [0,1] # Ejecutamos la retropropagación backpropagation_error(network, expected_values) # Comprobamos cómo se han generado las señales de error (deltas) for layer in network: print(layer) ###Output [{'weights': [0.13436424411240122, 0.8474337369372327, 0.763774618976614], 'output': 0.7105668883115941, 'delta': -0.002711797799238243}] [{'weights': [0.2550690257394217, 0.49543508709194095], 'output': 0.6629970129852887, 'delta': -0.14813473120687762}, {'weights': [0.4494910647887381, 0.651592972722763], 'output': 0.7253160725279748, 'delta': 0.05472601157879688}] ###Markdown Entrenamiento de la redPara entrenar la red, se utiliza el algoritmo de descenso de gradiente estocástico.En cada iteración de entrenamiento:- Se introduce una fila del dataset en la red.- Se hace un pase hacia delante.- Se hace un pase hacia atrás.- Se actualizan los pesos y biases de la red. Actualización de pesosUna vez calculados los errores de cada neurona mediante la función de retropropagación definida anteriormente, se pueden utilizar para actualizar los pesos de la siguiente manera:`weight = weight + learning_rate * error * input` ###Code def update_weights(network, row, l_rate): """ Actualización de pesos de una red tras haber hecho un pase hacia delante y otro hacia atrás. :param network: (list) Lista con la estructura de una red inicializada. :param row: (list) Lista de valores de entrada. :param l_rate: (float) Tasa de aprendizaje (learning_rate). """ # Para cada capa de la red for i in range(len(network)): # Se toman todos los valores de entradas menos el último inputs = row[:-1] # Si no estamos en la capa de entrada if i != 0: # Las entradas son las salidas de la capa anterior inputs = [neuron['output'] for neuron in network[i - 1]] # Para cada neurona de la capa en la que estamos for neuron in network[i]: # Para cada entrada for j in range(len(inputs)): # Se aplica la regla de actualización a los pesos de la neurona neuron['weights'][j] += l_rate * neuron['delta'] * inputs[j] # Se aplica la regla de actualización al bias neuron['weights'][-1] += l_rate * neuron['delta'] ###Output _____no_output_____ ###Markdown Entrenamiento iterativoPara entrenar la red, como ya se ha comentado, se utiliza el algoritmo de descenso de gradiente estocástico.Para ello:- Se define un número máximo de *epochs*. - En capa epoch, se actualizan los parámetros de la red. ###Code # Train a network for a fixed number of epochs def train(network, train_data, l_rate, n_epoch, n_outputs): """ Entrenamiento de una red, dado un número fijo de epochs. :param network: (list) Lista con la estructura de una red inicializada. :param train_data: (list) Lista de valores de entrada. :param l_rate: (float) Tasa de aprendizaje (learning_rate). :param n_epoch: (int) Número de epochs. :param n_outputs: (int) Número esperado de valores de salida. """ # Para cada epoch for epoch in range(n_epoch): # Se inicializa el error sum_error = 0 # Para cada fila de datos for row in train_data: # Se hace un pase hacia delante outputs = forward_propagation(network, row) # Se toman los valores esperados de salida expected = [0 for i in range(n_outputs)] expected[row[-1]] = 1 # Se almacena el error de evaluación de la red # Para ello, se toma la suma de residuos al cuadrado sum_error += sum([(expected[i]-outputs[i])**2 for i in range(len(expected))]) # Se hace un pase hacia atrás backpropagation_error(network, expected) # Se actualizan los pesos update_weights(network, row, l_rate) # Se imprime el error para esta epoch print(f"epoch = {epoch}, error = {sum_error}") ###Output _____no_output_____ ###Markdown PrediccionesUna vez entrenada la red, se pueden hacer predicciones de forma muy sencilla, simplemente haciendo un pase hacia delante.Los valores de salida se pueden interpretar como la probabilidad de pertenencia a una clase. Sin embargo, es útil convertirlos directamente en una clase, para lo cual se puede seleccionar el valor de clase que tiene mayor probabilidad. ###Code def predict(network, row): """ Generación de predicciones con una red entrenada. :param network: (list) Lista con la estructura de una red inicializada. :param row: (list) Fila de datos de entrada. """ outputs = forward_propagation(network, row) # Se asume que los valores de clase se han transformado en números enteros # comenzando en 0, así que se devuelve el índice de la salida de la red # con mayor probabilidad return outputs.index(max(outputs)) ###Output _____no_output_____ ###Markdown Caso de estudio Para probar el entrenamiento de la red y la generación de predicciones, tomamos los siguientes datos, considerando que la última columna corresponde a las etiquetas: ###Code seed(1) dataset = [[2.7810836,2.550537003,0], [1.465489372,2.362125076,0], [3.396561688,4.400293529,0], [1.38807019,1.850220317,0], [3.06407232,3.005305973,0], [7.627531214,2.759262235,1], [5.332441248,2.088626775,1], [6.922596716,1.77106367,1], [8.675418651,-0.242068655,1], [7.673756466,3.508563011,1]] n_inputs = len(dataset[0]) - 1 n_outputs = len(set([row[-1] for row in dataset])) network = init_network(n_inputs, 2, n_outputs) train(network, dataset, 0.5, 20, n_outputs) for layer in network: print(layer) for row in dataset: prediction = predict(network, row) print('Expected=%d, Got=%d' % (row[-1], prediction)) ###Output Pesos de las neuronas de la capa 2: [{'weights': [-1.4688375095432327, 1.850887325439514, 1.0858178629550297], 'output': 0.029980305604426185, 'delta': -0.0059546604162323625}, {'weights': [0.37711098142462157, -0.0625909894552989, 0.2765123702642716], 'output': 0.9456229000211323, 'delta': 0.0026279652850863837}] Pesos de las entradas que recibe la neurona 1 de la capa 2: {'weights': [-1.4688375095432327, 1.850887325439514, 1.0858178629550297], 'output': 0.029980305604426185, 'delta': -0.0059546604162323625} Salida de la neurona 1 de la capa 2: 0.848336685767009 Pesos de las entradas que recibe la neurona 2 de la capa 2: {'weights': [0.37711098142462157, -0.0625909894552989, 0.2765123702642716], 'output': 0.9456229000211323, 'delta': 0.0026279652850863837} Salida de la neurona 2 de la capa 2: 0.762357633919813 Pesos de las neuronas de la capa 3: [{'weights': [2.515394649397849, -0.3391927502445985, -0.9671565426390275], 'output': 0.23648794202357587, 'delta': -0.04270059278364587}, {'weights': [-2.5584149848484263, 1.0036422106209202, 0.42383086467582715], 'output': 0.7790535202438367, 'delta': 0.03803132596437354}] Pesos de las entradas que recibe la neurona 1 de la capa 3: {'weights': [2.515394649397849, -0.3391927502445985, -0.9671565426390275], 'output': 0.23648794202357587, 'delta': -0.04270059278364587} Salida de la neurona 1 de la capa 3: 0.7126232557623697 Pesos de las entradas que recibe la neurona 2 de la capa 3: {'weights': [-2.5584149848484263, 1.0036422106209202, 0.42383086467582715], 'output': 0.7790535202438367, 'delta': 0.03803132596437354} Salida de la neurona 2 de la capa 3: 0.27260771151578705 Expected=0, Got=0 Pesos de las neuronas de la capa 2: [{'weights': [-1.4688375095432327, 1.850887325439514, 1.0858178629550297], 'output': 0.848336685767009, 'delta': -0.0059546604162323625}, {'weights': [0.37711098142462157, -0.0625909894552989, 0.2765123702642716], 'output': 0.762357633919813, 'delta': 0.0026279652850863837}] Pesos de las entradas que recibe la neurona 1 de la capa 2: {'weights': [-1.4688375095432327, 1.850887325439514, 1.0858178629550297], 'output': 0.848336685767009, 'delta': -0.0059546604162323625} Salida de la neurona 1 de la capa 2: 0.9646094840954318 Pesos de las entradas que recibe la neurona 2 de la capa 2: {'weights': [0.37711098142462157, -0.0625909894552989, 0.2765123702642716], 'output': 0.762357633919813, 'delta': 0.0026279652850863837} Salida de la neurona 2 de la capa 2: 0.6640325211749527 Pesos de las neuronas de la capa 3: [{'weights': [2.515394649397849, -0.3391927502445985, -0.9671565426390275], 'output': 0.7126232557623697, 'delta': -0.04270059278364587}, {'weights': [-2.5584149848484263, 1.0036422106209202, 0.42383086467582715], 'output': 0.27260771151578705, 'delta': 0.03803132596437354}] Pesos de las entradas que recibe la neurona 1 de la capa 3: {'weights': [2.515394649397849, -0.3391927502445985, -0.9671565426390275], 'output': 0.7126232557623697, 'delta': -0.04270059278364587} Salida de la neurona 1 de la capa 3: 0.7745147530889296 Pesos de las entradas que recibe la neurona 2 de la capa 3: {'weights': [-2.5584149848484263, 1.0036422106209202, 0.42383086467582715], 'output': 0.27260771151578705, 'delta': 0.03803132596437354} Salida de la neurona 2 de la capa 3: 0.2013964274666392 Expected=0, Got=0 Pesos de las neuronas de la capa 2: [{'weights': [-1.4688375095432327, 1.850887325439514, 1.0858178629550297], 'output': 0.9646094840954318, 'delta': -0.0059546604162323625}, {'weights': [0.37711098142462157, -0.0625909894552989, 0.2765123702642716], 'output': 0.6640325211749527, 'delta': 0.0026279652850863837}] Pesos de las entradas que recibe la neurona 1 de la capa 2: {'weights': [-1.4688375095432327, 1.850887325439514, 1.0858178629550297], 'output': 0.9646094840954318, 'delta': -0.0059546604162323625} Salida de la neurona 1 de la capa 2: 0.9858147836862672 Pesos de las entradas que recibe la neurona 2 de la capa 2: {'weights': [0.37711098142462157, -0.0625909894552989, 0.2765123702642716], 'output': 0.6640325211749527, 'delta': 0.0026279652850863837} Salida de la neurona 2 de la capa 2: 0.7827856680769559 Pesos de las neuronas de la capa 3: [{'weights': [2.515394649397849, -0.3391927502445985, -0.9671565426390275], 'output': 0.7745147530889296, 'delta': -0.04270059278364587}, {'weights': [-2.5584149848484263, 1.0036422106209202, 0.42383086467582715], 'output': 0.2013964274666392, 'delta': 0.03803132596437354}] Pesos de las entradas que recibe la neurona 1 de la capa 3: {'weights': [2.515394649397849, -0.3391927502445985, -0.9671565426390275], 'output': 0.7745147530889296, 'delta': -0.04270059278364587} Salida de la neurona 1 de la capa 3: 0.7767873046375927 Pesos de las entradas que recibe la neurona 2 de la capa 3: {'weights': [-2.5584149848484263, 1.0036422106209202, 0.42383086467582715], 'output': 0.2013964274666392, 'delta': 0.03803132596437354} Salida de la neurona 2 de la capa 3: 0.21204278675598506 Expected=0, Got=0 Pesos de las neuronas de la capa 2: [{'weights': [-1.4688375095432327, 1.850887325439514, 1.0858178629550297], 'output': 0.9858147836862672, 'delta': -0.0059546604162323625}, {'weights': [0.37711098142462157, -0.0625909894552989, 0.2765123702642716], 'output': 0.7827856680769559, 'delta': 0.0026279652850863837}] Pesos de las entradas que recibe la neurona 1 de la capa 2: {'weights': [-1.4688375095432327, 1.850887325439514, 1.0858178629550297], 'output': 0.9858147836862672, 'delta': -0.0059546604162323625} Salida de la neurona 1 de la capa 2: 0.9221208222444449 Pesos de las entradas que recibe la neurona 2 de la capa 2: {'weights': [0.37711098142462157, -0.0625909894552989, 0.2765123702642716], 'output': 0.7827856680769559, 'delta': 0.0026279652850863837} Salida de la neurona 2 de la capa 2: 0.6646669255893195 Pesos de las neuronas de la capa 3: [{'weights': [2.515394649397849, -0.3391927502445985, -0.9671565426390275], 'output': 0.7767873046375927, 'delta': -0.04270059278364587}, {'weights': [-2.5584149848484263, 1.0036422106209202, 0.42383086467582715], 'output': 0.21204278675598506, 'delta': 0.03803132596437354}] Pesos de las entradas que recibe la neurona 1 de la capa 3: {'weights': [2.515394649397849, -0.3391927502445985, -0.9671565426390275], 'output': 0.7767873046375927, 'delta': -0.04270059278364587} Salida de la neurona 1 de la capa 3: 0.7552646947754036 Pesos de las entradas que recibe la neurona 2 de la capa 3: {'weights': [-2.5584149848484263, 1.0036422106209202, 0.42383086467582715], 'output': 0.21204278675598506, 'delta': 0.03803132596437354} Salida de la neurona 2 de la capa 3: 0.21955712765918486 Expected=0, Got=0 Pesos de las neuronas de la capa 2: [{'weights': [-1.4688375095432327, 1.850887325439514, 1.0858178629550297], 'output': 0.9221208222444449, 'delta': -0.0059546604162323625}, {'weights': [0.37711098142462157, -0.0625909894552989, 0.2765123702642716], 'output': 0.6646669255893195, 'delta': 0.0026279652850863837}] Pesos de las entradas que recibe la neurona 1 de la capa 2: {'weights': [-1.4688375095432327, 1.850887325439514, 1.0858178629550297], 'output': 0.9221208222444449, 'delta': -0.0059546604162323625} Salida de la neurona 1 de la capa 2: 0.8954514307321184 Pesos de las entradas que recibe la neurona 2 de la capa 2: {'weights': [0.37711098142462157, -0.0625909894552989, 0.2765123702642716], 'output': 0.6646669255893195, 'delta': 0.0026279652850863837} Salida de la neurona 2 de la capa 2: 0.7762425903762347 Pesos de las neuronas de la capa 3: [{'weights': [2.515394649397849, -0.3391927502445985, -0.9671565426390275], 'output': 0.7552646947754036, 'delta': -0.04270059278364587}, {'weights': [-2.5584149848484263, 1.0036422106209202, 0.42383086467582715], 'output': 0.21955712765918486, 'delta': 0.03803132596437354}] Pesos de las entradas que recibe la neurona 1 de la capa 3: {'weights': [2.515394649397849, -0.3391927502445985, -0.9671565426390275], 'output': 0.7552646947754036, 'delta': -0.04270059278364587} Salida de la neurona 1 de la capa 3: 0.7353544678197247 Pesos de las entradas que recibe la neurona 2 de la capa 3: {'weights': [-2.5584149848484263, 1.0036422106209202, 0.42383086467582715], 'output': 0.21955712765918486, 'delta': 0.03803132596437354} Salida de la neurona 2 de la capa 3: 0.25198835601388997 Expected=0, Got=0 Pesos de las neuronas de la capa 2: [{'weights': [-1.4688375095432327, 1.850887325439514, 1.0858178629550297], 'output': 0.8954514307321184, 'delta': -0.0059546604162323625}, {'weights': [0.37711098142462157, -0.0625909894552989, 0.2765123702642716], 'output': 0.7762425903762347, 'delta': 0.0026279652850863837}] Pesos de las entradas que recibe la neurona 1 de la capa 2: {'weights': [-1.4688375095432327, 1.850887325439514, 1.0858178629550297], 'output': 0.8954514307321184, 'delta': -0.0059546604162323625} Salida de la neurona 1 de la capa 2: 0.006622073847261473 Pesos de las entradas que recibe la neurona 2 de la capa 2: {'weights': [0.37711098142462157, -0.0625909894552989, 0.2765123702642716], 'output': 0.7762425903762347, 'delta': 0.0026279652850863837} Salida de la neurona 2 de la capa 2: 0.9516730975506533 Pesos de las neuronas de la capa 3: [{'weights': [2.515394649397849, -0.3391927502445985, -0.9671565426390275], 'output': 0.7353544678197247, 'delta': -0.04270059278364587}, {'weights': [-2.5584149848484263, 1.0036422106209202, 0.42383086467582715], 'output': 0.25198835601388997, 'delta': 0.03803132596437354}] Pesos de las entradas que recibe la neurona 1 de la capa 3: {'weights': [2.515394649397849, -0.3391927502445985, -0.9671565426390275], 'output': 0.7353544678197247, 'delta': -0.04270059278364587} Salida de la neurona 1 de la capa 3: 0.21869286496893786 Pesos de las entradas que recibe la neurona 2 de la capa 3: {'weights': [-2.5584149848484263, 1.0036422106209202, 0.42383086467582715], 'output': 0.25198835601388997, 'delta': 0.03803132596437354} Salida de la neurona 2 de la capa 3: 0.7960891263956652 Expected=1, Got=1 Pesos de las neuronas de la capa 2: [{'weights': [-1.4688375095432327, 1.850887325439514, 1.0858178629550297], 'output': 0.006622073847261473, 'delta': -0.0059546604162323625}, {'weights': [0.37711098142462157, -0.0625909894552989, 0.2765123702642716], 'output': 0.9516730975506533, 'delta': 0.0026279652850863837}] Pesos de las entradas que recibe la neurona 1 de la capa 2: {'weights': [-1.4688375095432327, 1.850887325439514, 1.0858178629550297], 'output': 0.006622073847261473, 'delta': -0.0059546604162323625} Salida de la neurona 1 de la capa 2: 0.05310792115806771 Pesos de las entradas que recibe la neurona 2 de la capa 2: {'weights': [0.37711098142462157, -0.0625909894552989, 0.2765123702642716], 'output': 0.9516730975506533, 'delta': 0.0026279652850863837} Salida de la neurona 2 de la capa 2: 0.8962937020778735 Pesos de las neuronas de la capa 3: [{'weights': [2.515394649397849, -0.3391927502445985, -0.9671565426390275], 'output': 0.21869286496893786, 'delta': -0.04270059278364587}, {'weights': [-2.5584149848484263, 1.0036422106209202, 0.42383086467582715], 'output': 0.7960891263956652, 'delta': 0.03803132596437354}] Pesos de las entradas que recibe la neurona 1 de la capa 3: {'weights': [2.515394649397849, -0.3391927502445985, -0.9671565426390275], 'output': 0.21869286496893786, 'delta': -0.04270059278364587} Salida de la neurona 1 de la capa 3: 0.24276394412011773 Pesos de las entradas que recibe la neurona 2 de la capa 3: {'weights': [-2.5584149848484263, 1.0036422106209202, 0.42383086467582715], 'output': 0.7960891263956652, 'delta': 0.03803132596437354} Salida de la neurona 2 de la capa 3: 0.7662966796635028 Expected=1, Got=1 Pesos de las neuronas de la capa 2: [{'weights': [-1.4688375095432327, 1.850887325439514, 1.0858178629550297], 'output': 0.05310792115806771, 'delta': -0.0059546604162323625}, {'weights': [0.37711098142462157, -0.0625909894552989, 0.2765123702642716], 'output': 0.8962937020778735, 'delta': 0.0026279652850863837}] Pesos de las entradas que recibe la neurona 1 de la capa 2: {'weights': [-1.4688375095432327, 1.850887325439514, 1.0858178629550297], 'output': 0.05310792115806771, 'delta': -0.0059546604162323625} Salida de la neurona 1 de la capa 2: 0.0030054662968349863 Pesos de las entradas que recibe la neurona 2 de la capa 2: {'weights': [0.37711098142462157, -0.0625909894552989, 0.2765123702642716], 'output': 0.8962937020778735, 'delta': 0.0026279652850863837} Salida de la neurona 2 de la capa 2: 0.9413786775553202 Pesos de las neuronas de la capa 3: [{'weights': [2.515394649397849, -0.3391927502445985, -0.9671565426390275], 'output': 0.24276394412011773, 'delta': -0.04270059278364587}, {'weights': [-2.5584149848484263, 1.0036422106209202, 0.42383086467582715], 'output': 0.7662966796635028, 'delta': 0.03803132596437354}] Pesos de las entradas que recibe la neurona 1 de la capa 3: {'weights': [2.515394649397849, -0.3391927502445985, -0.9671565426390275], 'output': 0.24276394412011773, 'delta': -0.04270059278364587} Salida de la neurona 1 de la capa 3: 0.21773660096058492 Pesos de las entradas que recibe la neurona 2 de la capa 3: {'weights': [-2.5584149848484263, 1.0036422106209202, 0.42383086467582715], 'output': 0.7662966796635028, 'delta': 0.03803132596437354} Salida de la neurona 2 de la capa 3: 0.7959138936812228 Expected=1, Got=1 Pesos de las neuronas de la capa 2: [{'weights': [-1.4688375095432327, 1.850887325439514, 1.0858178629550297], 'output': 0.0030054662968349863, 'delta': -0.0059546604162323625}, {'weights': [0.37711098142462157, -0.0625909894552989, 0.2765123702642716], 'output': 0.9413786775553202, 'delta': 0.0026279652850863837}] Pesos de las entradas que recibe la neurona 1 de la capa 2: {'weights': [-1.4688375095432327, 1.850887325439514, 1.0858178629550297], 'output': 0.0030054662968349863, 'delta': -0.0059546604162323625} Salida de la neurona 1 de la capa 2: 5.531730843576379e-06 Pesos de las entradas que recibe la neurona 2 de la capa 2: {'weights': [0.37711098142462157, -0.0625909894552989, 0.2765123702642716], 'output': 0.9413786775553202, 'delta': 0.0026279652850863837} Salida de la neurona 2 de la capa 2: 0.9724350789538234 Pesos de las neuronas de la capa 3: [{'weights': [2.515394649397849, -0.3391927502445985, -0.9671565426390275], 'output': 0.21773660096058492, 'delta': -0.04270059278364587}, {'weights': [-2.5584149848484263, 1.0036422106209202, 0.42383086467582715], 'output': 0.7959138936812228, 'delta': 0.03803132596437354}] Pesos de las entradas que recibe la neurona 1 de la capa 3: {'weights': [2.515394649397849, -0.3391927502445985, -0.9671565426390275], 'output': 0.21773660096058492, 'delta': -0.04270059278364587} Salida de la neurona 1 de la capa 3: 0.21467277989608474 Pesos de las entradas que recibe la neurona 2 de la capa 3: {'weights': [-2.5584149848484263, 1.0036422106209202, 0.42383086467582715], 'output': 0.7959138936812228, 'delta': 0.03803132596437354} Salida de la neurona 2 de la capa 3: 0.802151134673332 Expected=1, Got=1 Pesos de las neuronas de la capa 2: [{'weights': [-1.4688375095432327, 1.850887325439514, 1.0858178629550297], 'output': 5.531730843576379e-06, 'delta': -0.0059546604162323625}, {'weights': [0.37711098142462157, -0.0625909894552989, 0.2765123702642716], 'output': 0.9724350789538234, 'delta': 0.0026279652850863837}] Pesos de las entradas que recibe la neurona 1 de la capa 2: {'weights': [-1.4688375095432327, 1.850887325439514, 1.0858178629550297], 'output': 5.531730843576379e-06, 'delta': -0.0059546604162323625} Salida de la neurona 1 de la capa 2: 0.024322537679354106 Pesos de las entradas que recibe la neurona 2 de la capa 2: {'weights': [0.37711098142462157, -0.0625909894552989, 0.2765123702642716], 'output': 0.9724350789538234, 'delta': 0.0026279652850863837} Salida de la neurona 2 de la capa 2: 0.9502996684842616 Pesos de las neuronas de la capa 3: [{'weights': [2.515394649397849, -0.3391927502445985, -0.9671565426390275], 'output': 0.21467277989608474, 'delta': -0.04270059278364587}, {'weights': [-2.5584149848484263, 1.0036422106209202, 0.42383086467582715], 'output': 0.802151134673332, 'delta': 0.03803132596437354}] Pesos de las entradas que recibe la neurona 1 de la capa 3: {'weights': [2.515394649397849, -0.3391927502445985, -0.9671565426390275], 'output': 0.21467277989608474, 'delta': -0.04270059278364587} Salida de la neurona 1 de la capa 3: 0.22647726109932073 Pesos de las entradas que recibe la neurona 2 de la capa 3: {'weights': [-2.5584149848484263, 1.0036422106209202, 0.42383086467582715], 'output': 0.802151134673332, 'delta': 0.03803132596437354} Salida de la neurona 2 de la capa 3: 0.7884094596056147 Expected=1, Got=1
Humble_Bumble_Data_Analyst_Challenge.ipynb
###Markdown ![Humble Bumble Hero](./images/bumble.gif) Humble Bumble Data Analyst Interview Challenge 🐝🍯 Bumble   Data Analyst Interview Challenge using Python, Pandas, and Matplotlib 🐝🍯![Bumble Question 1](./images/bumble_Q1.gif) Question 1: Please complete the below shell function so that, given a string s, it will count the number of unique words, which is case insensitive and ignores punctuation. * The answer should be printed, and should be printed in alphabeticalorder. * No libraries outside of the python standard libraries can be used (ie, no pandas, no sklearn, no nltk etc). Example: "I'm smart, I'm educated. It would have been a disservice to every woman to go away or hide." - Whitney Wolfe Founder of Bumble ------```Input: "I'm smart I'm educated. It would have been a disservice to every woman to go away or hide." Ouput: [ ('a', 1), ('away', 1), ('been', 1), ('disservice', 1), ('educated', 1), ('every', 1), ('go', 1), ('have', 1), ('hide', 1), ("i'm", 2), ('it', 1), ('or', 1), ('smart', 1), ('to', 2), ('woman', 1), ('would', 1)]```----- ###Code punctuations=[',', '.', '!', '"', '?'] def word_count(s): sentence = s.lower() for punctuation in punctuations: words = sentence.replace(punctuation, '') word_list = words.split() word_dict = {word : word_list.count(word) for word in word_list} return sorted(word_dict.items()) word_count("I'm smart I'm educated. It would have been a disservice to every woman to go away or hide.") ###Output _____no_output_____ ###Markdown ![Bumble Question 2](./images/bumble_Q2.gif) Question 2: Using the given pandas dataframe, please calculate the ratio of messages sent to messages received (messages_sent / messages_received) split by country and gender, and visualise this in a way that is easy to digest andunderstand. Please use any libraries you wish. ###Code import pandas as pd import numpy as np import matplotlib.pyplot as plt #creating dataframe messages_df = pd.DataFrame({'gender': ['M','F','M','M','F','M','F','M', 'F','F','M','F','F'],'country':['UK','UK','UK','UK','FR','FR','FR','UK','FR','UK','BR','BR','BR'], 'messages_sent':[10,12,1,4,5,92,23,14,None,18,12,6,9], 'messages_received':[54,12,32,12,53,11,0,0,54,None,13,4,14]}) print(messages_df) ###Output gender country messages_sent messages_received 0 M UK 10.0 54.0 1 F UK 12.0 12.0 2 M UK 1.0 32.0 3 M UK 4.0 12.0 4 F FR 5.0 53.0 5 M FR 92.0 11.0 6 F FR 23.0 0.0 7 M UK 14.0 0.0 8 F FR NaN 54.0 9 F UK 18.0 NaN 10 M BR 12.0 13.0 11 F BR 6.0 4.0 12 F BR 9.0 14.0 ###Markdown ![Bumble DF](./images/bumble_df.gif) Step 1. Cleaning the NaNs with Zeros![Cleaning NaNs with Zeros](./Images/cleaning_NaN.gif) ###Code # filling NaNs with zeros messages_df = messages_df.fillna(0) messages_df ###Output _____no_output_____ ###Markdown Step 2. Creating grouped table for Messaged Received ###Code # Creating grouped table for Messaged Received total_messages_received_df = messages_df.groupby(['country', 'gender']).\ messages_received.\ sum().\ to_frame().\ reset_index().\ rename(columns = {'': 'messages_received'}) total_messages_received_df ###Output _____no_output_____ ###Markdown Step 3. Creating Grouped Table for Messaged Sent ###Code # Creating Grouped Table for Messaged Sent total_messages_sent_df = messages_df.groupby(['country', 'gender']).\ messages_sent.\ sum().\ to_frame().\ reset_index().\ rename(columns = {'': 'messages_sent'}) total_messages_sent_df ###Output _____no_output_____ ###Markdown Step 4. Merging the two tables ###Code # Merging the two tables bumble_df = pd.merge(total_messages_received_df, total_messages_sent_df, how = 'outer', \ left_on = ['country', 'gender'], right_on=['country', 'gender']) bumble_df ###Output _____no_output_____ ###Markdown Step 5. Calculating Message Ratio ###Code # Calculating the Messaged Ratio bumble_df['messages_ratio'] = (bumble_df['messages_sent'] / bumble_df['messages_received']) * 100 bumble_df ###Output _____no_output_____ ###Markdown Step 6. Analysis* French males have the highest send/receive ratio with 92 messages sent and only 11 received back.* French females and UK males seem very popular with ratios of 26% and 30% respectively* Both have received a lot more messages than they have sent. Step 7. Plotting a Chart using Matplotlib ###Code # Plotting the data on a chart c=3 # Converting Ration to percent female_ratio = list(bumble_df[bumble_df["gender"] == "F"].messages_ratio) male_ratio = list(bumble_df[bumble_df["gender"] == "M"].messages_ratio) country = np.arange(c) width = 0.4 #width of bars fig = plt.figure(figsize = (8, 8)) ax = fig.add_subplot() bar_1 = ax.bar(country, female_ratio, width, color = 'gold', label = 'Female') bar_2 = ax.bar(country + width, male_ratio, width, color = '#F9B007', label = 'Male') ax.set_ylabel('Percent') ax.set_xticks(country + width / 2) ax.set_xticklabels(['BR', 'FR', 'UK']) ax.legend((bar_1, bar_2), ('Female', 'Male'), loc = 'upper right') ax.set_title('Bumble Ratio of messages received by country and gender') import plotly.express as px fig = px.bar(bumble_df, x="country", y="messages_ratio", color_discrete_map = {"F":'gold',"M":'#F9B007'}, barmode ="group", color="gender", title="Bumble Ratio of messages received by country and gender") fig.show() ###Output _____no_output_____
[3]_Regression Models/XGBoost_regression_with_hyperparameter_tuning_by_GPyOpt.ipynb
###Markdown XGBoost regression with hyperparameter tuning by GPyOptReference : http://krasserm.github.io/2018/03/21/bayesian-optimization/ https://xgboost.readthedocs.io/en/latest/parameter.html Import library and dataset ###Code %matplotlib inline %pylab inline import sys import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns # XGBoost import xgboost as xgb # Cross validation from sklearn.model_selection import (KFold, ShuffleSplit) from sklearn.metrics import mean_squared_error, r2_score #GPy import GPy, GPyOpt from GPyOpt.methods import BayesianOptimization # load dataset df = pd.read_csv('glass.csv') print(df.shape) df.head() df_test = df.drop(df.columns[[0, 10]], axis=1) print(df_test.shape) df_test.head() X = df_test.iloc[:, 1:] y = df_test.iloc[:, :1] print(X.shape) X.head() print(y.shape) 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 = 0) print(X_train.shape, X_test.shape, y_train.shape, y_test.shape) ###Output (171, 8) (43, 8) (171, 1) (43, 1) ###Markdown Default ###Code xgr = xgb.XGBRegressor() xgr.fit(X_train, y_train) pred_xgr = xgr.predict(X_test) R2_xgr = r2_score(pred_xgr, y_test) print('R2 = ', R2_xgr) ###Output R2 = 0.5115816779953148 ###Markdown Hyperparameter tuning using GPyOpt ###Code # GPyOpt for XGBoost regression bounds_xgr = [ {'name': 'learning_rate', 'type': 'continuous', 'domain': (0, 1)}, {'name': 'gamma', 'type': 'continuous', 'domain': (0, 5)}, {'name': 'max_depth', 'type': 'discrete', 'domain': (1, 50)}, {'name': 'n_estimators', 'type': 'discrete', 'domain': (1, 300)}, {'name': 'min_child_weight', 'type': 'discrete', 'domain': (1, 10)} ] # Optimization objective function def rmse_xgr(*args): params = args[0] xgr = xgb.XGBRegressor(learning_rate = params[0][0], gamma = int(params[0][1]), max_depth = int(params[0][2]), n_estimators = int(params[0][3]), min_child_weight = params[0][4], bootstrap = True, random_state = 0, silent = True) xgr.fit(X_train, y_train) pred_xgr = xgr.predict(X_test) RMSE = np.sqrt(mean_squared_error(pred_xgr, y_test)) return RMSE %%time optimizer = BayesianOptimization(f = rmse_xgr, domain = bounds_xgr) optimizer.run_optimization(max_iter = 50) optimizer.x_opt xgr_best = xgb.XGBRegressor(learning_rate = optimizer.x_opt[0], gamma = int(optimizer.x_opt[1]), max_depth = int(optimizer.x_opt[2]), n_estimators = int(optimizer.x_opt[3]), min_child_weight = optimizer.x_opt[4], bootstrap = True, random_state = 0, silent = True) xgr_best.fit(X_train, y_train) y_pred_xgr = xgr_best.predict(X_test) print('R2 = ', '{:.4}'.format(r2_score(y_pred_xgr, y_test))) optimizer.plot_convergence() ###Output _____no_output_____ ###Markdown Check model performance by CV ###Code # Use all data X_train, y_train = X, y xgr_best = xgb.XGBRegressor(learning_rate = optimizer.x_opt[0], gamma = int(optimizer.x_opt[1]), max_depth = int(optimizer.x_opt[2]), n_estimators = int(optimizer.x_opt[3]), min_child_weight = optimizer.x_opt[4], bootstrap = True, random_state = 0, silent = True) xgr_best.fit(X_train, y_train) y_pred = xgr_best.predict(X_train) print('R2 = ', ' {:.4}'.format(r2_score(y, y_pred))) plt.figure(figsize = [4, 4]) slp_1_begin = 0.99 * y.min() slp_1_end = 1.01 * y.max() plt.scatter(y, y_pred, c = 'r', alpha = 0.5) plt.plot([slp_1_begin, slp_1_end], [slp_1_begin, slp_1_end], c = 'b') plt.title('Fitting check') plt.xlabel('Observed value') plt.ylabel('Predicted value') plt.show() from sklearn.model_selection import cross_val_score from sklearn.model_selection import cross_validate from sklearn.model_selection import (KFold, ShuffleSplit) split_num = 5 cv_KF = KFold(n_splits = split_num, shuffle = True, random_state = 0) print('Check best model perfromance in the folds') for train_index, test_index in cv_KF.split(X): X_train, X_test, y_train, y_test = X.loc[train_index], X.loc[test_index], y.loc[train_index], y.loc[test_index] y_pred = xgr_best.predict(X_test) R2_reg = r2_score(y_test, y_pred) print(' {:.4}'.format(R2_reg)) ###Output Check best model perfromance in the folds 0.9674 0.9271 0.802 0.8999 0.9319
.ipynb_checkpoints/Inventory-checkpoint.ipynb
###Markdown Welcome to Sales Reportauthor: Jack Lau last edit: 05/11/19 purpose: this report is use to show the sales info for the intopia ###Code import pandas as pd from intopia_analysis import * df_contact = pd.read_csv('Intopia - Contact List - Sheet1.csv') df_sales = get_sales_data('phase2/period7/') df_production = get_production_data('phase2/period7/') df_inventory = get_inventory_data('phase2/period7/') df_production df_supply = pd.merge(df_inventory, df_production, on=['Company', 'Grade', 'region', 'type'], how='outer') df_supply = df_supply[['Company', 'type', 'Grade', 'region', 'Units', 'Unit Production']] df_supply = df_supply.rename(columns={'Units':"inventory", 'Unit Production':"production"}) df_supply[df_supply['Company'] == 25] ###Output _____no_output_____
nbs/04_sequence-classification.ipynb
###Markdown Sequence classification> Example sequence classification with fastai and huggingface transformersIn this notebook a multilingual BERT model will be used to classify radiology report texts for presence or absence of congestion. ###Code import transformers from transformers import AutoTokenizer, AutoModelForSequenceClassification from fastai_transformer.core import * from fastai.text.all import * # cuda from fastai.distributed import * pretrained_weights = 'bert-base-uncased' tokenizer = AutoTokenizer.from_pretrained(pretrained_weights) model = AutoModelForSequenceClassification df = pd.read_csv('test_data.csv') dls = TextDataLoaders.from_df_with_custom_tok(df, custom_tok = tokenizer, bs = 32, seq_len = 256) dls.show_batch(max_n = 2) # cuda learn = transformers_classifier_learner(dls, model, model_name=pretrained_weights, metrics = accuracy).to_fp16() learn.unfreeze() learn = learn.to_parallel() # cuda learn.lr_find() # cuda learn.fit_one_cycle(5, 1e-4, wd = 1e-4) # cuda interp = ClassificationInterpretation.from_learner(learn) # cuda interp.plot_confusion_matrix() ###Output _____no_output_____
CS42_DS_&_A_1_M4_Searching_and_Recursion.ipynb
###Markdown Searching and Recursion* Logarithms* Types of problems where you might find `O(log n)` solutions* Linear search refresher* Binary Search* Introduction to Recursion**Attendance code: 7349** ###Code import random random.seed(3490) numbers = [random.randrange(200) for _ in range(20)] print(numbers) # Linear search for i in numbers: # O(n) over the len(numbers) if i == 66: print("Found it!") numbers.sort() # O(n * log n) print(numbers) # Now that it's sorted, we can do Binary Search instead # A process might be O(log n) if each step halves the remaining data to be processed # IOW effectively doubles the amount of data processed each step ###Output [129, 34, 192, 148, 46, 3, 150, 53, 153, 102, 160, 159, 66, 88, 37, 175, 89, 8, 10, 185] Found it! [3, 8, 10, 34, 37, 46, 53, 66, 88, 89, 102, 129, 148, 150, 153, 159, 160, 175, 185, 192] ###Markdown What is log n?Logarithms are like the opposites of exponentsCS when we say log n, we mean log_2 n.``` n2 = xlog_2 x = n As x gets big, n remains relatively small``````2^5 == 32elements operationsto process | v vlog_2 16 == 4log_2 32 == 5log_2 64 == 6log_2 128 == 7log_2 256 == 8log_2 65536 == 16log_2 4294967296 == 32``` ###Code # Binary Search def binary_search(numbers, target): # Return the index we find the target at, or -1 if we don't find it iterations = 0 # Start min_index at 0 min_index = 0 # Start max_index at len(numbers) - 1 max_index = len(numbers) - 1 # Loop until max_index < min_index: while min_index <= max_index: iterations += 1 # Find the middle index by averaging min_index and max_index (min + max) // 2 current = (min_index + max_index) // 2 # if value at current == target: return current if numbers[current] == target: return (current, iterations) # if value at current < target: if numbers[current] < target: # move min to current + 1 min_index = current + 1 # else: # value at current > target else: # move max to current - 1 max_index = current - 1 # If we get here, not found, return -1 return (-1, iterations) """ numbers = [3, 8, 10, 34, 37, 46, 53, 66, 88, 89, 102, 129, 148, 150, 153, 159, 160, 175, 185, 192] for n in numbers: print(binary_search(numbers, n)) """ print("Building lists...") random.seed(3490) numbers = [random.randrange(500000) for _ in range(10000000)] print("Sorting...") numbers.sort() # O(n * log n) print("Searching...") for i in range(2000, 2200): print(binary_search(numbers,i)) # O(log n) ###Output Building lists... Sorting... Searching... (39518, 16) (39537, 19) (39556, 18) (39575, 19) (39594, 17) (39613, 19) (39632, 18) (39651, 19) (39671, 14) (39690, 19) (39709, 18) (39728, 19) (39747, 17) (39766, 19) (39785, 18) (39823, 16) (39842, 19) (39861, 18) (39899, 17) (39918, 19) (39937, 18) (39956, 19) (39976, 15) (39995, 19) (40014, 18) (40033, 19) (40052, 17) (40061, 20) (40071, 19) (40090, 18) (40109, 19) (40128, 16) (40166, 18) (40175, 20) (40204, 17) (40213, 20) (40242, 18) (40251, 20) (40261, 19) (40281, 13) (40300, 19) (40319, 18) (40338, 19) (40357, 17) (40376, 19) (40395, 18) (40433, 16) (40452, 19) (40471, 18) (40509, 17) (40528, 19) (40547, 18) (40566, 19) (40576, 20) (40586, 15) (40624, 18) (40643, 19) (40662, 17) (40681, 19) (40700, 18) (40719, 19) (40738, 16) (40776, 18) (40795, 19) (40814, 17) (40833, 19) (40852, 18) (40871, 19) (40891, 14) (40929, 18) (40948, 19) (40967, 17) (40986, 19) (41005, 18) (41024, 19) (41043, 16) (41062, 19) (41081, 18) (41119, 17) (41128, 20) (41157, 18) (41176, 19) (41196, 15) (41215, 19) (41234, 18) (41253, 19) (41272, 17) (41291, 19) (41310, 18) (41329, 19) (41339, 20) (41349, 16) (41387, 18) (41406, 19) (41425, 17) (41444, 19) (41463, 18) (41482, 19) (41502, 12) (41540, 18) (41559, 19) (41578, 17) (41597, 19) (41616, 18) (41635, 19) (41654, 16) (41673, 19) (41692, 18) (41711, 19) (41730, 17) (41749, 19) (41768, 18) (41787, 19) (41807, 15) (41826, 19) (41845, 18) (41864, 19) (41883, 17) (41902, 19) (41916, 21) (41921, 18) (41959, 16) (41978, 19) (41997, 18) (42016, 19) (42035, 17) (42054, 19) (42073, 18) (42092, 19) (42112, 14) (42131, 19) (42150, 18) (42169, 19) (42188, 17) (42226, 18) (42245, 19) (42264, 16) (42283, 19) (42302, 18) (42321, 19) (42340, 17) (42359, 19) (42378, 18) (42417, 15) (42436, 19) (42455, 18) (42474, 19) (42493, 17) (42512, 19) (42531, 18) (42540, 20) (42550, 19) (42569, 16) (42588, 19) (42607, 18) (42626, 19) (42645, 17) (42664, 19) (42683, 18) (42702, 19) (42722, 13) (42741, 19) (42760, 18) (42779, 19) (42798, 17) (42836, 18) (42855, 19) (42874, 16) (42893, 19) (42912, 18) (42931, 19) (42950, 17) (42969, 19) (42988, 18) (43007, 19) (43027, 15) (43046, 19) (43065, 18) (43084, 19) (43103, 17) (43122, 19) (43141, 18) (43160, 19) (43179, 16) (43198, 19) (43217, 18) (43245, 20) (43255, 17) (43293, 18) (43312, 19) (43332, 14) (43351, 19) (43370, 18) (43379, 20) (43389, 19) (43408, 17) (43446, 18) (43465, 19) (43484, 16) (43503, 19) ###Markdown Intro to RecursionFunctions calling themselves. How to spot a recursive problemSee if you find how the problem is composed of identical subproblems. Print a listRecursively!```a = [1,2,3,4,5,6,7]``````print_a_list(x): print(x[0]) print_a_list(x[1:]) slice the rest of the list and pass it in``` ###Code a = [1,2,3,4] def print_a_list(x): # Base case if x == []: return print("inbound", x[0]) print_a_list(x[1:]) print("outbound", x[0]) print_a_list(a) # Fibonacci Sequence # # 0 1 2 3 4 5 6 7 8 9 10 11 # 0 1 1 2 3 5 8 13 21 34 55 89 ... # # Compute the nth Fibonacci number # # fib(0): 0 # fib(1): 1 # fib(n): fib(n-1) + fib(n-2) def fib(n): # Base cases if n == 0: return 0 if n == 1: return 1 return fib(n-1) + fib(n-2) for i in range(37): print(i, fib(i)) # Bonus info: "memoization" cache = {} def fib(n): # Base cases if n == 0: return 0 if n == 1: return 1 if n not in cache: cache[n] = fib(n-1) + fib(n-2) return cache[n] for i in range(1000): print(i, fib(i)) ###Output 0 0 1 1 2 1 3 2 4 3 5 5 6 8 7 13 8 21 9 34 10 55 11 89 12 144 13 233 14 377 15 610 16 987 17 1597 18 2584 19 4181 20 6765 21 10946 22 17711 23 28657 24 46368 25 75025 26 121393 27 196418 28 317811 29 514229 30 832040 31 1346269 32 2178309 33 3524578 34 5702887 35 9227465 36 14930352 37 24157817 38 39088169 39 63245986 40 102334155 41 165580141 42 267914296 43 433494437 44 701408733 45 1134903170 46 1836311903 47 2971215073 48 4807526976 49 7778742049 50 12586269025 51 20365011074 52 32951280099 53 53316291173 54 86267571272 55 139583862445 56 225851433717 57 365435296162 58 591286729879 59 956722026041 60 1548008755920 61 2504730781961 62 4052739537881 63 6557470319842 64 10610209857723 65 17167680177565 66 27777890035288 67 44945570212853 68 72723460248141 69 117669030460994 70 190392490709135 71 308061521170129 72 498454011879264 73 806515533049393 74 1304969544928657 75 2111485077978050 76 3416454622906707 77 5527939700884757 78 8944394323791464 79 14472334024676221 80 23416728348467685 81 37889062373143906 82 61305790721611591 83 99194853094755497 84 160500643816367088 85 259695496911122585 86 420196140727489673 87 679891637638612258 88 1100087778366101931 89 1779979416004714189 90 2880067194370816120 91 4660046610375530309 92 7540113804746346429 93 12200160415121876738 94 19740274219868223167 95 31940434634990099905 96 51680708854858323072 97 83621143489848422977 98 135301852344706746049 99 218922995834555169026 100 354224848179261915075 101 573147844013817084101 102 927372692193078999176 103 1500520536206896083277 104 2427893228399975082453 105 3928413764606871165730 106 6356306993006846248183 107 10284720757613717413913 108 16641027750620563662096 109 26925748508234281076009 110 43566776258854844738105 111 70492524767089125814114 112 114059301025943970552219 113 184551825793033096366333 114 298611126818977066918552 115 483162952612010163284885 116 781774079430987230203437 117 1264937032042997393488322 118 2046711111473984623691759 119 3311648143516982017180081 120 5358359254990966640871840 121 8670007398507948658051921 122 14028366653498915298923761 123 22698374052006863956975682 124 36726740705505779255899443 125 59425114757512643212875125 126 96151855463018422468774568 127 155576970220531065681649693 128 251728825683549488150424261 129 407305795904080553832073954 130 659034621587630041982498215 131 1066340417491710595814572169 132 1725375039079340637797070384 133 2791715456571051233611642553 134 4517090495650391871408712937 135 7308805952221443105020355490 136 11825896447871834976429068427 137 19134702400093278081449423917 138 30960598847965113057878492344 139 50095301248058391139327916261 140 81055900096023504197206408605 141 131151201344081895336534324866 142 212207101440105399533740733471 143 343358302784187294870275058337 144 555565404224292694404015791808 145 898923707008479989274290850145 146 1454489111232772683678306641953 147 2353412818241252672952597492098 148 3807901929474025356630904134051 149 6161314747715278029583501626149 150 9969216677189303386214405760200 151 16130531424904581415797907386349 152 26099748102093884802012313146549 153 42230279526998466217810220532898 154 68330027629092351019822533679447 155 110560307156090817237632754212345 156 178890334785183168257455287891792 157 289450641941273985495088042104137 158 468340976726457153752543329995929 159 757791618667731139247631372100066 160 1226132595394188293000174702095995 161 1983924214061919432247806074196061 162 3210056809456107725247980776292056 163 5193981023518027157495786850488117 164 8404037832974134882743767626780173 165 13598018856492162040239554477268290 166 22002056689466296922983322104048463 167 35600075545958458963222876581316753 168 57602132235424755886206198685365216 169 93202207781383214849429075266681969 170 150804340016807970735635273952047185 171 244006547798191185585064349218729154 172 394810887814999156320699623170776339 173 638817435613190341905763972389505493 174 1033628323428189498226463595560281832 175 1672445759041379840132227567949787325 176 2706074082469569338358691163510069157 177 4378519841510949178490918731459856482 178 7084593923980518516849609894969925639 179 11463113765491467695340528626429782121 180 18547707689471986212190138521399707760 181 30010821454963453907530667147829489881 182 48558529144435440119720805669229197641 183 78569350599398894027251472817058687522 184 127127879743834334146972278486287885163 185 205697230343233228174223751303346572685 186 332825110087067562321196029789634457848 187 538522340430300790495419781092981030533 188 871347450517368352816615810882615488381 189 1409869790947669143312035591975596518914 190 2281217241465037496128651402858212007295 191 3691087032412706639440686994833808526209 192 5972304273877744135569338397692020533504 193 9663391306290450775010025392525829059713 194 15635695580168194910579363790217849593217 195 25299086886458645685589389182743678652930 196 40934782466626840596168752972961528246147 197 66233869353085486281758142155705206899077 198 107168651819712326877926895128666735145224 199 173402521172797813159685037284371942044301 200 280571172992510140037611932413038677189525 201 453973694165307953197296969697410619233826 202 734544867157818093234908902110449296423351 203 1188518561323126046432205871807859915657177 204 1923063428480944139667114773918309212080528 205 3111581989804070186099320645726169127737705 206 5034645418285014325766435419644478339818233 207 8146227408089084511865756065370647467555938 208 13180872826374098837632191485015125807374171 209 21327100234463183349497947550385773274930109 210 34507973060837282187130139035400899082304280 211 55835073295300465536628086585786672357234389 212 90343046356137747723758225621187571439538669 213 146178119651438213260386312206974243796773058 214 236521166007575960984144537828161815236311727 215 382699285659014174244530850035136059033084785 216 619220451666590135228675387863297874269396512 217 1001919737325604309473206237898433933302481297 218 1621140188992194444701881625761731807571877809 219 2623059926317798754175087863660165740874359106 220 4244200115309993198876969489421897548446236915 221 6867260041627791953052057353082063289320596021 222 11111460156937785151929026842503960837766832936 223 17978720198565577104981084195586024127087428957 224 29090180355503362256910111038089984964854261893 225 47068900554068939361891195233676009091941690850 226 76159080909572301618801306271765994056795952743 227 123227981463641240980692501505442003148737643593 228 199387062373213542599493807777207997205533596336 229 322615043836854783580186309282650000354271239929 230 522002106210068326179680117059857997559804836265 231 844617150046923109759866426342507997914076076194 232 1366619256256991435939546543402365995473880912459 233 2211236406303914545699412969744873993387956988653 234 3577855662560905981638959513147239988861837901112 235 5789092068864820527338372482892113982249794889765 236 9366947731425726508977331996039353971111632790877 237 15156039800290547036315704478931467953361427680642 238 24522987531716273545293036474970821924473060471519 239 39679027332006820581608740953902289877834488152161 240 64202014863723094126901777428873111802307548623680 241 103881042195729914708510518382775401680142036775841 242 168083057059453008835412295811648513482449585399521 243 271964099255182923543922814194423915162591622175362 244 440047156314635932379335110006072428645041207574883 245 712011255569818855923257924200496343807632829750245 246 1152058411884454788302593034206568772452674037325128 247 1864069667454273644225850958407065116260306867075373 248 3016128079338728432528443992613633888712980904400501 249 4880197746793002076754294951020699004973287771475874 250 7896325826131730509282738943634332893686268675876375 251 12776523572924732586037033894655031898659556447352249 252 20672849399056463095319772838289364792345825123228624 253 33449372971981195681356806732944396691005381570580873 254 54122222371037658776676579571233761483351206693809497 255 87571595343018854458033386304178158174356588264390370 256 141693817714056513234709965875411919657707794958199867 257 229265413057075367692743352179590077832064383222590237 258 370959230771131880927453318055001997489772178180790104 259 600224643828207248620196670234592075321836561403380341 260 971183874599339129547649988289594072811608739584170445 261 1571408518427546378167846658524186148133445300987550786 262 2542592393026885507715496646813780220945054040571721231 263 4114000911454431885883343305337966369078499341559272017 264 6656593304481317393598839952151746590023553382130993248 265 10770594215935749279482183257489712959102052723690265265 266 17427187520417066673081023209641459549125606105821258513 267 28197781736352815952563206467131172508227658829511523778 268 45624969256769882625644229676772632057353264935332782291 269 73822750993122698578207436143903804565580923764844306069 270 119447720249892581203851665820676436622934188700177088360 271 193270471243015279782059101964580241188515112465021394429 272 312718191492907860985910767785256677811449301165198482789 273 505988662735923140767969869749836918999964413630219877218 274 818706854228831001753880637535093596811413714795418360007 275 1324695516964754142521850507284930515811378128425638237225 276 2143402371193585144275731144820024112622791843221056597232 277 3468097888158339286797581652104954628434169971646694834457 278 5611500259351924431073312796924978741056961814867751431689 279 9079598147510263717870894449029933369491131786514446266146 280 14691098406862188148944207245954912110548093601382197697835 281 23770696554372451866815101694984845480039225387896643963981 282 38461794961234640015759308940939757590587318989278841661816 283 62232491515607091882574410635924603070626544377175485625797 284 100694286476841731898333719576864360661213863366454327287613 285 162926777992448823780908130212788963731840407743629812913410 286 263621064469290555679241849789653324393054271110084140201023 287 426547842461739379460149980002442288124894678853713953114433 288 690168906931029935139391829792095612517948949963798093315456 289 1116716749392769314599541809794537900642843628817512046429889 290 1806885656323799249738933639586633513160792578781310139745345 291 2923602405716568564338475449381171413803636207598822186175234 292 4730488062040367814077409088967804926964428786380132325920579 293 7654090467756936378415884538348976340768064993978954512095813 294 12384578529797304192493293627316781267732493780359086838016392 295 20038668997554240570909178165665757608500558774338041350112205 296 32423247527351544763402471792982538876233052554697128188128597 297 52461916524905785334311649958648296484733611329035169538240802 298 84885164052257330097714121751630835360966663883732297726369399 299 137347080577163115432025771710279131845700275212767467264610201 300 222232244629420445529739893461909967206666939096499764990979600 301 359579325206583560961765665172189099052367214309267232255589801 302 581811569836004006491505558634099066259034153405766997246569401 303 941390895042587567453271223806288165311401367715034229502159202 304 1523202464878591573944776782440387231570435521120801226748728603 305 2464593359921179141398048006246675396881836888835835456250887805 306 3987795824799770715342824788687062628452272409956636682999616408 307 6452389184720949856740872794933738025334109298792472139250504213 308 10440185009520720572083697583620800653786381708749108822250120621 309 16892574194241670428824570378554538679120491007541580961500624834 310 27332759203762391000908267962175339332906872716290689783750745455 311 44225333398004061429732838340729878012027363723832270745251370289 312 71558092601766452430641106302905217344934236440122960529002115744 313 115783425999770513860373944643635095356961600163955231274253486033 314 187341518601536966291015050946540312701895836604078191803255601777 315 303124944601307480151388995590175408058857436768033423077509087810 316 490466463202844446442404046536715720760753273372111614880764689587 317 793591407804151926593793042126891128819610710140145037958273777397 318 1284057871006996373036197088663606849580363983512256652839038466984 319 2077649278811148299629990130790497978399974693652401690797312244381 320 3361707149818144672666187219454104827980338677164658343636350711365 321 5439356428629292972296177350244602806380313370817060034433662955746 322 8801063578447437644962364569698707634360652047981718378070013667111 323 14240420007076730617258541919943310440740965418798778412503676622857 324 23041483585524168262220906489642018075101617466780496790573690289968 325 37281903592600898879479448409585328515842582885579275203077366912825 326 60323387178125067141700354899227346590944200352359771993651057202793 327 97605290770725966021179803308812675106786783237939047196728424115618 328 157928677948851033162880158208040021697730983590298819190379481318411 329 255533968719576999184059961516852696804517766828237866387107905434029 330 413462646668428032346940119724892718502248750418536685577487386752440 331 668996615388005031531000081241745415306766517246774551964595292186469 332 1082459262056433063877940200966638133809015267665311237542082678938909 333 1751455877444438095408940282208383549115781784912085789506677971125378 334 2833915139500871159286880483175021682924797052577397027048760650064287 335 4585371016945309254695820765383405232040578837489482816555438621189665 336 7419286156446180413982701248558426914965375890066879843604199271253952 337 12004657173391489668678522013941832147005954727556362660159637892443617 338 19423943329837670082661223262500259061971330617623242503763837163697569 339 31428600503229159751339745276442091208977285345179605163923475056141186 340 50852543833066829834000968538942350270948615962802847667687312219838755 341 82281144336295989585340713815384441479925901307982452831610787275979941 342 133133688169362819419341682354326791750874517270785300499298099495818696 343 215414832505658809004682396169711233230800418578767753330908886771798637 344 348548520675021628424024078524038024981674935849553053830206986267617333 345 563963353180680437428706474693749258212475354428320807161115873039415970 346 912511873855702065852730553217787283194150290277873860991322859307033303 347 1476475227036382503281437027911536541406625644706194668152438732346449273 348 2388987100892084569134167581129323824600775934984068529143761591653482576 349 3865462327928467072415604609040860366007401579690263197296200323999931849 350 6254449428820551641549772190170184190608177514674331726439961915653414425 351 10119911756749018713965376799211044556615579094364594923736162239653346274 352 16374361185569570355515148989381228747223756609038926650176124155306760699 353 26494272942318589069480525788592273303839335703403521573912286394960106973 354 42868634127888159424995674777973502051063092312442448224088410550266867672 355 69362907070206748494476200566565775354902428015845969798000696945226974645 356 112231541198094907919471875344539277405965520328288418022089107495493842317 357 181594448268301656413948075911105052760867948344134387820089804440720816962 358 293825989466396564333419951255644330166833468672422805842178911936214659279 359 475420437734698220747368027166749382927701417016557193662268716376935476241 360 769246427201094785080787978422393713094534885688979999504447628313150135520 361 1244666864935793005828156005589143096022236302705537193166716344690085611761 362 2013913292136887790908943984011536809116771188394517192671163973003235747281 363 3258580157072680796737099989600679905139007491100054385837880317693321359042 364 5272493449209568587646043973612216714255778679494571578509044290696557106323 365 8531073606282249384383143963212896619394786170594625964346924608389878465365 366 13803567055491817972029187936825113333650564850089197542855968899086435571688 367 22334640661774067356412331900038009953045351020683823507202893507476314037053 368 36138207717265885328441519836863123286695915870773021050058862406562749608741 369 58472848379039952684853851736901133239741266891456844557261755914039063645794 370 94611056096305838013295371573764256526437182762229865607320618320601813254535 371 153083904475345790698149223310665389766178449653686710164582374234640876900329 372 247694960571651628711444594884429646292615632415916575771902992555242690154864 373 400778865046997419409593818195095036058794082069603285936485366789883567055193 374 648473825618649048121038413079524682351409714485519861708388359345126257210057 375 1049252690665646467530632231274619718410203796555123147644873726135009824265250 376 1697726516284295515651670644354144400761613511040643009353262085480136081475307 377 2746979206949941983182302875628764119171817307595766156998135811615145905740557 378 4444705723234237498833973519982908519933430818636409166351397897095281987215864 379 7191684930184179482016276395611672639105248126232175323349533708710427892956421 380 11636390653418416980850249915594581159038678944868584489700931605805709880172285 381 18828075583602596462866526311206253798143927071100759813050465314516137773128706 382 30464466237021013443716776226800834957182606015969344302751396920321847653300991 383 49292541820623609906583302538007088755326533087070104115801862234837985426429697 384 79757008057644623350300078764807923712509139103039448418553259155159833079730688 385 129049549878268233256883381302815012467835672190109552534355121389997818506160385 386 208806557935912856607183460067622936180344811293149000952908380545157651585891073 387 337856107814181089864066841370437948648180483483258553487263501935155470092051458 388 546662665750093946471250301438060884828525294776407554440171882480313121677942531 389 884518773564275036335317142808498833476705778259666107927435384415468591769993989 390 1431181439314368982806567444246559718305231073036073662367607266895781713447936520 391 2315700212878644019141884587055058551781936851295739770295042651311250305217930509 392 3746881652193013001948452031301618270087167924331813432662649918207032018665867029 393 6062581865071657021090336618356676821869104775627553202957692569518282323883797538 394 9809463517264670023038788649658295091956272699959366635620342487725314342549664567 395 15872045382336327044129125268014971913825377475586919838578035057243596666433462105 396 25681508899600997067167913917673267005781650175546286474198377544968911008983126672 397 41553554281937324111297039185688238919607027651133206312776412602212507675416588777 398 67235063181538321178464953103361505925388677826679492786974790147181418684399715449 399 108788617463475645289761992289049744844995705477812699099751202749393926359816304226 400 176023680645013966468226945392411250770384383304492191886725992896575345044216019675 401 284812298108489611757988937681460995615380088782304890986477195645969271404032323901 402 460835978753503578226215883073872246385764472086797082873203188542544616448248343576 403 745648276861993189984204820755333242001144560869101973859680384188513887852280667477 404 1206484255615496768210420703829205488386909032955899056732883572731058504300529011053 405 1952132532477489958194625524584538730388053593825001030592563956919572392152809678530 406 3158616788092986726405046228413744218774962626780900087325447529650630896453338689583 407 5110749320570476684599671752998282949163016220605901117918011486570203288606148368113 408 8269366108663463411004717981412027167937978847386801205243459016220834185059487057696 409 13380115429233940095604389734410310117100995067992702323161470502791037473665635425809 410 21649481537897403506609107715822337285038973915379503528404929519011871658725122483505 411 35029596967131343602213497450232647402139968983372205851566400021802909132390757909314 412 56679078505028747108822605166054984687178942898751709379971329540814780791115880392819 413 91708675472160090711036102616287632089318911882123915231537729562617689923506638302133 414 148387753977188837819858707782342616776497854780875624611509059103432470714622518694952 415 240096429449348928530894810398630248865816766662999539843046788666050160638129156997085 416 388484183426537766350753518180972865642314621443875164454555847769482631352751675692037 417 628580612875886694881648328579603114508131388106874704297602636435532791990880832689122 418 1017064796302424461232401846760575980150446009550749868752158484205015423343632508381159 419 1645645409178311156114050175340179094658577397657624573049761120640548215334513341070281 420 2662710205480735617346452022100755074809023407208374441801919604845563638678145849451440 421 4308355614659046773460502197440934169467600804865999014851680725486111854012659190521721 422 6971065820139782390806954219541689244276624212074373456653600330331675492690805039973161 423 11279421434798829164267456416982623413744225016940372471505281055817787346703464230494882 424 18250487254938611555074410636524312658020849229014745928158881386149462839394269270468043 425 29529908689737440719341867053506936071765074245955118399664162441967250186097733500962925 426 47780395944676052274416277690031248729785923474969864327823043828116713025492002771430968 427 77310304634413492993758144743538184801550997720924982727487206270083963211589736272393893 428 125090700579089545268174422433569433531336921195894847055310250098200676237081739043824861 429 202401005213503038261932567177107618332887918916819829782797456368284639448671475316218754 430 327491705792592583530106989610677051864224840112714676838107706466485315685753214360043615 431 529892711006095621792039556787784670197112759029534506620905162834769955134424689676262369 432 857384416798688205322146546398461722061337599142249183459012869301255270820177904036305984 433 1387277127804783827114186103186246392258450358171783690079918032136025225954602593712568353 434 2244661544603472032436332649584708114319787957314032873538930901437280496774780497748874337 435 3631938672408255859550518752770954506578238315485816563618848933573305722729383091461442690 436 5876600217011727891986851402355662620898026272799849437157779835010586219504163589210317027 437 9508538889419983751537370155126617127476264588285666000776628768583891942233546680671759717 438 15385139106431711643524221557482279748374290861085515437934408603594478161737710269882076744 439 24893677995851695395061591712608896875850555449371181438711037372178370103971256950553836461 440 40278817102283407038585813270091176624224846310456696876645445975772848265708967220435913205 441 65172495098135102433647404982700073500075401759827878315356483347951218369680224170989749666 442 105451312200418509472233218252791250124300248070284575192001929323724066635389191391425662871 443 170623807298553611905880623235491323624375649830112453507358412671675285005069415562415412537 444 276075119498972121378113841488282573748675897900397028699360341995399351640458606953841075408 445 446698926797525733283994464723773897373051547730509482206718754667074636645528022516256487945 446 722774046296497854662108306212056471121727445630906510906079096662473988285986629470097563353 447 1169472973094023587946102770935830368494778993361415993112797851329548624931514651986354051298 448 1892247019390521442608211077147886839616506438992322504018876947992022613217501281456451614651 449 3061719992484545030554313848083717208111285432353738497131674799321571238149015933442805665949 450 4953967011875066473162524925231604047727791871346061001150551747313593851366517214899257280600 451 8015687004359611503716838773315321255839077303699799498282226546635165089515533148342062946549 452 12969654016234677976879363698546925303566869175045860499432778293948758940882050363241320227149 453 20985341020594289480596202471862246559405946478745659997715004840583924030397583511583383173698 454 33954995036828967457475566170409171862972815653791520497147783134532682971279633874824703400847 455 54940336057423256938071768642271418422378762132537180494862787975116607001677217386408086574545 456 88895331094252224395547334812680590285351577786328700992010571109649289972956851261232789975392 457 143835667151675481333619103454952008707730339918865881486873359084765896974634068647640876549937 458 232730998245927705729166438267632598993081917705194582478883930194415186947590919908873666525329 459 376566665397603187062785541722584607700812257624060463965757289279181083922224988556514543075266 460 609297663643530892791951979990217206693894175329255046444641219473596270869815908465388209600595 461 985864329041134079854737521712801814394706432953315510410398508752777354792040897021902752675861 462 1595161992684664972646689501703019021088600608282570556855039728226373625661856805487290962276456 463 2581026321725799052501427023415820835483307041235886067265438236979150980453897702509193714952317 464 4176188314410464025148116525118839856571907649518456624120477965205524606115754507996484677228773 465 6757214636136263077649543548534660692055214690754342691385916202184675586569652210505678392181090 466 10933402950546727102797660073653500548627122340272799315506394167390200192685406718502163069409863 467 17690617586682990180447203622188161240682337031027142006892310369574875779255058929007841461590953 468 28624020537229717283244863695841661789309459371299941322398704536965075971940465647510004531000816 469 46314638123912707463692067318029823029991796402327083329291014906539951751195524576517845992591769 470 74938658661142424746936931013871484819301255773627024651689719443505027723135990224027850523592585 471 121253296785055132210628998331901307849293052175954107980980734350044979474331514800545696516184354 472 196191955446197556957565929345772792668594307949581132632670453793550007197467505024573547039776939 473 317445252231252689168194927677674100517887360125535240613651188143594986671799019825119243555961293 474 513637207677450246125760857023446893186481668075116373246321641937144993869266524849692790595738232 475 831082459908702935293955784701120993704369028200651613859972830080739980541065544674812034151699525 476 1344719667586153181419716641724567886890850696275767987106294472017884974410332069524504824747437757 477 2175802127494856116713672426425688880595219724476419600966267302098624954951397614199316858899137282 478 3520521795081009298133389068150256767486070420752187588072561774116509929361729683723821683646575039 479 5696323922575865414847061494575945648081290145228607189038829076215134884313127297923138542545712321 480 9216845717656874712980450562726202415567360565980794777111390850331644813674856981646960226192287360 481 14913169640232740127827512057302148063648650711209401966150219926546779697987984279570098768737999681 482 24130015357889614840807962620028350479216011277190196743261610776878424511662841261217058994930287041 483 39043184998122354968635474677330498542864661988399598709411830703425204209650825540787157763668286722 484 63173200356011969809443437297358849022080673265589795452673441480303628721313666802004216758598573763 485 102216385354134324778078911974689347564945335253989394162085272183728832930964492342791374522266860485 486 165389585710146294587522349272048196587026008519579189614758713664032461652278159144795591280865434248 487 267605971064280619365601261246737544151971343773568583776843985847761294583242651487586965803132294733 488 432995556774426913953123610518785740738997352293147773391602699511793756235520810632382557083997728981 489 700601527838707533318724871765523284890968696066716357168446685359555050818763462119969522887130023714 490 1133597084613134447271848482284309025629966048359864130560049384871348807054284272752352079971127752695 491 1834198612451841980590573354049832310520934744426580487728496070230903857873047734872321602858257776409 492 2967795697064976427862421836334141336150900792786444618288545455102252664927332007624673682829385529104 493 4801994309516818408452995190383973646671835537213025106017041525333156522800379742496995285687643305513 494 7769790006581794836315417026718114982822736329999469724305586980435409187727711750121668968517028834617 495 12571784316098613244768412217102088629494571867212494830322628505768565710528091492618664254204672140130 496 20341574322680408081083829243820203612317308197211964554628215486203974898255803242740333222721700974747 497 32913358638779021325852241460922292241811880064424459384950843991972540608783894735358997476926373114877 498 53254932961459429406936070704742495854129188261636423939579059478176515507039697978099330699648074089624 499 86168291600238450732788312165664788095941068326060883324529903470149056115823592713458328176574447204501 500 139423224561697880139724382870407283950070256587697307264108962948325571622863290691557658876222521294125 501 225591516161936330872512695036072072046011324913758190588638866418474627738686883405015987052796968498626 502 365014740723634211012237077906479355996081581501455497852747829366800199361550174096573645929019489792751 503 590606256885570541884749772942551428042092906415213688441386695785274827100237057501589632981816458291377 504 955620997609204752896986850849030784038174487916669186294134525152075026461787231598163278910835948084128 505 1546227254494775294781736623791582212080267394331882874735521220937349853562024289099752911892652406375505 506 2501848252103980047678723474640612996118441882248552061029655746089424880023811520697916190803488354459633 507 4048075506598755342460460098432195208198709276580434935765176967026774733585835809797669102696140760835138 508 6549923758702735390139183573072808204317151158828986996794832713116199613609647330495585293499629115294771 509 10597999265301490732599643671505003412515860435409421932560009680142974347195483140293254396195769876129909 510 17147923024004226122738827244577811616833011594238408929354842393259173960805130470788839689695398991424680 511 27745922289305716855338470916082815029348872029647830861914852073402148308000613611082094085891168867554589 512 44893845313309942978077298160660626646181883623886239791269694466661322268805744081870933775586567858979269 513 72639767602615659833415769076743441675530755653534070653184546540063470576806357692953027861477736726533858 514 117533612915925602811493067237404068321712639277420310444454241006724792845612101774823961637064304585513127 515 190173380518541262644908836314147509997243394930954381097638787546788263422418459467776989498542041312046985 516 307706993434466865456401903551551578318956034208374691542093028553513056268030561242600951135606345897560112 517 497880373953008128101310739865699088316199429139329072639731816100301319690449020710377940634148387209607097 518 805587367387474993557712643417250666635155463347703764181824844653814375958479581952978891769754733107167209 519 1303467741340483121659023383282949754951354892487032836821556660754115695648928602663356832403903120316774306 520 2109055108727958115216736026700200421586510355834736601003381505407930071607408184616335724173657853423941515 521 3412522850068441236875759409983150176537865248321769437824938166162045767256336787279692556577560973740715821 522 5521577958796399352092495436683350598124375604156506038828319671569975838863744971896028280751218827164657336 523 8934100808864840588968254846666500774662240852478275476653257837732021606120081759175720837328779800905373157 524 14455678767661239941060750283349851372786616456634781515481577509301997444983826731071749118079998628070030493 525 23389779576526080530029005130016352147448857309113056992134835347034019051103908490247469955408778428975403650 526 37845458344187320471089755413366203520235473765747838507616412856336016496087735221319219073488777057045434143 527 61235237920713401001118760543382555667684331074860895499751248203370035547191643711566689028897555486020837793 528 99080696264900721472208515956748759187919804840608734007367661059706052043279378932885908102386332543066271936 529 160315934185614122473327276500131314855604135915469629507118909263076087590471022644452597131283888029087109729 530 259396630450514843945535792456880074043523940756078363514486570322782139633750401577338505233670220572153381665 531 419712564636128966418863068957011388899128076671547993021605479585858227224221424221791102364954108601240491394 532 679109195086643810364398861413891462942652017427626356536092049908640366857971825799129607598624329173393873059 533 1098821759722772776783261930370902851841780094099174349557697529494498594082193250020920709963578437774634364453 534 1777930954809416587147660791784794314784432111526800706093789579403138960940165075820050317562202766948028237512 535 2876752714532189363930922722155697166626212205625975055651487108897637555022358325840971027525781204722662601965 536 4654683669341605951078583513940491481410644317152775761745276688300776515962523401661021345087983971670690839477 537 7531436383873795315009506236096188648036856522778750817396763797198414070984881727501992372613765176393353441442 538 12186120053215401266088089750036680129447500839931526579142040485499190586947405129163013717701749148064044280919 539 19717556437089196581097595986132868777484357362710277396538804282697604657932286856665006090315514324457397722361 540 31903676490304597847185685736169548906931858202641803975680844768196795244879691985828019808017263472521442003280 541 51621232927393794428283281722302417684416215565352081372219649050894399902811978842493025898332777796978839725641 542 83524909417698392275468967458471966591348073767993885347900493819091195147691670828321045706350041269500281728921 543 135146142345092186703752249180774384275764289333345966720120142869985595050503649670814071604682819066479121454562 544 218671051762790578979221216639246350867112363101339852068020636689076790198195320499135117311032860335979403183483 545 353817194107882765682973465820020735142876652434685818788140779559062385248698970169949188915715679402458524638045 546 572488245870673344662194682459267086009989015536025670856161416248139175446894290669084306226748539738437927821528 547 926305439978556110345168148279287821152865667970711489644302195807201560695593260839033495142464219140896452459573 548 1498793685849229455007362830738554907162854683506737160500463612055340736142487551508117801369212758879334380281101 549 2425099125827785565352530979017842728315720351477448650144765807862542296838080812347151296511676978020230832740674 550 3923892811677015020359893809756397635478575034984185810645229419917883032980568363855269097880889736899565213021775 551 6348991937504800585712424788774240363794295386461634460789995227780425329818649176202420394392566714919796045762449 552 10272884749181815606072318598530637999272870421445820271435224647698308362799217540057689492273456451819361258784224 553 16621876686686616191784743387304878363067165807907454732225219875478733692617866716260109886666023166739157304546673 554 26894761435868431797857061985835516362340036229353275003660444523177042055417084256317799378939479618558518563330897 555 43516638122555047989641805373140394725407202037260729735885664398655775748034950972577909265605502785297675867877570 556 70411399558423479787498867358975911087747238266614004739546108921832817803452035228895708644544982403856194431208467 557 113928037680978527777140672732116305813154440303874734475431773320488593551486986201473617910150485189153870299086037 558 184339437239402007564639540091092216900901678570488739214977882242321411354939021430369326554695467593010064730294504 559 298267474920380535341780212823208522714056118874363473690409655562810004906426007631842944464845952782163935029380541 560 482606912159782542906419752914300739614957797444852212905387537805131416261365029062212271019541420375173999759675045 561 780874387080163078248199965737509262329013916319215686595797193367941421167791036694055215484387373157337934789055586 562 1263481299239945621154619718651810001943971713764067899501184731173072837429156065756267486503928793532511934548730631 563 2044355686320108699402819684389319264272985630083283586096981924541014258596947102450322701988316166689849869337786217 564 3307836985560054320557439403041129266216957343847351485598166655714087096026103168206590188492244960222361803886516848 565 5352192671880163019960259087430448530489942973930635071695148580255101354623050270656912890480561126912211673224303065 566 8660029657440217340517698490471577796706900317777986557293315235969188450649153438863503078972806087134573477110819913 567 14012222329320380360477957577902026327196843291708621628988463816224289805272203709520415969453367214046785150335122978 568 22672251986760597700995656068373604123903743609486608186281779052193478255921357148383919048426173301181358627445942891 569 36684474316080978061473613646275630451100586901195229815270242868417768061193560857904335017879540515228143777781065869 570 59356726302841575762469269714649234575004330510681838001552021920611246317114918006288254066305713816409502405227008760 571 96041200618922553823942883360924865026104917411877067816822264789029014378308478864192589084185254331637646183008074629 572 155397926921764129586412153075574099601109247922558905818374286709640260695423396870480843150490968148047148588235083389 573 251439127540686683410355036436498964627214165334435973635196551498669275073731875734673432234676222479684794771243158018 574 406837054462450812996767189512073064228323413256994879453570838208309535769155272605154275385167190627731943359478241407 575 658276182003137496407122225948572028855537578591430853088767389706978810842887148339827707619843413107416738130721399425 576 1065113236465588309403889415460645093083860991848425732542338227915288346612042420944981983005010603735148681490199640832 577 1723389418468725805811011641409217121939398570439856585631105617622267157454929569284809690624854016842565419620921040257 578 2788502654934314115214901056869862215023259562288282318173443845537555504066971990229791673629864620577714101111120681089 579 4511892073403039921025912698279079336962658132728138903804549463159822661521901559514601364254718637420279520732041721346 580 7300394728337354036240813755148941551985917695016421221977993308697378165588873549744393037884583257997993621843162402435 581 11812286801740393957266726453428020888948575827744560125782542771857200827110775109258994402139301895418273142575204123781 582 19112681530077747993507540208576962440934493522760981347760536080554578992699648659003387440023885153416266764418366526216 583 30924968331818141950774266662004983329883069350505541473543078852411779819810423768262381842163187048834539906993570649997 584 50037649861895889944281806870581945770817562873266522821303614932966358812510072427265769282187072202250806671411937176213 585 80962618193714031895056073532586929100700632223772064294846693785378138632320496195528151124350259251085346578405507826210 586 131000268055609921839337880403168874871518195097038587116150308718344497444830568622793920406537331453336153249817445002423 587 211962886249323953734393953935755803972218827320810651410997002503722636077151064818322071530887590704421499828222952828633 588 342963154304933875573731834338924678843737022417849238527147311222067133521981633441115991937424922157757653078040397831056 589 554926040554257829308125788274680482815955849738659889938144313725789769599132698259438063468312512862179152906263350659689 590 897889194859191704881857622613605161659692872156509128465291624947856903121114331700554055405737435019936805984303748490745 591 1452815235413449534189983410888285644475648721895169018403435938673646672720247029959992118874049947882115958890567099150434 592 2350704430272641239071841033501890806135341594051678146868727563621503575841361361660546174279787382902052764874870847641179 593 3803519665686090773261824444390176450610990315946847165272163502295150248561608391620538293153837330784168723765437946791613 594 6154224095958732012333665477892067256746331909998525312140891065916653824402969753281084467433624713686221488640308794432792 595 9957743761644822785595489922282243707357322225945372477413054568211804072964578144901622760587462044470390212405746741224405 596 16111967857603554797929155400174310964103654135943897789553945634128457897367547898182707228021086758156611701046055535657197 597 26069711619248377583524645322456554671460976361889270266967000202340261970332126043084329988608548802627001913451802276881602 598 42181679476851932381453800722630865635564630497833168056520945836468719867699673941267037216629635560783613614497857812538799 599 68251391096100309964978446045087420307025606859722438323487946038808981838031799984351367205238184363410615527949660089420401 600 110433070572952242346432246767718285942590237357555606380008891875277701705731473925618404421867819924194229142447517901959200 601 178684461669052552311410692812805706249615844217278044703496837914086683543763273909969771627106004287604844670397177991379601 602 289117532242004794657842939580523992192206081574833651083505729789364385249494747835588176048973824211799073812844695893338801 603 467801993911057346969253632393329698441821925792111695787002567703451068793258021745557947676079828499403918483241873884718402 604 756919526153062141627096571973853690634028007366945346870508297492815454042752769581146123725053652711202992296086569778057203 605 1224721520064119488596350204367183389075849933159057042657510865196266522836010791326704071401133481210606910779328443662775605 606 1981641046217181630223446776341037079709877940526002389528019162689081976878763560907850195126187133921809903075415013440832808 607 3206362566281301118819796980708220468785727873685059432185530027885348499714774352234554266527320615132416813854743457103608413 608 5188003612498482749043243757049257548495605814211061821713549190574430476593537913142404461653507749054226716930158470544441221 609 8394366178779783867863040737757478017281333687896121253899079218459778976308312265376958728180828364186643530784901927648049634 610 13582369791278266616906284494806735565776939502107183075612628409034209452901850178519363189834336113240870247715060398192490855 611 21976735970058050484769325232564213583058273190003304329511707627493988429210162443896321918015164477427513778499962325840540489 612 35559105761336317101675609727370949148835212692110487405124336036528197882112012622415685107849500590668384026215022724033031344 613 57535841731394367586444934959935162731893485882113791734636043664022186311322175066312007025864665068095897804714985049873571833 614 93094947492730684688120544687306111880728698574224279139760379700550384193434187688727692133714165658764281830930007773906603177 615 150630789224125052274565479647241274612622184456338070874396423364572570504756362755039699159578830726860179635644992823780175010 616 243725736716855736962686024334547386493350883030562350014156803065122954698190550443767391293292996385624461466575000597686778187 617 394356525940980789237251503981788661105973067486900420888553226429695525202946913198807090452871827112484641102219993421466953197 618 638082262657836526199937528316336047599323950517462770902710029494818479901137463642574481746164823498109102568794994019153731384 619 1032438788598817315437189032298124708705297018004363191791263255924514005104084376841381572199036650610593743671014987440620684581 620 1670521051256653841637126560614460756304620968521825962693973285419332485005221840483956053945201474108702846239809981459774415965 621 2702959839855471157074315592912585465009917986526189154485236541343846490109306217325337626144238124719296589910824968900395100546 622 4373480891112124998711442153527046221314538955048015117179209826763178975114528057809293680089439598827999436150634950360169516511 623 7076440730967596155785757746439631686324456941574204271664446368107025465223834275134631306233677723547296026061459919260564617057 624 11449921622079721154497199899966677907638995896622219388843656194870204440338362332943924986323117322375295462212094869620734133568 625 18526362353047317310282957646406309593963452838196423660508102562977229905562196608078556292556795045922591488273554788881298750625 626 29976283975127038464780157546372987501602448734818643049351758757847434345900558941022481278879912368297886950485649658502032884193 627 48502646328174355775063115192779297095565901573015066709859861320824664251462755549101037571436707414220478438759204447383331634818 628 78478930303301394239843272739152284597168350307833709759211620078672098597363314490123518850316619782518365389244854105885364519011 629 126981576631475750014906387931931581692734251880848776469071481399496762848826070039224556421753327196738843828004058553268696153829 630 205460506934777144254749660671083866289902602188682486228283101478168861446189384529348075272069946979257209217248912659154060672840 631 332442083566252894269656048603015447982636854069531262697354582877665624295015454568572631693823274175996053045252971212422756826669 632 537902590501030038524405709274099314272539456258213748925637684355834485741204839097920706965893221155253262262501883871576817499509 633 870344674067282932794061757877114762255176310327745011622992267233500110036220293666493338659716495331249315307754855083999574326178 634 1408247264568312971318467467151214076527715766585958760548629951589334595777425132764414045625609716486502577570256738955576391825687 635 2278591938635595904112529225028328838782892076913703772171622218822834705813645426430907384285326211817751892878011594039575966151865 636 3686839203203908875430996692179542915310607843499662532720252170412169301591070559195321429910935928304254470448268332995152357977552 637 5965431141839504779543525917207871754093499920413366304891874389235004007404715985626228814196262140122006363326279927034728324129417 638 9652270345043413654974522609387414669404107763913028837612126559647173308995786544821550244107198068426260833774548260029880682106969 639 15617701486882918434518048526595286423497607684326395142504000948882177316400502530447779058303460208548267197100828187064609006236386 640 25269971831926332089492571135982701092901715448239423980116127508529350625396289075269329302410658276974528030875376447094489688343355 641 40887673318809250524010619662577987516399323132565819122620128457411527941796791605717108360714118485522795227976204634159098694579741 642 66157645150735582613503190798560688609301038580805243102736255965940878567193080680986437663124776762497323258851581081253588382923096 643 107045318469544833137513810461138676125700361713371062225356384423352406508989872286703546023838895248020118486827785715412687077502837 644 173202963620280415751017001259699364735001400294176305328092640389293285076182952967689983686963672010517441745679366796666275460425933 645 280248282089825248888530811720838040860701762007547367553449024812645691585172825254393529710802567258537560232507152512078962537928770 646 453451245710105664639547812980537405595703162301723672881541665201938976661355778222083513397766239269055001978186519308745237998354703 647 733699527799930913528078624701375446456404924309271040434990690014584668246528603476477043108568806527592562210693671820824200536283473 648 1187150773510036578167626437681912852052108086610994713316532355216523644907884381698560556506335045796647564188880191129569438534638176 649 1920850301309967491695705062383288298508513010920265753751523045231108313154412985175037599614903852324240126399573862950393639070921649 650 3108001074820004069863331500065201150560621097531260467068055400447631958062297366873598156121238898120887690588454054079963077605559825 651 5028851376129971561559036562448489449069134108451526220819578445678740271216710352048635755736142750445127816988027917030356716676481474 652 8136852450949975631422368062513690599629755205982786687887633846126372229279007718922233911857381648566015507576481971110319794282041299 653 13165703827079947192981404624962180048698889314434312908707212291805112500495718070970869667593524399011143324564509888140676510958522773 654 21302556278029922824403772687475870648328644520417099596594846137931484729774725789893103579450906047577158832140991859250996305240564072 655 34468260105109870017385177312438050697027533834851412505302058429736597230270443860863973247044430446588302156705501747391672816199086845 656 55770816383139792841788949999913921345356178355268512101896904567668081960045169650757076826495336494165460988846493606642669121439650917 657 90239076488249662859174127312351972042383712190119924607198962997404679190315613511621050073539766940753763145551995354034341937638737762 658 146009892871389455700963077312265893387739890545388436709095867565072761150360783162378126900035103434919224134398488960677011059078388679 659 236248969359639118560137204624617865430123602735508361316294830562477440340676396673999176973574870375672987279950484314711352996717126441 660 382258862231028574261100281936883758817863493280896798025390698127550201491037179836377303873609973810592211414348973275388364055795515120 661 618507831590667692821237486561501624247987096016405159341685528690027641831713576510376480847184844186265198694299457590099717052512641561 662 1000766693821696267082337768498385383065850589297301957367076226817577843322750756346753784720794817996857410108648430865488081108308156681 663 1619274525412363959903575255059887007313837685313707116708761755507605485154464332857130265567979662183122608802947888455587798160820798242 664 2620041219234060226985913023558272390379688274611009074075837982325183328477215089203884050288774480179980018911596319321075879269128954923 665 4239315744646424186889488278618159397693525959924716190784599737832788813631679422061014315856754142363102627714544207776663677429949753165 666 6859356963880484413875401302176431788073214234535725264860437720157972142108894511264898366145528622543082646626140527097739556699078708088 667 11098672708526908600764889580794591185766740194460441455645037457990760955740573933325912682002282764906185274340684734874403234129028461253 668 17958029672407393014640290882971022973839954428996166720505475178148733097849468444590811048147811387449267920966825261972142790828107169341 669 29056702380934301615405180463765614159606694623456608176150512636139494053590042377916723730150094152355453195307509996846546024957135630594 670 47014732053341694630045471346736637133446649052452774896655987814288227151439510822507534778297905539804721116274335258818688815785242799935 671 76071434434275996245450651810502251293053343675909383072806500450427721205029553200424258508447999692160174311581845255665234840742378430529 672 123086166487617690875496123157238888426499992728362157969462488264715948356469064022931793286745905231964895427856180514483923656527621230464 673 199157600921893687120946774967741139719553336404271541042268988715143669561498617223356051795193904924125069739438025770149158497269999660993 674 322243767409511377996442898124980028146053329132633699011731476979859617917967681246287845081939810156089965167294206284633082153797620891457 675 521401368331405065117389673092721167865606665536905240054000465695003287479466298469643896877133715080215034906732232054782240651067620552450 676 843645135740916443113832571217701196011659994669538939065731942674862905397433979715931741959073525236305000074026438339415322804865241443907 677 1365046504072321508231222244310422363877266660206444179119732408369866192876900278185575638836207240316520034980758670394197563455932861996357 678 2208691639813237951345054815528123559888926654875983118185464351044729098274334257901507380795280765552825035054785108733612886260798103440264 679 3573738143885559459576277059838545923766193315082427297305196759414595291151234536087083019631488005869345070035543779127810449716730965436621 680 5782429783698797410921331875366669483655119969958410415490661110459324389425568793988590400426768771422170105090328887861423335977529068876885 681 9356167927584356870497608935205215407421313285040837712795857869873919680576803330075673420058256777291515175125872666989233785694260034313506 682 15138597711283154281418940810571884891076433254999248128286518980333244070002372124064263820485025548713685280216201554850657121671789103190391 683 24494765638867511151916549745777100298497746540040085841082376850207163750579175454139937240543282326005200455342074221839890907366049137503897 684 39633363350150665433335490556348985189574179795039333969368895830540407820581547578204201061028307874718885735558275776690548029037838240694288 685 64128128989018176585252040302126085488071926335079419810451272680747571571160723032344138301571590200724086190900349998530438936403887378198185 686 103761492339168842018587530858475070677646106130118753779820168511287979391742270610548339362599898075442971926458625775220986965441725618892473 687 167889621328187018603839571160601156165718032465198173590271441192035550962902993642892477664171488276167058117358975773751425901845612997090658 688 271651113667355860622427102019076226843364138595316927370091609703323530354645264253440817026771386351610030043817601548972412867287338615983131 689 439540734995542879226266673179677383009082171060515100960363050895359081317548257896333294690942874627777088161176577322723838769132951613073789 690 711191848662898739848693775198753609852446309655832028330454660598682611672193522149774111717714260979387118204994178871696251636420290229056920 691 1150732583658441619074960448378430992861528480716347129290817711494041692989741780046107406408657135607164206366170756194420090405553241842130709 692 1861924432321340358923654223577184602713974790372179157621272372092724304661935302195881518126371396586551324571164935066116342041973532071187629 693 3012657015979781977998614671955615595575503271088526286912090083586765997651677082241988924535028532193715530937335691260536432447526773913318338 694 4874581448301122336922268895532800198289478061460705444533362455679490302313612384437870442661399928780266855508500626326652774489500305984505967 695 7887238464280904314920883567488415793864981332549231731445452539266256299965289466679859367196428460973982386445836317587189206937027079897824305 696 12761819912582026651843152463021215992154459394009937175978814994945746602278901851117729809857828389754249241954336943913841981426527385882330272 697 20649058376862930966764036030509631786019440726559168907424267534212002902244191317797589177054256850728231628400173261501031188363554465780154577 698 33410878289444957618607188493530847778173900120569106083403082529157749504523093168915318986912085240482480870354510205414873169790081851662484849 699 54059936666307888585371224524040479564193340847128274990827350063369752406767284486712908163966342091210712498754683466915904358153636317442639426 700 87470814955752846203978413017571327342367240967697381074230432592527501911290377655628227150878427331693193369109193672330777527943718169105124275 701 141530751622060734789349637541611806906560581814825656065057782655897254318057662142341135314844769422903905867863877139246681886097354486547763701 702 229001566577813580993328050559183134248927822782523037139288215248424756229348039797969362465723196754597099236973070811577459414041072655652887976 703 370532318199874315782677688100794941155488404597348693204345997904322010547405701940310497780567966177501005104836947950824141300138427142200651677 704 599533884777687896776005738659978075404416227379871730343634213152746766776753741738279860246291162932098104341810018762401600714179499797853539653 705 970066202977562212558683426760773016559904631977220423547980211057068777324159443678590358026859129109599109446646966713225742014317926940054191330 706 1569600087755250109334689165420751091964320859357092153891614424209815544100913185416870218273150292041697213788456985475627342728497426737907730983 707 2539666290732812321893372592181524108524225491334312577439594635266884321425072629095460576300009421151296323235103952188853084742815353677961922313 708 4109266378488062431228061757602275200488546350691404731331209059476699865525985814512330794573159713192993537023560937664480427471312780415869653296 709 6648932669220874753121434349783799309012771842025717308770803694743584186951058443607791370873169134344289860258664889853333512214128134093831575609 710 10758199047708937184349496107386074509501318192717122040102012754220284052477044258120122165446328847537283397282225827517813939685440914509701228905 711 17407131716929811937470930457169873818514090034742839348872816448963868239428102701727913536319497981881573257540890717371147451899569048603532804514 712 28165330764638749121820426564555948328015408227459961388974829203184152291905146959848035701765826829418856654823116544888961391585009963113234033419 713 45572462481568561059291357021725822146529498262202800737847645652148020531333249661575949238085324811300429912364007262260108843484579011716766837933 714 73737793246207310181111783586281770474544906489662762126822474855332172823238396621423984939851151640719286567187123807149070235069588974830000871352 715 119310255727775871240403140608007592621074404751865562864670120507480193354571646282999934177936476452019716479551131069409179078554167986546767709285 716 193048048973983181421514924194289363095619311241528324991492595362812366177810042904423919117787628092739003046738254876558249313623756961376768580637 717 312358304701759052661918064802296955716693715993393887856162715870292559532381689187423853295724104544758719526289385945967428392177924947923536289922 718 505406353675742234083432988996586318812313027234922212847655311233104925710191732091847772413511732637497722573027640822525677705801681909300304870559 719 817764658377501286745351053798883274529006743228316100703818027103397485242573421279271625709235837182256442099317026768493106097979606857223841160481 720 1323171012053243520828784042795469593341319770463238313551473338336502410952765153371119398122747569819754164672344667591018783803781288766524146031040 721 2140935670430744807574135096594352867870326513691554414255291365439899896195338574650391023831983407002010606771661694359511889901760895623747987191521 722 3464106682483988328402919139389822461211646284154792727806764703776402307148103728021510421954730976821764771444006361950530673705542184390272133222561 723 5605042352914733135977054235984175329081972797846347142062056069216302203343442302671901445786714383823775378215668056310042563607303080014020120414082 724 9069149035398721464379973375373997790293619082001139869868820772992704510491546030693411867741445360645540149659674418260573237312845264404292253636643 725 14674191388313454600357027611358173119375591879847487011930876842209006713834988333365313313528159744469315527875342474570615800920148344418312374050725 726 23743340423712176064737000986732170909669210961848626881799697615201711224326534364058725181269605105114855677535016892831189038232993608822604627687368 727 38417531812025630665094028598090344029044802841696113893730574457410717938161522697424038494797764849584171205410359367401804839153141953240917001738093 728 62160872235737806729831029584822514938714013803544740775530272072612429162488057061482763676067369954699026882945376260232993877386135562063521629425461 729 100578404047763437394925058182912858967758816645240854669260846530023147100649579758906802170865134804283198088355735627634798716539277515304438631163554 730 162739276283501244124756087767735373906472830448785595444791118602635576263137636820389565846932504758982224971301111887867792593925413077367960260589015 731 263317680331264681519681145950648232874231647094026450114051965132658723363787216579296368017797639563265423059656847515502591310464690592672398891752569 732 426056956614765925644437233718383606780704477542812045558843083735294299626924853399685933864730144322247648030957959403370383904390103670040359152341584 733 689374636946030607164118379669031839654936124636838495672895048867953022990712069978982301882527783885513071090614806918872975214854794262712758044094153 734 1115431593560796532808555613387415446435640602179650541231738132603247322617636923378668235747257928207760719121572766322243359119244897932753117196435737 735 1804806230506827139972673993056447286090576726816489036904633181471200345608348993357650537629785712093273790212187573241116334334099692195465875240529890 736 2920237824067623672781229606443862732526217328996139578136371314074447668225985916736318773377043640301034509333760339563359693453344590128218992436965627 737 4725044054574450812753903599500310018616794055812628615041004495545648013834334910093969311006829352394308299545947912804476027787444282323684867677495517 738 7645281878642074485535133205944172751143011384808768193177375809620095682060320826830288084383872992695342808879708252367835721240788872451903860114461144 739 12370325933216525298289036805444482769759805440621396808218380305165743695894655736924257395390702345089651108425656165172311749028233154775588727791956661 740 20015607811858599783824170011388655520902816825430165001395756114785839377954976563754545479774575337784993917305364417540147470269022027227492587906417805 741 32385933745075125082113206816833138290662622266051561809614136419951583073849632300678802875165277682874645025731020582712459219297255182003081315698374466 742 52401541556933724865937376828221793811565439091481726811009892534737422451804608864433348354939853020659638943036385000252606689566277209230573903604792271 743 84787475302008849948050583645054932102228061357533288620624028954689005525654241165112151230105130703534283968767405582965065908863532391233655219303166737 744 137189016858942574813987960473276725913793500449015015431633921489426427977458850029545499585044983724193922911803790583217672598429809600464229122907959008 745 221976492160951424762038544118331658016021561806548304052257950444115433503113091194657650815150114427728206880571196166182738507293341991697884342211125745 746 359165509019893999576026504591608383929815062255563319483891871933541861480571941224203150400195098151922129792374986749400411105723151592162113465119084753 747 581142001180845424338065048709940041945836624062111623536149822377657294983685032418860801215345212579650336672946182915583149613016493583859997807330210498 748 940307510200739423914091553301548425875651686317674943020041694311199156464256973643063951615540310731572466465321169664983560718739645176022111272449295251 749 1521449511381584848252156602011488467821488310379786566556191516688856451447942006061924752830885523311222803138267352580566710331756138759882109079779505749 750 2461757021582324272166248155313036893697139996697461509576233211000055607912198979704988704446425834042795269603588522245550271050495783935904220352228801000 751 3983206532963909120418404757324525361518628307077248076132424727688912059360140985766913457277311357354018072741855874826116981382251922695786329432008306749 752 6444963554546233392584652912637562255215768303774709585708657938688967667272339965471902161723737191396813342345444397071667252432747706631690549784237107749 753 10428170087510142513003057669962087616734396610851957661841082666377879726632480951238815619001048548750831415087300271897784233814999629327476879216245414498 754 16873133642056375905587710582599649871950164914626667247549740605066847393904820916710717780724785740147644757432744668969451486247747335959167429000482522247 755 27301303729566518418590768252561737488684561525478624909390823271444727120537301867949533399725834288898476172520044940867235720062746965286644308216727936745 756 44174437371622894324178478835161387360634726440105292156940563876511574514442122784660251180450620029046120929952789609836687206310494301245811737217210458992 757 71475741101189412742769247087723124849319287965583917066331387147956301634979424652609784580176454317944597102472834550703922926373241266532456045433938395737 758 115650178472812307066947725922884512209954014405689209223271951024467876149421547437270035760627074346990718032425624160540610132683735567778267782651148854729 759 187125919574001719809716973010607637059273302371273126289603338172424177784400972089879820340803528664935315134898458711244533059056976834310723828085087250466 760 302776098046814026876664698933492149269227316776962335512875289196892053933822519527149856101430603011926033167324082871785143191740712402088991610736236105195 761 489902017620815746686381671944099786328500619148235461802478627369316231718223491617029676442234131676861348302222541583029676250797689236399715438821323355661 762 792678115667629773563046370877591935597727935925197797315353916566208285652046011144179532543664734688787381469546624454814819442538401638488707049557559460856 763 1282580133288445520249428042821691721926228555073433259117832543935524517370269502761209208985898866365648729771769166037844495693336090874888422488378882816517 764 2075258248956075293812474413699283657523956490998631056433186460501732803022315513905388741529563601054436111241315790492659315135874492513377129537936442277373 765 3357838382244520814061902456520975379450185046072064315551019004437257320392585016666597950515462467420084841013084956530503810829210583388265552026315325093890 766 5433096631200596107874376870220259036974141537070695371984205464938990123414900530571986692045026068474520952254400747023163125965085075901642681564251767371263 767 8790935013445116921936279326741234416424326583142759687535224469376247443807485547238584642560488535894605793267485703553666936794295659289908233590567092465153 768 14224031644645713029810656196961493453398468120213455059519429934315237567222386077810571334605514604369126745521886450576830062759380735191550915154818859836416 769 23014966658090829951746935523702727869822794703356214747054654403691485011029871625049155977166003140263732538789372154130496999553676394481459148745385952301569 770 37238998302736542981557591720664221323221262823569669806574084338006722578252257702859727311771517744632859284311258604707327062313057129673010063900204812137985 771 60253964960827372933304527244366949193044057526925884553628738741698207589282129327908883288937520884896591823100630758837824061866733524154469212645590764439554 772 97492963263563915914862118965031170516265320350495554360202823079704930167534387030768610600709038629529451107411889363545151124179790653827479276545795576577539 773 157746928224391288848166646209398119709309377877421438913831561821403137756816516358677493889646559514426042930512520122382975186046524177981948489191386341017093 774 255239891487955204763028765174429290225574698227916993274034384901108067924350903389446104490355598143955494037924409485928126310226314831809427765737181917594632 775 412986819712346493611195411383827409934884076105338432187865946722511205681167419748123598380002157658381536968436929608311101496272839009791376254928568258611725 776 668226711200301698374224176558256700160458774333255425461900331623619273605518323137569702870357755802337031006361339094239227806499153841600804020665750176206357 777 1081213530912648191985419587942084110095342850438593857649766278346130479286685742885693301250359913460718567974798268702550329302771992851392180275594318434818082 778 1749440242112949890359643764500340810255801624771849283111666609969749752892204066023263004120717669263055598981159607796789557109271146692992984296260068611024439 779 2830653773025598082345063352442424920351144475210443140761432888315880232178889808908956305371077582723774166955957876499339886412043139544385164571854387045842521 780 4580094015138547972704707116942765730606946099982292423873099498285629985071093874932219309491795251986829765937117484296129443521314286237378148868114455656866960 781 7410747788164146055049770469385190650958090575192735564634532386601510217249983683841175614862872834710603932893075360795469329933357425781763313439968842702709481 782 11990841803302694027754477586327956381565036675175027988507631884887140202321077558773394924354668086697433698830192845091598773454671712019141462308083298359576441 783 19401589591466840082804248055713147032523127250367763553142164271488650419571061242614570539217540921408037631723268205887068103388029137800904775748052141062285922 784 31392431394769534110558725642041103414088163925542791541649796156375790621892138801387965463572209008105471330553461050978666876842700849820046238056135439421862363 785 50794020986236374193362973697754250446611291175910555094791960427864441041463200044002536002789749929513508962276729256865734980230729987620951013804187580484148285 786 82186452381005908303921699339795353860699455101453346636441756584240231663355338845390501466361958937618980292830190307844401857073430837440997251860323019906010648 787 132980473367242282497284673037549604307310746277363901731233717012104672704818538889393037469151708867132489255106919564710136837304160825061948265664510600390158933 788 215166925748248190801206372377344958168010201378817248367675473596344904368173877734783538935513667804751469547937109872554538694377591662502945517524833620296169581 789 348147399115490473298491045414894562475320947656181150098909190608449577072992416624176576404665376671883958803044029437264675531681752487564893783189344220686328514 790 563314324863738664099697417792239520643331149034998398466584664204794481441166294358960115340179044476635428350981139309819214226059344150067839300714177840982498095 791 911461723979229137398188463207134083118652096691179548565493854813244058514158710983136691744844421148519387154025168747083889757741096637632733083903522061668826609 792 1474776048842967801497885880999373603761983245726177947032078519018038539955325005342096807085023465625154815505006308056903103983800440787700572384617699902651324704 793 2386237772822196938896074344206507686880635342417357495597572373831282598469483716325233498829867886773674202659031476803986993741541537425333305468521221964320151313 794 3861013821665164740393960225205881290642618588143535442629650892849321138424808721667330305914891352398829018164037784860890097725341978213033877853138921866971476017 795 6247251594487361679290034569412388977523253930560892938227223266680603736894292437992563804744759239172503220823069261664877091466883515638367183321660143831291627330 796 10108265416152526419683994794618270268165872518704428380856874159529924875319101159659894110659650591571332238987107046525767189192225493851401061174799065698263103347 797 16355517010639888098974029364030659245689126449265321319084097426210528612213393597652457915404409830743835459810176308190644280659109009489768244496459209529554730677 798 26463782426792414518658024158648929513854998967969749699940971585740453487532494757312352026064060422315167698797283354716411469851334503341169305671258275227817834024 799 42819299437432302617632053522679588759544125417235071019025069011950982099745888354964809941468470253059003158607459662907055750510443512830937550167717484757372564701 800 69283081864224717136290077681328518273399124385204820718966040597691435587278383112277161967532530675374170857404743017623467220361778016172106855838975759985190398725 801 112102381301657019753922131204008107032943249802439891737991109609642417687024271467241971909001000928433174016012202680530522970872221529003044406006693244742562963426 802 181385463165881736890212208885336625306342374187644712456957150207333853274302654579519133876533531603807344873416945698153990191233999545175151261845669004727753362151 803 293487844467538756644134340089344732339285623990084604194948259816976270961326926046761105785534532532240518889429148378684513162106221074178195667852362249470316325577 804 474873307633420493534346548974681357645627998177729316651905410024310124235629580626280239662068064136047863762846094076838503353340220619353346929698031254198069687728 805 768361152100959250178480889064026089984913622167813920846853669841286395196956506673041345447602596668288382652275242455523016515446441693531542597550393503668386013305 806 1243234459734379743712827438038707447630541620345543237498759079865596519432586087299321585109670660804336246415121336532361519868786662312884889527248424757866455701033 807 2011595611835338993891308327102733537615455242513357158345612749706882914629542593972362930557273257472624629067396578987884536384233104006416432124798818261534841714338 808 3254830071569718737604135765141440985245996862858900395844371829572479434062128681271684515666943918276960875482517915520246056253019766319301321652047243019401297415371 809 5266425683405057731495444092244174522861452105372257554189984579279362348691671275244047446224217175749585504549914494508130592637252870325717753776846061280936139129709 810 8521255754974776469099579857385615508107448968231157950034356408851841782753799956515731961891161094026546380032432410028376648890272636645019075428893304300337436545080 811 13787681438379834200595023949629790030968901073603415504224340988131204131445471231759779408115378269776131884582346904536507241527525506970736829205739365581273575674789 812 22308937193354610669694603807015405539076350041834573454258697396983045914199271188275511370006539363802678264614779314564883890417798143615755904634632669881611012219869 813 36096618631734444870289627756645195570045251115437988958483038385114250045644742420035290778121917633578810149197126219101391131945323650586492733840372035462884587894658 814 58405555825089055539984231563660601109121601157272562412741735782097295959844013608310802148128456997381488413811905533666275022363121794202248638475004705344495600114527 815 94502174456823500410273859320305796679166852272710551371224774167211546005488756028346092926250374630960298563009031752767666154308445444788741372315376740807380188009185 816 152907730281912555950258090883966397788288453429983113783966509949308841965332769636656895074378831628341786976820937286433941176671567238990990010790381446151875788123712 817 247409904738736056360531950204272194467455305702693665155191284116520387970821525665002988000629206259302085539829969039201607330980012683779731383105758186959255976132897 818 400317635020648612310790041088238592255743759132676778939157794065829229936154295301659883075008037887643872516650906325635548507651579922770721393896139633111131764256609 819 647727539759384668671321991292510786723199064835370444094349078182349617906975820966662871075637244146945958056480875364837155838631592606550452777001897820070387740389506 820 1048045174780033280982112032380749378978942823968047223033506872248178847843130116268322754150645282034589830573131781690472704346283172529321174170898037453181519504646115 821 1695772714539417949653434023673260165702141888803417667127855950430528465750105937234985625226282526181535788629612657055309860184914765135871626947899935273251907245035621 822 2743817889319451230635546056054009544681084712771464890161362822678707313593236053503308379376927808216125619202744438745782564531197937665192801118797972726433426749681736 823 4439590603858869180288980079727269710383226601574882557289218773109235779343341990738294004603210334397661407832357095801092424716112702801064428066697907999685333994717357 824 7183408493178320410924526135781279255064311314346347447450581595787943092936578044241602383980138142613787027035101534546874989247310640466257229185495880726118760744399093 825 11622999097037189591213506215508548965447537915921230004739800368897178872279920034979896388583348477011448434867458630347967413963423343267321657252193788725804094739116450 826 18806407590215510002138032351289828220511849230267577452190381964685121965216498079221498772563486619625235461902560164894842403210733983733578886437689669451922855483515543 827 30429406687252699593351538566798377185959387146188807456930182333582300837496418114201395161146835096636683896770018795242809817174157327000900543689883458177726950222631993 828 49235814277468209595489570918088205406471236376456384909120564298267422802712916193422893933710321716261919358672578960137652220384891310734479430127573127629649805706147536 829 79665220964720909188841109484886582592430623522645192366050746631849723640209334307624289094857156812898603255442597755380462037559048637735379973817456585807376755928779529 830 128901035242189118784330680402974787998901859899101577275171310930117146442922250501047183028567478529160522614115176715518114257943939948469859403945029713437026561634927065 831 208566256206910027973171789887861370591332483421746769641222057561966870083131584808671472123424635342059125869557774470898576295502988586205239377762486299244403317563706594 832 337467291449099146757502470290836158590234343320848346916393368492084016526053835309718655151992113871219648483672951186416690553446928534675098781707516012681429879198633659 833 546033547656009174730674260178697529181566826742595116557615426054050886609185420118390127275416749213278774353230725657315266848949917120880338159470002311925833196762340253 834 883500839105108321488176730469533687771801170063443463474008794546134903135239255428108782427408863084498422836903676843731957402396845655555436941177518324607263075960973912 835 1429534386761117496218850990648231216953367996806038580031624220600185789744424675546498909702825612297777197190134402501047224251346762776435775100647520636533096272723314165 836 2313035225866225817707027721117764904725169166869482043505633015146320692879663930974607692130234475382275620027038079344779181653743608431991212041825038961140359348684288077 837 3742569612627343313925878711765996121678537163675520623537257235746506482624088606521106601833060087680052817217172481845826405905090371208426987142472559597673455621407602242 838 6055604838493569131632906432883761026403706330545002667042890250892827175503752537495714293963294563062328437244210561190605587558833979640418199184297598558813814970091890319 839 9798174451120912445558785144649757148082243494220523290580147486639333658127841144016820895796354650742381254461383043036431993463924350848845186326770158156487270591499492561 840 15853779289614481577191691577533518174485949824765525957623037737532160833631593681512535189759649213804709691705593604227037581022758330489263385511067756715301085561591382880 841 25651953740735394022750476722183275322568193318986049248203185224171494491759434825529356085556003864547090946166976647263469574486682681338108571837837914871788356153090875441 842 41505733030349875599942168299716793497054143143751575205826222961703655325391028507041891275315653078351800637872570251490507155509441011827371957348905671587089441714682258321 843 67157686771085269622692645021900068819622336462737624454029408185875149817150463332571247360871656942898891584039546898753976729996123693165480529186743586458877797867773133762 844 108663419801435145222634813321616862316676479606489199659855631147578805142541491839613138636187310021250692221912117150244483885505564704992852486535649258045967239582455392083 845 175821106572520414845327458343516931136298816069226824113885039333453954959691955172184385997058966964149583805951664048998460615501688398158333015722392844504845037450228525845 846 284484526373955560067962271665133793452975295675716023773740670481032760102233447011797524633246276985400276027863781199242944501007253103151185502258042102550812277032683917928 847 460305632946475974913289730008650724589274111744942847887625709814486715061925402183981910630305243949549859833815445248241405116508941501309518517980434947055657314482912443773 848 744790159320431534981252001673784518042249407420658871661366380295519475164158849195779435263551520934950135861679226447484349617516194604460704020238477049606469591515596361701 849 1205095792266907509894541731682435242631523519165601719548992090110006190226084251379761345893856764884499995695494671695725754734025136105770222538218911996662126905998508805474 850 1949885951587339044875793733356219760673772926586260591210358470405525665390243100575540781157408285819450131557173898143210104351541330710230926558457389046268596497514105167175 851 3154981743854246554770335465038655003305296445751862310759350560515531855616327351955302127051265050703950127252668569838935859085566466816001149096676301042930723403512613972649 852 5104867695441585599646129198394874763979069372338122901969709030921057521006570452530842908208673336523400258809842467982145963437107797526232075655133690089199319901026719139824 853 8259849439295832154416464663433529767284365818089985212729059591436589376622897804486145035259938387227350386062511037821081822522674264342233224751809991132130043304539333112473 854 13364717134737417754062593861828404531263435190428108114698768622357646897629468257016987943468611723750750644872353505803227785959782061868465300406943681221329363205566052252297 855 21624566574033249908479058525261934298547801008518093327427828213794236274252366061503132978728550110978101030934864543624309608482456326210698525158753672353459406510105385364770 856 34989283708770667662541652387090338829811236198946201442126596836151883171881834318520120922197161834728851675807218049427537394442238388079163825565697353574788769715671437617067 857 56613850282803917571020710912352273128359037207464294769554425049946119446134200380023253900925711945706952706742082593051847002924694714289862350724451025928248176225776822981837 858 91603133991574585233562363299442611958170273406410496211681021886098002618016034698543374823122873780435804382549300642479384397366933102369026176290148379503036945941448260598904 859 148216984274378502804583074211794885086529310613874790981235446936044122064150235078566628724048585726142757089291383235531231400291627816658888527014599405431285122167225083580741 860 239820118265953088038145437511237497044699584020285287192916468822142124682166269777110003547171459506578561471840683878010615797658560919027914703304747784934322068108673344179645 861 388037102540331590842728511723032382131228894634160078174151915758186246746316504855676632271220045232721318561132067113541847197950188735686803230319347190365607190275898427760386 862 627857220806284678880873949234269879175928478654445365367068384580328371428482774632786635818391504739299880032972750991552462995608749654714717933624094975299929258384571771940031 863 1015894323346616269723602460957302261307157373288605443541220300338514618174799279488463268089611549972021198594104818105094310193558938390401521163943442165665536448660470199700417 864 1643751544152900948604476410191572140483085851943050808908288684918842989603282054121249903908003054711321078627077569096646773189167688045116239097567537140965465707045041971640448 865 2659645867499517218328078871148874401790243225231656252449508985257357607778081333609713171997614604683342277221182387201741083382726626435517760261510979306631002155705512171340865 866 4303397411652418166932555281340446542273329077174707061357797670176200597381363387730963075905617659394663355848259956298387856571894314480633999359078516447596467862750554142981313 867 6963043279151935385260634152489320944063572302406363313807306655433558205159444721340676247903232264078005633069442343500128939954620940916151759620589495754227470018456066314322178 868 11266440690804353552193189433829767486336901379581070375165104325609758802540808109071639323808849923472668988917702299798516796526515255396785758979668012201823937881206620457303491 869 18229483969956288937453823586319088430400473681987433688972410981043317007700252830412315571712082187550674621987144643298645736481136196312937518600257507956051407899662686771625669 870 29495924660760642489647013020148855916737375061568504064137515306653075810241060939483954895520932111023343610904846943097162533007651451709723277579925520157875345780869307228929160 871 47725408630716931427100836606467944347137848743555937753109926287696392817941313769896270467233014298574018232891991586395808269488787648022660796180183028113926753680531994000554829 872 77221333291477573916747849626616800263875223805124441817247441594349468628182374709380225362753946409597361843796838529492970802496439099732384073760108548271802099461401301229483989 873 124946741922194505343848686233084744611013072548680379570357367882045861446123688479276495829986960708171380076688830115888779071985226747755044869940291576385728853141933295230038818 874 202168075213672079260596535859701544874888296353804821387604809476395330074306063188656721192740907117768741920485668645381749874481665847487428943700400124657530952603334596459522807 875 327114817135866584604445222092786289485901368902485200957962177358441191520429751667933217022727867825940121997174498761270528946466892595242473813640691701043259805745267891689561625 876 529282892349538663865041757952487834360789665256290022345566986834836521594735814856589938215468774943708863917660167406652278820948558442729902757341091825700790758348602488149084432 877 856397709485405248469486980045274123846691034158775223303529164193277713115165566524523155238196642769648985914834666167922807767415451037972376570981783526744050564093870379838646057 878 1385680601834943912334528737997761958207480699415065245649096151028114234709901381381113093453665417713357849832494833574575086588364009480702279328322875352444841322442472867987730489 879 2242078311320349160804015718043036082054171733573840468952625315221391947825066947905636248691862060483006835747329499742497894355779460518674655899304658879188891886536343247826376546 880 3627758913155293073138544456040798040261652432988905714601721466249506182534968329286749342145527478196364685579824333317072980944143469999376935227627534231633733208978816115814107035 881 5869837224475642233942560174083834122315824166562746183554346781470898130360035277192385590837389538679371521327153833059570875299922930518051591126932193110822625095515159363640483581 882 9497596137630935307081104630124632162577476599551651898156068247720404312895003606479134932982917016875736206906978166376643856244066400517428526354559727342456358304493975479454590616 883 15367433362106577541023664804208466284893300766114398081710415029191302443255038883671520523820306555555107728234131999436214731543989331035480117481491920453278983400009134843095074197 884 24865029499737512848104769434333098447470777365666049979866483276911706756150042490150655456803223572430843935141110165812858587788055731552908643836051647795735341704503110322549664813 885 40232462861844090389128434238541564732364078131780448061576898306103009199405081373822175980623530127985951663375242165249073319332045062588388761317543568249014325104512245165644739010 886 65097492361581603237233203672874663179834855497446498041443381583014715955555123863972831437426753700416795598516352331061931907120100794141297405153595216044749666809015355488194403823 887 105329955223425693626361637911416227912198933629226946103020279889117725154960205237795007418050283828402747261891594496311005226452145856729686166471138784293763991913527600653839142833 888 170427447585007296863594841584290891092033789126673444144463661472132441110515329101767838855477037528819542860407946827372937133572246650870983571624734000338513658722542956142033546656 889 275757402808432990489956479495707119004232722755900390247483941361250166265475534339562846273527321357222290122299541323683942360024392507600669738095872784632277650636070556795872689489 890 446184850393440287353551321079998010096266511882573834391947602833382607375990863441330685129004358886041832982707488151056879493596639158471653309720606784970791309358613512937906236145 891 721942253201873277843507800575705129100499234638474224639431544194632773641466397780893531402531680243264123105007029474740821853621031666072323047816479569603068959994684069733778925634 892 1168127103595313565197059121655703139196765746521048059031379147028015381017457261222224216531536039129305956087714517625797701347217670824543976357537086354573860269353297582671685161779 893 1890069356797186843040566922231408268297264981159522283670810691222648154658923659003117747934067719372570079192721547100538523200838702490616299405353565924176929229347981652405464087413 894 3058196460392500408237626043887111407494030727680570342702189838250663535676380920225341964465603758501876035280436064726336224548056373315160275762890652278750789498701279235077149249192 895 4948265817189687251278192966118519675791295708840092626373000529473311690335304579228459712399671477874446114473157611826874747748895075805776575168244218202927718728049260887482613336605 896 8006462277582187659515819010005631083285326436520662969075190367723975226011685499453801676865275236376322149753593676553210972296951449120936850931134870481678508226750540122559762585797 897 12954728094771874910794011976124150759076622145360755595448190897197286916346990078682261389264946714250768264226751288380085720045846524926713426099379088684606226954799801010042375922402 898 20961190372354062570309830986129781842361948581881418564523381264921262142358675578136063066130221950627090413980344964933296692342797974047650277030513959166284735181550341132602138508199 899 33915918467125937481103842962253932601438570727242174159971572162118549058705665656818324455395168664877858678207096253313382412388644498974363703129893047850890962136350142142644514430601 900 54877108839480000051413673948383714443800519309123592724494953427039811201064341234954387521525390615504949092187441218246679104731442473022013980160407007017175697317900483275246652938800 901 88793027306605937532517516910637647045239090036365766884466525589158360259770006891772711976920559280382807770394537471560061517120086971996377683290300054868066659454250625417891167369401 902 143670136146085937583931190859021361489039609345489359608961479016198171460834348126727099498445949895887756862581978689806740621851529445018391663450707061885242356772151108693137820308201 903 232463163452691875116448707769659008534278699381855126493428004605356531720604355018499811475366509176270564632976516161366802138971616417014769346741007116753309016226401734111028987677602 904 376133299598777812700379898628680370023318308727344486102389483621554703181438703145226910973812459072158321495558494851173542760823145862033161010191714178638551372998552842804166807985803 905 608596463051469687816828606398339378557597008109199612595817488226911234902043058163726722449178968248428886128535011012540344899794762279047930356932721295391860389224954576915195795663405 906 984729762650247500517208505027019748580915316836544098698206971848465938083481761308953633422991427320587207624093505863713887660617908141081091367124435474030411762223507419719362603649208 907 1593326225701717188334037111425359127138512324945743711294024460075377172985524819472680355872170395569016093752628516876254232560412670420129021724057156769422272151448461996634558399312613 908 2578055988351964688851245616452378875719427641782287809992231431923843111069006580781633989295161822889603301376722022739968120221030578561210113091181592243452683913671969416353921002961821 909 4171382214053681877185282727877738002857939966728031521286255891999220284054531400254314345167332218458619395129350539616222352781443248981339134815238749012874956065120431412988479402274434 910 6749438202405646566036528344330116878577367608510319331278487323923063395123537981035948334462494041348222696506072562356190473002473827542549247906420341256327639978792400829342400405236255 911 10920820416459328443221811072207854881435307575238350852564743215922283679178069381290262679629826259806842091635423101972412825783917076523888382721659090269202596043912832242330879807510689 912 17670258618864975009258339416537971760012675183748670183843230539845347074301607362326211014092320301155064788141495664328603298786390904066437630628079431525530236022705233071673280212746944 913 28591079035324303452480150488745826641447982758987021036407973755767630753479676743616473693722146560961906879776918766301016124570307980590326013349738521794732832066618065314004160020257633 914 46261337654189278461738489905283798401460657942735691220251204295612977827781284105942684707814466862116971667918414430629619423356698884656763643977817953320263068089323298385677440233004577 915 74852416689513581914218640394029625042908640701722712256659178051380608581260960849559158401536613423078878547695333196930635547927006865247089657327556475114995900155941363699681600253262210 916 121113754343702860375957130299313423444369298644458403476910382346993586409042244955501843109351080285195850215613747627560254971283705749903853301305374428435258968245264662085359040486266787 917 195966171033216442290175770693343048487277939346181115733569560398374194990303205805061001510887693708274728763309080824490890519210712615150942958632930903550254868401206025785040640739528997 918 317079925376919302666132900992656471931647237990639519210479942745367781399345450760562844620238773993470578978922828452051145490494418365054796259938305331985513836646470687870399681225795784 919 513046096410135744956308671685999520418925177336820634944049503143741976389648656565623846131126467701745307742231909276542036009705130980205739218571236235535768705047676713655440321965324781 920 830126021787055047622441572678655992350572415327460154154529445889109757788994107326186690751365241695215886721154737728593181500199549345260535478509541567521282541694147401525840003191120565 921 1343172118197190792578750244364655512769497592664280789098578949032851734178642763891810536882491709396961194463386647005135217509904680325466274697080777803057051246741824115181280325156445346 922 2173298139984245840201191817043311505120070007991740943253108394921961491967636871217997227633856951092177081184541384733728399010104229670726810175590319370578333788435971516707120328347565911 923 3516470258181436632779942061407967017889567600656021732351687343954813226146279635109807764516348660489138275647928031738863616520008909996193084872671097173635385035177795631888400653504011257 924 5689768398165682472981133878451278523009637608647762675604795738876774718113916506327804992150205611581315356832469416472592015530113139666919895048261416544213718823613767148595520981851577168 925 9206238656347119105761075939859245540899205209303784407956483082831587944260196141437612756666554272070453632480397448211455632050122049663112979920932513717849103858791562780483921635355588425 926 14896007054512801578742209818310524063908842817951547083561278821708362662374112647765417748816759883651768989312866864684047647580235189330032874969193930262062822682405329929079442617207165593 927 24102245710859920684503285758169769604808048027255331491517761904539950606634308789203030505483314155722222621793264312895503279630357238993145854890126443979911926541196892709563364252562754018 928 38998252765372722263245495576480293668716890845206878575079040726248313269008421436968448254300074039373991611106131177579550927210592428323178729859320374241974749223602222638642806869769919611 929 63100498476232642947748781334650063273524938872462210066596802630788263875642730226171478759783388195096214232899395490475054206840949667316324584749446818221886675764799115348206171122332673629 930 102098751241605365210994276911130356942241829717669088641675843357036577144651151663139927014083462234470205844005526668054605134051542095639503314608767192463861424988401337986848977992102593240 931 165199249717838008158743058245780420215766768590131298708272645987824841020293881889311405773866850429566420076904922158529659340892491762955827899358214010685748100753200453335055149114435266869 932 267298000959443373369737335156910777158008598307800387349948489344861418164945033552451332787950312664036625920910448826584264474944033858595331213966981203149609525741601791321904127106537860109 933 432497250677281381528480393402691197373775366897931686058221135332686259185238915441762738561817163093603045997815370985113923815836525621551159113325195213835357626494802244656959276220973126978 934 699795251636724754898217728559601974531783965205732073408169624677547677350183948994214071349767475757639671918725819811698188290780559480146490327292176416984967152236404035978863403327510987087 935 1132292502314006136426698121962293171905559332103663759466390760010233936535422864435976809911584638851242717916541190796812112106617085101697649440617371630820324778731206280635822679548484114065 936 1832087753950730891324915850521895146437343297309395832874560384687781613885606813430190881261352114608882389835267010608510300397397644581844139767909548047805291930967610316614686082875995101152 937 2964380256264737027751613972484188318342902629413059592340951144698015550421029677866167691172936753460125107751808201405322412504014729683541789208526919678625616709698816597250508762424479215217 938 4796468010215467919076529823006083464780245926722455425215511529385797164306636491296358572434288868069007497587075212013832712901412374265385928976436467726430908640666426913865194845300474316369 939 7760848266480204946828143795490271783123148556135515017556462674083812714727666169162526263607225621529132605338883413419155125405427103948927718184963387405056525350365243511115703607724953531586 940 12557316276695672865904673618496355247903394482857970442771974203469609879034302660458884836041514489598140102925958625432987838306839478214313647161399855131487433991031670424980898453025427847955 941 20318164543175877812732817413986627031026543038993485460328436877553422593761968829621411099648740111127272708264842038852142963712266582163241365346363242536543959341396913936096602060750381379541 942 32875480819871550678637491032482982278929937521851455903100411081023032472796271490080295935690254600725412811190800664285130802019106060377555012507763097668031393332428584361077500513775809227496 943 53193645363047428491370308446469609309956480560844941363428847958576455066558240319701707035338994711852685519455642703137273765731372642540796377854126340204575352673825498297174102574526190607037 944 86069126182918979170007799478952591588886418082696397266529259039599487539354511809782002971029249312578098330646443367422404567750478702918351390361889437872606746006254082658251603088301999834533 945 139262771545966407661378107925422200898842898643541338629958106998175942605912752129483710006368244024430783850102086070559678333481851345459147768216015778077182098680079580955425705662828190441570 946 225331897728885386831385907404374792487729316726237735896487366037775430145267263939265712977397493337008882180748529437982082901232330048377499158577905215949788844686333663613677308751130190276103 947 364594669274851794492764015329796993386572215369779074526445473035951372751180016068749422983765737361439666030850615508541761234714181393836646926793920994026970943366413244569103014413958380717673 948 589926567003737181324149922734171785874301532096016810422932839073726802896447280008015135961163230698448548211599144946523844135946511442214146085371826209976759788052746908182780323165088570993776 949 954521236278588975816913938063968779260873747465795884949378312109678175647627296076764558944928968059888214242449760455065605370660692836050793012165747204003730731419160152751883337579046951711449 950 1544447803282326157141063860798140565135175279561812695372311151183404978544074576084779694906092198758336762454048905401589449506607204278264939097537573413980490519471907060934663660744135522705225 951 2498969039560915132957977798862109344396049027027608580321689463293083154191701872161544253851021166818224976696498665856655054877267897114315732109703320617984221250891067213686546998323182474416674 952 4043416842843241290099041659660249909531224306589421275694000614476488132735776448246323948757113365576561739150547571258244504383875101392580671207240894031964711770362974274621210659067317997121899 953 6542385882404156423057019458522359253927273333617029856015690077769571286927478320407868202608134532394786715847046237114899559261142998506896403316944214649948933021254041488307757657390500471538573 954 10585802725247397713156061118182609163458497640206451131709690692246059419663254768654192151365247897971348454997593808373144063645018099899477074524185108681913644791617015762928968316457818468660472 955 17128188607651554136213080576704968417385770973823480987725380770015630706590733089062060353973382430366135170844640045488043622906161098406373477841129323331862577812871057251236725973848318940199045 956 27713991332898951849369141694887577580844268614029932119435071462261690126253987857716252505338630328337483625842233853861187686551179198305850552365314432013776222604488073014165694290306137408859517 957 44842179940550505985582222271592545998230039587853413107160452232277320832844720946778312859312012758703618796686873899349231309457340296712224030206443755345638800417359130265402420264154456349058562 958 72556171273449457834951363966480123579074308201883345226595523694539010959098708804494565364650643087041102422529107753210418996008519495018074582571758187359415023021847203279568114554460593757918079 959 117398351213999963820533586238072669577304347789736758333755975926816331791943429751272878223962655845744721219215981652559650305465859791730298612778201942705053823439206333544970534818615050106976641 960 189954522487449421655484950204552793156378655991620103560351499621355342751042138555767443588613298932785823641745089405770069301474379286748373195349960130064468846461053536824538649373075643864894720 961 307352873701449385476018536442625462733683003781356861894107475548171674542985568307040321812575954778530544860961071058329719606940239078478671808128162072769522669900259870369509184191690693971871361 962 497307396188898807131503486647178255890061659772976965454458975169527017294027706862807765401189253711316368502706160464099788908414618365227045003478122202833991516361313407194047833564766337836766081 963 804660269890348192607522023089803718623744663554333827348566450717698691837013275169848087213765208489846913363667231522429508515354857443705716811606284275603514186261573277563557017756457031808637442 964 1301967666079246999739025509736981974513806323327310792803025425887225709131040982032655852614954462201163281866373391986529297423769475808932761815084406478437505702622886684757604851321223369645403523 965 2106627935969595192346547532826785693137550986881644620151591876604924400968054257202503939828719670691010195230040623508958805939124333252638478626690690754041019888884459962321161869077680401454040965 966 3408595602048842192085573042563767667651357310208955412954617302492150110099095239235159792443674132892173477096414015495488103362893809061571240441775097232478525591507346647078766720398903771099444488 967 5515223538018437384432120575390553360788908297090600033106209179097074511067149496437663732272393803583183672326454639004446909302018142314209719068465787986519545480391806609399928589476584172553485453 968 8923819140067279576517693617954321028440265607299555446060826481589224621166244735672823524716067936475357149422868654499935012664911951375780959510240885218998071071899153256478695309875487943652929941 969 14439042678085716960949814193344874389229173904390155479167035660686299132233394232110487256988461740058540821749323293504381921966930093689990678578706673205517616552290959865878623899352072116206415394 970 23362861818152996537467507811299195417669439511689710925227862142275523753399638967783310781704529676533897971172191948004316934631842045065771638088947558424515687624190113122357319209227560059859345335 971 37801904496238713498417322004644069806898613416079866404394897802961822885633033199893798038692991416592438792921515241508698856598772138755762316667654231630033304176481072988235943108579632176065760729 972 61164766314391710035884829815943265224568052927769577329622759945237346639032672167677108820397521093126336764093707189513015791230614183821533954756601790054548991800671186110593262317807192235925106064 973 98966670810630423534302151820587335031466666343849443734017657748199169524665705367570906859090512509718775557015222431021714647829386322577296271424256021684582295977152259098829205426386824411990866793 974 160131437125022133570186981636530600256034719271619021063640417693436516163698377535248015679488033602845112321108929620534730439060000506398830226180857811739131287777823445209422467744194016647915972857 975 259098107935652557104489133457117935287501385615468464797658075441635685688364082902818922538578546112563887878124152051556445086889386828976126497605113833423713583754975704308251673170580841059906839650 976 419229545060674690674676115093648535543536104887087485861298493135072201852062460438066938218066579715409000199233081672091175525949387335374956723785971645162844871532799149517674140914774857707822812507 977 678327652996327247779165248550766470831037490502555950658956568576707887540426543340885860756645125827972888077357233723647620612838774164351083221391085478586558455287774853825925814085355698767729652157 978 1097557198057001938453841363644415006374573595389643436520255061711780089392489003778952798974711705543381888276590315395738796138788161499726039945177057123749403326820574003343599955000130556475552464664 979 1775884851053329186233006612195181477205611085892199387179211630288487976932915547119838659731356831371354776353947549119386416751626935664077123166568142602335961782108348857169525769085486255243282116821 980 2873442049110331124686847975839596483580184681281842823699466692000268066325404550898791458706068536914736664630537864515125212890415097163803163111745199726085365108928922860513125724085616811718834581485 981 4649326900163660310919854588034777960785795767174042210878678322288756043258320098018630118437425368286091440984485413634511629642042032827880286278313342328421326891037271717682651493171103066962116698306 982 7522768949273991435606702563874374444365980448455885034578145014289024109583724648917421577143493905200828105615023278149636842532457129991683449390058542054506691999966194578195777217256719878680951279791 983 12172095849437651746526557151909152405151776215629927245456823336577780152842044746936051695580919273486919546599508691784148472174499162819563735668371884382928018891003466295878428710427822945643067978097 984 19694864798711643182133259715783526849517756664085812280034968350866804262425769395853473272724413178687747652214531969933785314706956292811247185058430426437434710890969660874074205927684542824324019257888 985 31866960648149294928659816867692679254669532879715739525491791687444584415267814142789524968305332452174667198814040661717933786881455455630810920726802310820362729781973127169952634638112365769967087235985 986 51561825446860938110793076583476206104187289543801551805526760038311388677693583538642998241029745630862414851028572631651719101588411748442058105785232737257797440672942788044026840565796908594291106493873 987 83428786095010233039452893451168885358856822423517291331018551725755973092961397681432523209335078083037082049842613293369652888469867204072869026512035048078160170454915915213979475203909274364258193729858 988 134990611541871171150245970034645091463044111967318843136545311764067361770654981220075521450364823713899496900871185925021371990058278952514927132297267785335957611127858703258006315769706182958549300223731 989 218419397636881404189698863485813976821900934390836134467563863489823334863616378901508044659699901796936578950713799218391024878528146156587796158809302833414117781582774618471985790973615457322807493953589 990 353410009178752575339944833520459068284945046358154977604109175253890696634271360121583566110064725510836075851584985143412396868586425109102723291106570618750075392710633321729992106743321640281356794177320 991 571829406815633979529643697006273045106845980748991112071673038743714031497887739023091610769764627307772654802298784361803421747114571265690519449915873452164193174293407940201977897716937097604164288130909 992 925239415994386554869588530526732113391791027107146089675782213997604728132159099144675176879829352818608730653883769505215818615700996374793242741022444070914268567004041261931970004460258737885521082308229 993 1497068822810020534399232227533005158498637007856137201747455252741318759630046838167766787649593980126381385456182553867019240362815567640483762190938317523078461741297449202133947902177195835489685370439138 994 2422308238804407089268820758059737271890428034963283291423237466738923487762205937312441964529423332944990116110066323372235058978516564015277004931960761593992730308301490464065917906637454573375206452747367 995 3919377061614427623668052985592742430389065042819420493170692719480242247392252775480208752179017313071371501566248877239254299341332131655760767122899079117071192049598939666199865808814650408864891823186505 996 6341685300418834712936873743652479702279493077782703784593930186219165735154458712792650716708440646016361617676315200611489358319848695671037772054859840711063922357900430130265783715452104982240098275933872 997 10261062362033262336604926729245222132668558120602124277764622905699407982546711488272859468887457959087733119242564077850743657661180827326798539177758919828135114407499369796465649524266755391104990099120377 998 16602747662452097049541800472897701834948051198384828062358553091918573717701170201065510185595898605104094736918879278462233015981029522997836311232618760539199036765399799926731433239718860373345088375054249 999 26863810024485359386146727202142923967616609318986952340123175997617981700247881689338369654483356564191827856161443356312976673642210350324634850410377680367334151172899169723197082763985615764450078474174626
lecture_notes/lec3.ipynb
###Markdown Lecutre 3 Recall:TODO:1. Define a loss function that quantifies our unhappiness with the scors across the training data2. Come up with a way of efficiently finding the parameters that minimize the loss function (optimization) Loss FunctionA loss function tells how good our current classifier is.Given a dataset of examples$$\{(x_i, y_i)\}^N _{i=1}$$where $x_i$ is an image and $y_i$ is an integer label.Loss over the dataset is a sum of loss over examples:$$L = \frac{1}{N} \sum _i L_i(f(x_i, W), y_i)$$ Multi-class SVM LossLet s be the predicted score coming out of the classifier $s = f(x_i, W)$For example, if our classes were 1 for cat and 2 for dog, then $s_1$ and $s_2$ would be cat and dog scores respectively.$y_i$ was the category of the ground truth label, which is some integer.SO then $s_{y_i}$ would correspond to the score of the **true class** for the i'th example in the training set.The SVM has the form:if $$s_{y_i} \geq s_j + 1$$then $$L_i = \sum_{j \neq y_i} = 0$$otherwise$$L_i = \sum_{j\neq y_i} s_j - s_{y_i} + 1$$In summary:$$L_i = \sum_{j\neq y_i} max(0, s_j - s_{y_i} + 1)$$ Q1: What's the min/max possible loss for SVM?A: Our min loss is 0, if across all our classes our loss was 0.Our max loss is infinity. Recall the hinge joint function Q2: At initialization W is small so all $s \approx 0$. What is the loss?A: About $c-1$, where c is the number of classes. This is because for each class, if we loop over all incorrect classes, each pairing will have an $s$ that are about the same, so we'll get a loss of 1 as defined in our function (the safety margin).So, we'll get $c-1$, 1's.This is also a useful debugging tool, that you can use as a sanity check at the beginning of training to make sure your code isn't broken. Q3: What is the sum was over all classes, including $j = y_i$?A: The loss increases by 1. (So now $C$ instead of $C-1$)Q4: What if we used mean instead of sum here?$L_i = \sum_{j\neq y_i} max(0, s_j - s_{y_i} + 1)$A: Answer wouldn't change. The number of classes is fixed ahead of time when picking the dataset. Remember, we don't actually care about the true values of the scores/loss, only that the scores are higher for the accurate label.Q5: What if we used squared loss?$L_i = \sum_{j\neq y_i} max(0, s_j - s_{y_i} + 1) ^2$A: This would be different. We trade good/badness in a nonlinear way, so it would compute a different loss function.Looks like a squared hinge loss.Q6: When squared over not squared?A: Things that are very bad will now be very very bad. So use squared for cases where you don't want huge misclassifications. Multiclass SVM (Support Vector Machine) LossExample code:$$L_i = \sum_{j\neq y_i} max(0, s_j - s_{y_i} + 1)$$ ###Code import numpy as np def L_i_vectorized(x, y, W): scores = W.dot(x) margins = np.maximum(0, scores - scores[y] + 1) margins[y] = 0 loss_i = np.sum(margins) return loss_i ###Output _____no_output_____ ###Markdown Suppose that we found a W such that L = 0. Is this W unique?Recall:$$f(x, W) = Wx$$$$L = \frac{1}{N} \sum^N_{i=1} \sum_{j\neq y_i} max(0, s_j - s_{y_i} + 1)$$Answer: **NO!** Not unique. For example, $2W$ is also now $L=0$. RegularizationData loss: model predictions should match training dataRegularization: Model should be "simple", so it works on test data. AKA, we don't want to overfit our training data.So, we introduce a new term in our loss function:$$L(W) = \frac{1}{N} \sum^N_{i=1} L_i(f(x_i, W), y_i) + \lambda R(W)$$ Occam's Razor:"Among competing hypotheses, the simplest is best"William of Ockahm, 1285-1347. Regularization Types$\lambda = $ regularization strength (**hyperparameter**)$$L = \frac{1}{N} \sum^N_{i=1} \sum_{j\neq y_i} max(0, f(x_i; W)_j - f(x_i;W)_{y_i} + 1) + \lambda R(W)$$ In common use:**L2 regularization** $R(W) = \sum_k \sum_l W^2 _{k,l}$L1 regularization $R(W) = \sum_k \sum_l |W _{k,l}|$Elastic net (L1 + L2) $R(W) = \sum_k \sum_l \beta W^2 _{k,l} + |W _{k,l}|$Max norm regularization (might see later)Dropout (will see later)Fancier: Batch normalization, stocastic depth---A nice way of thinking about L1 vs L2 is:L1 prefers spare solutions, that drives all your entries of W to 0 except for a couple. L2 prefers to spread the W across all the values. Softmax ClassifierAKA: Multinominal Logistic Regressionscores = unnormalized log probabilities of the classes.$$P(Y=k|X=x_i) = \frac{e^{s_k} }{\sum_j e^{s_j}}$$where $s = f(x_i;W)$We want to maximize the log liklihood, or (for a loss function), to minimize the negative log likelihood of the correct class:$$L_i = -\log P(Y=y_i | X= x_i)$$ Q1: Sanity check: if all the s's are small and about 0, what is the loss?A: $-\log(\frac{1}{C}) = \log(C)$An interesting difference between softmax and SVM: SVM will not care once a point is correctly classified. Softmax will always want you to push the score of the correct class to infiity. Recap- We have some dataset of (x,y)- We have a score function- We have a loss function (many choices: Softmax, SVM, Full loss) OptimizationE.g. mountain:Slope in any direction is dot product of direction with gradient.Direction of steepest descent is negative gradient.Summary:- Numerical gradient: approximate, slow, easy to write- Analytic gradient: exact, fast, error-proneIn practice, always use analytic gradient, but check implementation with a numerical gradient. This is called a gradient check. Gradient Descent ###Code # Vanila gradient descent while True: weights_grad = evaluate_gradient(loss_fun, data, weights) weights += - step_size * weights_grad # performs parameter update ###Output _____no_output_____ ###Markdown step_size is an important hyperparameter - this is commonly known as the **learning rate**.There are also different update rules which tell us how exactly to use the gradient information at every time step (e.g. Adam, SGD, etc.) Stochastic Gradient Descent (SGD)Full sum for our loss function over every single image is slow and costly.What we can instead do is approximate using a **minibatch** of examples (32, 64, 128 are common) ###Code # Vanilla Minibatch Gradient Descent while True: data_batch = sample_training_data(data, 256) weights_grad = evaluate_gradient(loss_fun, data_batch, weights) weights += - step_size * weights_grad ###Output _____no_output_____
simulations/notebooks_sim_cts/0.2_sim_indepdent_elnet_cts.ipynb
###Markdown summarize elastic net results on Independent Simulation Scenarios for continuous outcome ###Code dir = '/panfs/panfs1.ucsd.edu/panscratch/lij014/Stability_2020/sim_data' load(paste0(dir, '/independent_Elnet.RData')) dim.list = list() size = c(50, 100, 500, 1000) idx = 0 for (P in size){ for (N in size){ idx = idx + 1 dim.list[[idx]] = c(P=P, N=N) } } files = NULL for (dim in dim.list){ p = dim[1] n = dim[2] files = cbind(files, paste0(dir, '/sim_independent_', paste('P', p, 'N', n, sep='_'), '.RData')) } avg_FDR = NULL for (i in 1:length(files)){ sim_file = files[i] load(sim_file, dat <- new.env()) sub = dat$sim_array[[i]] p = sub$p # take true values from 1st replicate of each simulated data coef = sub$beta coef.true = which(coef != 0) tt = results_ind_elnet[[i]]$Stab.table FDR = NULL for (r in 1:nrow(tt)){ FDR = c(FDR, length(setdiff(which(tt[r, ] !=0), coef.true))/sum(tt[r, ])) } avg_FDR = c(avg_FDR, mean(FDR, na.rm=T)) } table_ind = NULL tmp_num_select = rep(0, length(results_ind_elnet)) for (i in 1:length(results_ind_elnet)){ table_ind = rbind(table_ind, results_ind_elnet[[i]][c('n', 'p', 'rou', 'FP', 'FN', 'MSE', 'Stab')]) tmp_num_select[i] = mean(rowSums(results_ind_elnet[[i]]$Stab.table)) } table_ind = as.data.frame(table_ind) table_ind$num_select = tmp_num_select table_ind$FDR = round(avg_FDR,2) head(table_ind) # export result result.table_ind <- apply(table_ind,2,as.character) rownames(result.table_ind) = rownames(table_ind) result.table_ind = as.data.frame(result.table_ind) # extract numbers only for 'n' & 'p' result.table_ind$n = tidyr::extract_numeric(result.table_ind$n) result.table_ind$p = tidyr::extract_numeric(result.table_ind$p) result.table_ind$ratio = result.table_ind$p / result.table_ind$n result.table_ind = result.table_ind[c('n', 'p', 'ratio', 'Stab', 'MSE', 'FP', 'FN', 'num_select', 'FDR')] colnames(result.table_ind)[1:3] = c('N', 'P', 'Ratio') # convert interested measurements to be numeric result.table_ind$Stab = as.numeric(as.character(result.table_ind$Stab)) result.table_ind$MSE_mean = as.numeric(substr(result.table_ind$MSE, start=1, stop=4)) result.table_ind$FP_mean = as.numeric(substr(result.table_ind$FP, start=1, stop=4)) result.table_ind$FN_mean = as.numeric(substr(result.table_ind$FN, start=1, stop=4)) result.table_ind$FN_mean[is.na(result.table_ind$FN_mean)] = 0 result.table_ind$num_select = as.numeric(as.character(result.table_ind$num_select)) result.table_ind ## export write.table(result.table_ind, '../results_summary_cts/sim_ind_elnet.txt', sep='\t', row.names=F) ###Output _____no_output_____
odu/odu_solutions_py.ipynb
###Markdown quant-econ Solutions: Search with Unknown Offer Distribution Solutions for http://quant-econ.net/py/odu.html ###Code %matplotlib inline import numpy as np import matplotlib.pyplot as plt from quantecon import compute_fixed_point from odu import SearchProblem ###Output _____no_output_____ ###Markdown Exercise 1 This code solves the "Offer Distribution Unknown" model by iterating on a guess of thereservation wage function. You should find that the run time is much shorter than that of the value function approach in `odu_vfi.py` ###Code sp = SearchProblem(pi_grid_size=50) phi_init = np.ones(len(sp.pi_grid)) w_bar = compute_fixed_point(sp.res_wage_operator, phi_init) fig, ax = plt.subplots(figsize=(9, 7)) ax.plot(sp.pi_grid, w_bar, linewidth=2, color='black') ax.set_ylim(0, 2) ax.grid(axis='x', linewidth=0.25, linestyle='--', color='0.25') ax.grid(axis='y', linewidth=0.25, linestyle='--', color='0.25') ax.fill_between(sp.pi_grid, 0, w_bar, color='blue', alpha=0.15) ax.fill_between(sp.pi_grid, w_bar, 2, color='green', alpha=0.15) ax.text(0.42, 1.2, 'reject') ax.text(0.7, 1.8, 'accept') plt.show() ###Output Iteration Distance Elapsed (seconds) --------------------------------------------- 5 2.829e-02 2.087e-01 10 5.174e-03 3.894e-01 15 9.652e-04 5.700e-01 ###Markdown The next piece of code is not one of the exercises from quant-econ, it's just a fun simulation to see what the effect of a change in the underlying distribution on the unemployment rate is.At a point in the simulation, the distribution becomes significantly worse. It takes a while for agents to learn this, and in the meantime they are too optimistic, and turn down too many jobs. As a result, the unemployment rate spikes.The code takes a few minutes to run. ###Code from scipy import interp # Set up model and compute the function w_bar sp = SearchProblem(pi_grid_size=50, F_a=1, F_b=1) pi_grid, f, g, F, G = sp.pi_grid, sp.f, sp.g, sp.F, sp.G phi_init = np.ones(len(sp.pi_grid)) w_bar_vals = compute_fixed_point(sp.res_wage_operator, phi_init) w_bar = lambda x: interp(x, pi_grid, w_bar_vals) class Agent(object): """ Holds the employment state and beliefs of an individual agent. """ def __init__(self, pi=1e-3): self.pi = pi self.employed = 1 def update(self, H): "Update self by drawing wage offer from distribution H." if self.employed == 0: w = H.rvs() if w >= w_bar(self.pi): self.employed = 1 else: self.pi = 1.0 / (1 + ((1 - self.pi) * g(w)) / (self.pi * f(w))) num_agents = 5000 separation_rate = 0.025 # Fraction of jobs that end in each period separation_num = int(num_agents * separation_rate) agent_indices = list(range(num_agents)) agents = [Agent() for i in range(num_agents)] sim_length = 600 H = G # Start with distribution G change_date = 200 # Change to F after this many periods unempl_rate = [] for i in range(sim_length): if i % 20 == 0: print("date =", i) if i == change_date: H = F # Randomly select separation_num agents and set employment status to 0 np.random.shuffle(agent_indices) separation_list = agent_indices[:separation_num] for agent_index in separation_list: agents[agent_index].employed = 0 # Update agents for agent in agents: agent.update(H) employed = [agent.employed for agent in agents] unempl_rate.append(1 - np.mean(employed)) fig, ax = plt.subplots(figsize=(9, 7)) ax.plot(unempl_rate, lw=2, alpha=0.8, label='unemployment rate') ax.axvline(change_date, color="red") ax.legend() plt.show() ###Output Iteration Distance Elapsed (seconds) --------------------------------------------- 5 2.829e-02 2.050e-01 10 5.174e-03 3.851e-01 15 9.652e-04 5.652e-01 date = 0 date = 20 date = 40 date = 60 date = 80 date = 100 date = 120 date = 140 date = 160 date = 180 date = 200 date = 220 date = 240 date = 260 date = 280 date = 300 date = 320 date = 340 date = 360 date = 380 date = 400 date = 420 date = 440 date = 460 date = 480 date = 500 date = 520 date = 540 date = 560 date = 580
chapter_4_exercises.ipynb
###Markdown **Exercise 1)** ###Code help(str) help(list) help(tuple) ###Output Help on class tuple in module __builtin__: class tuple(object) | tuple() -> empty tuple | tuple(iterable) -> tuple initialized from iterable's items | | If the argument is a tuple, the return value is the same object. | | Methods defined here: | | __add__(...) | x.__add__(y) <==> x+y | | __contains__(...) | x.__contains__(y) <==> y in x | | __eq__(...) | x.__eq__(y) <==> x==y | | __ge__(...) | x.__ge__(y) <==> x>=y | | __getattribute__(...) | x.__getattribute__('name') <==> x.name | | __getitem__(...) | x.__getitem__(y) <==> x[y] | | __getnewargs__(...) | | __getslice__(...) | x.__getslice__(i, j) <==> x[i:j] | | Use of negative indices is not supported. | | __gt__(...) | x.__gt__(y) <==> x>y | | __hash__(...) | x.__hash__() <==> hash(x) | | __iter__(...) | x.__iter__() <==> iter(x) | | __le__(...) | x.__le__(y) <==> x<=y | | __len__(...) | x.__len__() <==> len(x) | | __lt__(...) | x.__lt__(y) <==> x<y | | __mul__(...) | x.__mul__(n) <==> x*n | | __ne__(...) | x.__ne__(y) <==> x!=y | | __repr__(...) | x.__repr__() <==> repr(x) | | __rmul__(...) | x.__rmul__(n) <==> n*x | | count(...) | T.count(value) -> integer -- return number of occurrences of value | | index(...) | T.index(value, [start, [stop]]) -> integer -- return first index of value. | Raises ValueError if the value is not present. | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __new__ = <built-in method __new__ of type object> | T.__new__(S, ...) -> a new object with type S, a subtype of T ###Markdown **Exercise 2)** ###Code # tuples + lists: slicing, concatination, indexing # only lists: reverse, sort, pop # only tuple: hash hash((1,2)) ###Output _____no_output_____ ###Markdown **Exercise 3)** ###Code myTuple = tuple([1]) print myTuple type(myTuple) myTuple = (1,) print myTuple type(myTuple) ###Output (1,) ###Markdown **Exercise 4)** ###Code words = ['is', 'NLP', 'fun', '?'] tmp = words[0] words[0] = words[1] words[1] = tmp words[3] = '!' words words = ['is', 'NLP', 'fun', '?'] words[0], words[1], words[3] = words[1], words[0], '!' words ###Output _____no_output_____ ###Markdown **Exercise 5)** ###Code help(cmp) cmp(3,9) cmp(9,3) # can differentiate 3 cases ###Output _____no_output_____ ###Markdown **Exercise 6)** ###Code sent = ['The', 'dog', 'gave', 'John', 'the', 'newspaper'] n = 3 [sent[i:i+n] for i in range(len(sent)-n+1)] sent = ['The', 'dog', 'gave', 'John', 'the', 'newspaper'] n = 1 [sent[i:i+n] for i in range(len(sent)-n+1)] sent = ['The', 'dog', 'gave', 'John', 'the', 'newspaper'] n = len(sent) [sent[i:i+n] for i in range(len(sent)-n+1)] ###Output _____no_output_____ ###Markdown **Exercise 7)** ###Code if (0): print 'true!' if (1): print 'true!' if ('foo'): print 'true!' if (()): print 'true!' if ((1,2)): print 'true!' if (-1): print 'true!' ###Output true! ###Markdown **Exercise 8)** ###Code 'Monty' < 'Python' 'Z' < 'a' 'z' < 'a' 'Monty' < 'Montague' ('Monty', 1) < ('Monty', 2) ('Monty', 1) < ('Montague', 2) (1, 'Monty') < (2, 'Montague') ###Output _____no_output_____ ###Markdown **Exercise 9)** ###Code # a myStr = ' some whitespaced string ' ' '.join(myStr.split()) # b import re re.sub(r'\s+', ' ', re.sub(r'^\s+|\s+$', '', myStr)) ###Output _____no_output_____ ###Markdown **Exercise 10)** ###Code def sortWords(words): def cmp_len(word1, word2): return cmp(len(word1), len(word2)) return sorted(words, cmp=cmp_len) sortWords(['The', 'dog', 'gave', 'John', 'the', 'newspaper']) ###Output _____no_output_____ ###Markdown **Exercise 11)** ###Code sent1 = ['The', 'dog', 'gave', 'John', 'the', 'newspaper'] sent2 = sent1 sent1[1] = 'cat' sent2 # a sent1 = ['The', 'dog', 'gave', 'John', 'the', 'newspaper'] sent2 = sent1[:] sent1[1] = 'cat' sent2 # [:] -> copy list items, instead of creating reference to same list # b text1 = [['The', 'dog', 'gave', 'John', 'the', 'newspaper'], ['The', 'cat', 'miowed']] text2 = text1[:] text1[0][1] = 'monkey' text2 # did not copy inner lists, but references to them # c from copy import deepcopy help(deepcopy) text1 = [['The', 'dog', 'gave', 'John', 'the', 'newspaper'], ['The', 'cat', 'miowed']] text3 = deepcopy(text1) text1[0][1] = 'monkey' text3 ###Output _____no_output_____ ###Markdown **Exercise 12)** ###Code word_table = [[''] * 3] * 4 word_table[1][2] = "hello" word_table # multiplication adds references to the same list, not copies of it word_table = [['' for count1 in range(3)] for count2 in range(4)] word_table[1][2] = "hello" word_table ###Output _____no_output_____ ###Markdown **Exercise 13)** ###Code word_vowels = [[]] words = ['The', 'dog', 'gave', 'John', 'the', 'newspaper', 'The', 'cat', 'miowed'] for word in words: if (len(word) > len(word_vowels)-1): for index in range(len(word_vowels), len(word)+1): word_vowels.append([]) num_vowels = len(re.findall(r'[aeiouAEIOU]', word)) if (num_vowels > len(word_vowels[len(word)])-1): for index in range(len(word_vowels[len(word)]), num_vowels+1): word_vowels[len(word)].append(set()) word_vowels[len(word)][num_vowels].add(word) print word_vowels[3][1] print word_vowels[9][3] ###Output set(['the', 'The', 'dog', 'cat']) set(['newspaper']) ###Markdown **Exercise 14)** ###Code def novel10(text): splitIndex = len(text) / 10 print [w for w in text[-splitIndex:] if w not in text[:-splitIndex]] from nltk.book import * novel10(text3) ###Output *** Introductory Examples for the NLTK Book *** Loading text1, ..., text9 and sent1, ..., sent9 Type the name of the text or sentence to view it. Type: 'texts()' or 'sents()' to list the materials. text1: Moby Dick by Herman Melville 1851 text2: Sense and Sensibility by Jane Austen 1811 text3: The Book of Genesis text4: Inaugural Address Corpus text5: Chat Corpus text6: Monty Python and the Holy Grail text7: Wall Street Journal text8: Personals Corpus text9: The Man Who Was Thursday by G . K . Chesterton 1908 [u'nati', u'aga', u'His', u'Phallu', u'Hezron', u'Carmi', u'Jemuel', u'Jamin', u'Ohad', u'Jachin', u'Shaul', u'Canaanitish', u'Gershon', u'Kohath', u'Merari', u'Zar', u'Hezron', u'Hamul', u'Tola', u'Phuvah', u'Job', u'Shimron', u'Sered', u'Jahleel', u'Din', u'Ziphion', u'Haggi', u'Shuni', u'Ezbon', u'Eri', u'Arodi', u'Areli', u'Jimnah', u'Ishuah', u'Isui', u'Beriah', u'Serah', u'Beriah', u'Heber', u'Malchiel', u'sixteen', u'Belah', u'Becher', u'Ashbel', u'Gera', u'Naaman', u'Ehi', u'Rosh', u'Muppim', u'Huppim', u'Ard', u'Hushim', u'Jahzeel', u'Guni', u'Jezer', u'Shillem', u'direct', u'presented', u'shepherds', u'occupation', u'fathe', u'shepherd', u'presented', u'occupation', u'shepherds', u'morever', u'pasture', u'activity', u'rulers', u'pilgrimage', u'attained', u'pilgrimage', u'Rameses', u'nourished', u'boug', u'faileth', u'fail', u'exchange', u'horses', u'bodies', u'lan', u'desolate', u'priests', u'priests', u'assigned', u'sow', u'increase', u'parts', u'saved', u'priests', u'multiplied', u'nigh', u'bed', u'si', u'strengthened', u'bed', u'issue', u'begettest', u'Padan', u'guiding', u'wittingly', u'Angel', u'redeemed', u'lads', u'remove', u'Not', u'Manass', u'last', u'excellency', u'dignity', u'excellency', u'pow', u'Unstable', u'excel', u'wentest', u'bed', u'defiledst', u'couch', u'instruments', u'cruelty', u'secret', u'assembly', u'honour', u'unit', u'selfwill', u'wall', u'fierce', u'cru', u'lion', u'whelp', u'prey', u'stooped', u'couched', u'lion', u'lion', u'rouse', u'sceptre', u'lawgiver', u'Shiloh', u'Binding', u'foal', u'colt', u'His', u'teeth', u'haven', u'haven', u'ships', u'Zidon', u'strong', u'couching', u'burdens', u'tribute', u'tribes', u'adder', u'path', u'biteth', u'horse', u'heels', u'rider', u'waited', u'salvation', u'overcome', u'overcome', u'last', u'royal', u'dainties', u'hind', u'loose', u'giveth', u'bough', u'bough', u'run', u'wa', u'archers', u'sorely', u'arms', u'strong', u'shepherd', u'blessings', u'blessings', u'blessings', u'breasts', u'blessings', u'blessings', u'progenitors', u'utmost', u'hil', u'crown', u'ravin', u'wolf', u'devour', u'prey', u'spoil', u'tribes', u'peop', u'purchase', u'commanding', u'bed', u'yielded', u'physicians', u'embalm', u'physicians', u'embalmed', u'embalm', u'past', u'elders', u'elders', u'chariots', u'horsemen', u'threshingfloor', u'Atad', u'lamentati', u'floor', u'Atad', u'Egyptia', u'Abelmizraim', u'requite', u'messenger', u'Forgive', u'forgive', u'meant', u'Machir', u'visit', u'visit', u'embalmed', u'coffin'] ###Markdown **Exercise 15)** ###Code import nltk def countWords(sent): sent = sent.split() fdist = nltk.FreqDist(w.lower() for w in sent) for key in sorted(fdist.keys()): print '%s: %d' % (key, fdist[key]) countWords(' '.join(sent9)) ###Output ,: 1 .: 1 a: 1 and: 1 as: 2 cloud: 1 lay: 1 london: 1 of: 3 on: 1 park: 1 ragged: 1 red: 1 saffron: 1 side: 1 suburb: 1 sunset: 2 the: 2 ###Markdown **Exercise 16)** ###Code # a def gematria(word): letter_vals = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':80, 'g':3, 'h':8, 'i':10, 'j':10, 'k':20, 'l':30, 'm':40, 'n':50, 'o':70, 'p':80, 'q':100, 'r':200, 's':300, 't':400, 'u':6, 'v':6, 'w':800, 'x':60, 'y':10, 'z':7} return sum(letter_vals[l] for l in word if len(re.findall(r'[a-z]', l)) > 0) gematria('gematria') # b for fileid in nltk.corpus.state_union.fileids(): words666 = [w.lower() for w in nltk.corpus.state_union.words(fileid) if w.isalpha() and gematria(w.lower()) == 666] print '\n%s: %d' % (fileid, len(words666)) print set(words666) # c import random def decode(text): num = random.randint(1, 1000) return num, set([w.lower() for w in text if w.isalpha() and gematria(w.lower()) == num]) result = decode(text4) print result[0] print result[1] ###Output 765 set([u'partaking', u'poetry', u'against', u'authorizing', u'gratefully', u'thorough', u'operated', u'frightened', u'tells', u'mentor']) ###Markdown **Exercise 17)** ###Code def shorten(text, n=20): most_freq = nltk.FreqDist(text).most_common(n) most_freq = [w for (w, num) in most_freq] print most_freq return [w for w in text if w not in most_freq] print ' '.join(shorten(text3, 50)[:100]) ###Output [u',', u'and', u'the', u'of', u'.', u'And', u'his', u'he', u'to', u';', u'unto', u'in', u'that', u'I', u'said', u'him', u'a', u'my', u'was', u'for', u'it', u'with', u'me', u'thou', u"'", u'is', u'thy', u's', u'thee', u'be', u'shall', u'they', u'all', u':', u'God', u'them', u'not', u'father', u'which', u'will', u'land', u'Jacob', u'came', u'her', u'LORD', u'were', u'she', u'Joseph', u'from', u'their'] In beginning created heaven earth earth without form void darkness upon face deep Spirit moved upon face waters Let there light there light saw light good divided light darkness called light Day darkness called Night evening morning first day Let there firmament midst waters let divide waters waters made firmament divided waters under firmament waters above firmame so called firmament Heaven evening morning second day Let waters under heaven gathered together one place let dry appe so called dry Earth gathering together waters called Se saw good Let earth bring forth grass herb yielding seed fruit tree yielding fruit after ###Markdown **Exercise 18)** ###Code def getWords(prop, value): lexicon = [('fish', 'water animal', 'fish'), ('house', 'building', 'haus'), ('whale', 'water animal', 'wejl')] if prop == 'meaning': return [w for (w, m, p) in lexicon if m == value] if prop == 'pronunciation': return [w for (w, m, p) in lexicon if p == value] getWords('meaning', 'water animal') getWords('pronunciation', 'haus') ###Output _____no_output_____ ###Markdown **Exercise 19)** ###Code from nltk.corpus import wordnet as wn list_syns = [wn.synset('minke_whale.n.01'), wn.synset('orca.n.01'), wn.synset('novel.n.01'), wn.synset('tortoise.n.01')] comp = wn.synset('right_whale.n.01') sorted(list_syns, lambda x,y: cmp(comp.shortest_path_distance(x), comp.shortest_path_distance(y))) ###Output _____no_output_____ ###Markdown **Exercise 20)** ###Code def sortWords(wordList): fdist = nltk.FreqDist(wordList) return fdist.keys() sortWords(['one', 'two', 'two', 'four', 'four', 'four', 'four', 'three', 'three', 'three']) ###Output _____no_output_____ ###Markdown **Exercise 21)** ###Code def unknownWords(text, vocab): return set(text).difference(set(vocab)) unknownWords(text3, nltk.corpus.words.words()) ###Output _____no_output_____ ###Markdown **Exercise 22)** ###Code from operator import itemgetter print sent3[:-1] print sorted(sent3[:-1], key=itemgetter(1)) print sorted(sent3[:-1], key=itemgetter(-1)) help(itemgetter) i = itemgetter(0) print i('hallo') print i(['hallo', 'welt']) ###Output h hallo ###Markdown **Exercise 23)** ###Code import nltk def insert(trie, key, value): if key: first, rest = key[0], key[1:] if first not in trie: trie[first] = {} insert(trie[first], rest, value) else: trie['value'] = value trie = nltk.defaultdict(dict) insert(trie, 'chat', 'cat') insert(trie, 'chien', 'dog') insert(trie, 'chair', 'flesh') trie['c']['h']['a']['t']['value'] import pprint def lookup(trie, key): if len(key) == 0: if 'value' in trie: result = trie['value'] return result elif (len(trie) == 1): keys = trie.keys() return lookup(trie[keys[0]], '') else: return 'no value found' else: if (key[0] in trie): return lookup(trie[key[0]], key[1:]) else: return 'no value found' print lookup(trie, 'ch') ###Output no value found ###Markdown **Exercise 24)** ###Code # TODO ###Output _____no_output_____ ###Markdown **Exercise 25)** ###Code help(nltk.edit_distance) nltk.edit_distance('kitten', 'sitting', True) ###Output _____no_output_____ ###Markdown **Exercise 26)** ###Code # a def catalan_recursive(n): if (n == 0): return 1 i = 0 result = 0 original_n = n while i < original_n: result += catalan_recursive(i) * catalan_recursive(n-1) n -= 1 i += 1 return result catalan_recursive(6) # b def catalan_dynamic(n, lookup={0:1}): result = 0 if n == 0: return 1 for i in range(n): if i not in lookup: lookup[i] = catalan_dynamic(i, lookup) if n-1 not in lookup: lookup[n-1] = catalan_dynamic(n-1, lookup) result += lookup[i] * lookup[n-1] n -= 1 return result catalan_dynamic(6) # c from timeit import Timer t = Timer(lambda: catalan_recursive(10)) print t.timeit(number=10) t = Timer(lambda: catalan_dynamic(10)) print t.timeit(number=10) ###Output 0.89065578542 0.000288574442266 ###Markdown **Exercise 27)** ###Code # TODO ###Output _____no_output_____ ###Markdown **Exercise 28)** ###Code # TODO ###Output _____no_output_____ ###Markdown **Exercise 29)** ###Code import nltk trie = nltk.defaultdict(dict) insert(trie, 'chat', 'cat') insert(trie, 'chien', 'dog') insert(trie, 'chair', 'flesh') insert(trie, 'chic', 'stylish') trie['c']['h']['a']['t']['value'] def pprint_trie(trie, line=''): if 'value' in trie: print line + ': \'' + trie['value'] + '\'' return for index, key in enumerate(sorted(trie.keys())): if (index == 0): pprint_trie(trie[key], line + key) else: pprint_trie(trie[key], ('-' * len(line)) + key) pprint_trie(trie) ###Output chair: 'flesh' ---t: 'cat' --ic: 'stylish' ---en: 'dog' ###Markdown **Exercise 30)** ###Code def lookup_unique(key, trie, unique='', buffer_unique=''): if len(key) == 0: if len(buffer_unique) > 0: return buffer_unique else: return unique if len(trie[key[0]]) == 1: if len(buffer_unique) > 0: new_buffer_unique = buffer_unique else: new_buffer_unique = unique + key[0] return lookup_unique(key[1:], trie[key[0]], unique + key[0], new_buffer_unique) return lookup_unique(key[1:], trie[key[0]], unique + key[0]) def compress(text): trie = nltk.defaultdict(dict) for word in text: insert(trie, word, word) return [lookup_unique(w, trie) for w in text] compressed = compress(text1) from __future__ import division print (100.0/len(''.join(text1))) * len(''.join(compressed)) print ' '.join(compressed[:200]) compressed = compress(sent3) print (100.0/len(''.join(sent3))) * len(''.join(compressed)) print ' '.join(compressed) ###Output 24.4444444444 I t b G c t h a t e . ###Markdown **Exercise 31)** ###Code def load(fileName): f = open(fileName + '.txt') return f.read() raw = load('corpus') import textwrap wrapped = textwrap.wrap(raw) print wrapped[:10] def justify(wrapped_text): line_length = max(len(line) for line in wrapped_text) for line in wrapped_text: words = line.split() num_chars = sum(len(word) for word in words) num_spaces = line_length - num_chars num_slots = len(words) - 1 fixed_spaces = int(num_spaces / num_slots) spaces = 0 for index, word in enumerate(words[:-1]): word += ' ' * fixed_spaces spaces += fixed_spaces words[index] = word while num_spaces - spaces > 0: remainder = (num_spaces - spaces) % num_slots chunk_size = int(len(words) / (remainder + 1)) chunk = 0 for index, word in enumerate(words[:-1]): if remainder and chunk == chunk_size: word += ' ' spaces += 1 chunk = 0 else: chunk += 1 words[index] = word print ''.join(words) justify(wrapped[:30]) ###Output Web-Based E-Assessment Beyond Multiple-Choice: The Application of PHP- and HTML5 Technologies to Different Testing Formats Documentation Master's Thesis in Linguistics and Web Technology presented to the Faculty of Foreign Languages and Cultures at the Philipps-Universität Marburg by Julia Neumann from Naumburg (Germany) Marburg, 2015 Contents List of Abbreviations 3 1 Introduction 4 2 User Guide 5 3 Overall Organization of the Code 7 3.1 General Design of the JavaScript Components 9 4 Implementation of the Testing Formats 11 4.1 Crossword 11 4.2 Dynamic Multiple- Choice 13 4.3 Drag-and-Drop 15 5 Database Structure 17 6 General Features 19 6.1 Index Page 19 6.2 Contact Page 20 6.3 Color Changer 20 6.4 Inline Editing and Deletion 21 6.5 Exporting Tests 22 References 25 Appendix I: Database Structure 26 Declaration of Authorship 27 List of Abbreviations AJAX Asynchronous JavaScript and XML CSS Cascading Style Sheets DOM Document Object Model HTML Hypertext Markup Language JPEG Joint Photographic Experts Group MVC Model-View-Controller MySQLi MySQL Improved PHP PHP: Hypertext Preprocessor PNG Portable Network Graphics SQL Structured Query Language SVG Scalable Vector Graphics XML Extensible Markup Language 1 Introduction This documentation provides an overview of an application developed for the creation and management of web-based assessment tasks in three different formats. The application consists of a user-friendly interface to a database structure for storing the created tests and allows its users not only to generate new tests, but also to edit, delete, view, and run existing tests. Thus, it constitutes a tool that can be used by ###Markdown **Exercise 32)** ###Code import nltk def summarize(text_sents, n): from operator import itemgetter freqDist = nltk.FreqDist([w.lower() for sent in text_sents for w in sent]) scoresSents = [(sum(freqDist[word] for word in sent), index, sent) for (index, sent) in enumerate(text_sents)] sortByFreq = sorted(scoresSents, key=itemgetter(0), reverse=True)[:n] sortByIndex = sorted(sortByFreq, key=itemgetter(1)) for (freq, index, sent) in sortByIndex: print index, ': ', sent, '\n' from nltk.corpus import brown summarize(brown.sents(categories='religion'), 10) ###Output 274 : [u'``', u'So', u'that', u'the', u'man', u'should', u'not', u'have', u'thoughts', u'of', u'grandeur', u',', u'and', u'become', u'lifted', u'up', u',', u'as', u'if', u'he', u'had', u'no', u'lord', u',', u'because', u'of', u'the', u'dominion', u'that', u'had', u'been', u'given', u'to', u'him', u',', u'and', u'the', u'freedom', u',', u'fall', u'into', u'sin', u'against', u'God', u'his', u'Creator', u',', u'overstepping', u'his', u'bounds', u',', u'and', u'take', u'up', u'an', u'attitude', u'of', u'self-conceited', u'arrogance', u'towards', u'God', u',', u'a', u'law', u'was', u'given', u'him', u'by', u'God', u',', u'that', u'he', u'might', u'know', u'that', u'he', u'had', u'for', u'lord', u'the', u'lord', u'of', u'all', u'.'] 304 : [u'But', u'He', u'set', u'a', u'bound', u'to', u'his', u'(', u'state', u'of', u')', u'sin', u',', u'by', u'interposing', u'death', u',', u'and', u'thus', u'causing', u'sin', u'to', u'cease', u',', u'putting', u'an', u'end', u'to', u'it', u'by', u'the', u'dissolution', u'of', u'the', u'flesh', u',', u'which', u'should', u'take', u'place', u'in', u'the', u'earth', u',', u'so', u'that', u'man', u',', u'ceasing', u'at', u'length', u'to', u'live', u'in', u'sin', u',', u'and', u'dying', u'to', u'it', u',', u'might', u'live', u'to', u'God', u"''", u'.'] 383 : [u'What', u'otherwise', u'could', u'``', u'the', u'lawyer', u',', u'doctor', u',', u'minister', u',', u'the', u'men', u'of', u'science', u'and', u'letters', u"''", u'do', u'when', u'told', u'that', u'they', u'had', u'``', u'become', u'the', u'cherubim', u'and', u'seraphim', u'and', u'the', u'three', u'archangels', u'who', u'stood', u'before', u'the', u'golden', u'throne', u'of', u'the', u'merchant', u',', u'and', u'continually', u'cried', u',', u"'", u'Holy', u',', u'holy', u',', u'holy', u'is', u'the', u'Almighty', u'Dollar', u"'", u'``', u'?', u'?'] 401 : [u'We', u'have', u'not', u'the', u'leisure', u',', u'or', u'the', u'patience', u',', u'or', u'the', u'skill', u',', u'to', u'comprehend', u'what', u'was', u'working', u'in', u'the', u'mind', u'and', u'heart', u'of', u'a', u'then', u'recent', u'graduate', u'from', u'the', u'Harvard', u'Divinity', u'School', u'who', u'would', u'muster', u'the', u'audacity', u'to', u'contradict', u'his', u'most', u'formidable', u'instructor', u',', u'the', u'majesterial', u'Andrews', u'Norton', u',', u'by', u'saying', u'that', u',', u'while', u'he', u'believed', u'Jesus', u'``', u'like', u'other', u'religious', u'teachers', u"''", u',', u'worked', u'miracles', u',', u'``', u'I', u'see', u'not', u'how', u'a', u'miracle', u'proves', u'a', u'doctrine', u"''", u'.'] 406 : [u'At', u'one', u'time', u'I', u'became', u'disturbed', u'in', u'the', u'faith', u'in', u'which', u'I', u'had', u'grown', u'up', u'by', u'the', u'apparent', u'inroads', u'being', u'made', u'upon', u'both', u'Old', u'and', u'New', u'Testaments', u'by', u'a', u'``', u'Higher', u'Criticism', u"''", u'of', u'the', u'Bible', u',', u'to', u'refute', u'which', u'I', u'felt', u'the', u'need', u'of', u'a', u'better', u'knowledge', u'of', u'Hebrew', u'and', u'of', u'archaeology', u',', u'for', u'it', u'seemed', u'to', u'me', u'that', u'to', u'pull', u'out', u'some', u'of', u'the', u'props', u'of', u'our', u'faith', u'was', u'to', u'weaken', u'the', u'entire', u'structure', u'.'] 417 : [u'The', u'outcome', u'of', u'such', u'an', u'experiment', u'has', u'been', u'in', u'due', u'time', u'the', u'acceptance', u'of', u'the', u'Bible', u'as', u'the', u'Word', u'of', u'God', u'inspired', u'in', u'a', u'sense', u'utterly', u'different', u'from', u'any', u'merely', u'human', u'book', u',', u'and', u'with', u'it', u'the', u'acceptance', u'of', u'our', u'Lord', u'Jesus', u'Christ', u'as', u'the', u'only', u'begotten', u'Son', u'of', u'God', u',', u'Son', u'of', u'Man', u'by', u'the', u'Virgin', u'Mary', u',', u'the', u'Saviour', u'of', u'the', u'world', u'.'] 418 : [u'I', u'believe', u',', u'therefore', u',', u'that', u'we', u'are', u'without', u'exception', u'sinners', u',', u'by', u'nature', u'alienated', u'from', u'God', u',', u'and', u'that', u'Jesus', u'Christ', u',', u'the', u'Son', u'of', u'God', u',', u'came', u'to', u'earth', u',', u'the', u'representative', u'Head', u'of', u'a', u'new', u'race', u',', u'to', u'die', u'upon', u'the', u'cross', u'and', u'pay', u'the', u'penalty', u'of', u'the', u'sin', u'of', u'the', u'world', u',', u'and', u'that', u'he', u'who', u'thus', u'receives', u'Christ', u'as', u'his', u'personal', u'Saviour', u'is', u'``', u'born', u'again', u"''", u'spiritually', u',', u'with', u'new', u'privileges', u',', u'appetites', u',', u'and', u'affections', u',', u'destined', u'to', u'live', u'and', u'grow', u'in', u'His', u'likeness', u'forever', u'.'] 657 : [u'Although', u'the', u'primary', u'mathematical', u'properties', u'of', u'the', u'middle', u'number', u'at', u'the', u'center', u'of', u'the', u'Lo', u'Shu', u',', u'and', u'the', u'interrelation', u'of', u'all', u'the', u'other', u'numbers', u'to', u'it', u',', u'might', u'seem', u'enough', u'to', u'account', u'for', u'the', u'deep', u'fascination', u'which', u'the', u'Lo', u'Shu', u'held', u'for', u'the', u'Old', u'Chinese', u'philosophers', u',', u'this', u'was', u'actually', u'only', u'a', u'beginning', u'of', u'wonders', u'.'] 964 : [u'Presumably', u',', u'if', u'the', u'reverse', u'is', u'the', u'case', u'and', u'the', u'good', u'effect', u'is', u'more', u'certain', u'than', u'the', u'evil', u'result', u'that', u'may', u'be', u'forthcoming', u',', u'not', u'only', u'must', u'the', u'good', u'and', u'the', u'evil', u'be', u'prudentially', u'weighed', u'and', u'found', u'proportionate', u',', u'but', u'also', u'calculation', u'of', u'the', u'probabilities', u'and', u'of', u'the', u'degree', u'of', u'certainty', u'or', u'uncertainty', u'in', u'the', u'good', u'or', u'evil', u'effect', u'must', u'be', u'taken', u'into', u'account', u'.'] 1258 : [u'We', u'should', u'recall', u'the', u'number', u'of', u'movements', u'for', u'the', u'service', u'of', u'mankind', u'which', u'arose', u'from', u'the', u'kindred', u'Evangelicalism', u'of', u'the', u'British', u'Isles', u'and', u'the', u'Pietism', u'of', u'the', u'Continent', u'of', u'Europe', u'--', u'among', u'them', u'prison', u'reform', u',', u'anti-slavery', u'measures', u',', u'legislation', u'for', u'the', u'alleviation', u'of', u'conditions', u'of', u'labour', u',', u'the', u'Inner', u'Mission', u',', u'and', u'the', u'Red', u'Cross', u'.'] ###Markdown **Exercise 33)** ###Code # TODO ###Output _____no_output_____ ###Markdown **Exercise 34)** ###Code # TODO ###Output _____no_output_____ ###Markdown **Exercise 35)** ###Code # TODO ###Output _____no_output_____ ###Markdown **Exercise 36)** ###Code def word_square(n): # works only if n < 5, with 5 exceeds maximum recursion callstack # TODO: Do this iteratively to avoid the callstack issue? from nltk.corpus import words myWords = [word.upper() for word in filter(lambda w: len(w) == n, words.words())] # get all words of length n square = [] skipWords = [[] for i in range(n)] # cache for words that have already been tested at position i def check_against_square(word): # checks if current state of square would allow to add word to it if word in square: return False for (index, square_word) in enumerate(square): if (word[index] != square_word[len(square)]): return False return True def add_word(): # recursively adds / removes words from square until solution is found if len(square) == n: return True for word in myWords: if len(square) == n: return True if (word not in skipWords[len(square)]) and check_against_square(word): # add the word to square if it hasn't been tested unsuccessfully already and if it fits square.append(word) add_word() if len(square) != n and len(square) != 0: skipWords[len(square) - 1].append(square.pop()) # add word to cache for i in range(len(square) + 1, n): # reset the following parts of the cache skipWords[i] = [] add_word() return False if add_word(): for word in square: print word else: print 'No square found :/' word_square(4) word_square(3) ###Output AAL ABA LAB
SPARK/02_Spark_SQL_Advanced.ipynb
###Markdown Prerrequisites Installing Spark and Apache Kafka Library in VM--- ###Code # install Java8 !apt-get install openjdk-8-jdk-headless -qq > /dev/null # download spark3.0.1 !wget -q https://apache.osuosl.org/spark/spark-3.0.1/spark-3.0.1-bin-hadoop3.2.tgz # unzip it !tar xf spark-3.0.1-bin-hadoop3.2.tgz !pip install -q findspark !pip install py4j # For maps !pip install folium !pip install plotly ###Output _____no_output_____ ###Markdown Define the environment (Java & Spark homes)--- ###Code import os os.environ["JAVA_HOME"] = "/usr/lib/jvm/java-8-openjdk-amd64" os.environ["SPARK_HOME"] = "/content/spark-3.0.1-bin-hadoop3.2" os.environ["PYSPARK_SUBMIT_ARGS"] = "--master local[*] pyspark-shell" ###Output _____no_output_____ ###Markdown Starting Spark Session and print the version--- ###Code import findspark findspark.init("spark-3.0.1-bin-hadoop3.2")# SPARK_HOME from pyspark.sql import SparkSession # create the session spark = SparkSession \ .builder \ .master("local[*]") \ .config("spark.ui.port", "4500") \ .getOrCreate() spark.version spark # For Pandas conversion optimization spark.conf.set("spark.sql.execution.arrow.enabled", "true") ###Output _____no_output_____ ###Markdown Creating ngrok tunnel to allow Spark UI (Optional) ###Code !wget https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip !unzip -o ngrok-stable-linux-amd64.zip !sleep 2 get_ipython().system_raw('./ngrok http 4500 &') !curl -s http://localhost:4040/api/tunnels | python3 -c \ "import sys, json; print(json.load(sys.stdin)['tunnels'][0]['public_url'])" ###Output _____no_output_____ ###Markdown Descargar Datasets ###Code !mkdir -p /dataset !wget -q https://github.com/masfworld/datahack_docker/raw/master/zeppelin/data/bank.csv -P /dataset !wget -q https://github.com/masfworld/datahack_docker/raw/master/zeppelin/data/vehicles.csv -P /dataset !wget -q https://github.com/masfworld/datahack_docker/raw/master/zeppelin/data/characters.csv -P /dataset !wget -q https://github.com/masfworld/datahack_docker/raw/master/zeppelin/data/planets.csv -P /dataset !wget -q https://github.com/masfworld/datahack_docker/raw/master/zeppelin/data/species.csv -P /dataset !ls /dataset ###Output _____no_output_____ ###Markdown Windows Partitioning--- Ejemplo 1 ###Code !head /dataset/bank.csv ###Output _____no_output_____ ###Markdown Leyendo Datos del fichero bank.csv a un Dataframe ###Code from pyspark.sql.functions import * bank_df = spark.read.format("csv") \ .option("sep", ";") \ .option("inferSchema", "true") \ .option("header", "true") \ .load("/dataset/bank.csv") bank_df.show() ###Output _____no_output_____ ###Markdown **Obtén el balance de las dos personas más jóvenes por tipo de trabajo** ###Code from pyspark.sql.window import Window byJob = Window.partitionBy("job").orderBy("age") bank_df \ .withColumn("new_column_job", row_number().over(byJob)) \ .filter(col("new_column_job") <= 2) \ .select("age", "job", "balance") \ .orderBy("job", "age") \ .show() ###Output _____no_output_____ ###Markdown Ejercicio 1 **A partir del Dataframe formado a partir del fichero "bank.csv". Obtén el Top 3 de máximos balances por estado civil**--- ###Code ###Output _____no_output_____ ###Markdown Ejercicio 2 **Carga el fichero de vehicles.csv en un DataFrame** ###Code !head /dataset/vehicles.csv ###Output _____no_output_____ ###Markdown **Para cada uno de los vehículos, obtén la diferencia de precio (*cost_in_credits*) para cada producto con respecto al más barato en la misma clase de vehículo**--- ###Code ###Output _____no_output_____ ###Markdown Joins Ejercicio 3 **Crea los dataframes correspondientes para los ficheros "characters.csv" y "planets.csv". Obtén la gravedad del planeta para cada personaje. Selecciona sólo el nombre del personaje y planeta además de su gravedad**--- ###Code ###Output _____no_output_____ ###Markdown Ejercicio 4 **Revisa el plan de ejecución del ejercicio 3. ¿Qué tipo de join se está ejecutando? ¿Por qué?**--- **Después de revisar el plan de ejecución, ejecuta las siguientes instrucciones**--- ###Code spark.conf.set("spark.sql.autoBroadcastJoinThreshold", '0') spark.conf.get("spark.sql.autoBroadcastJoinThreshold") ###Output _____no_output_____ ###Markdown **Vuelve a ejecutar la consulta del ejercicio 3 que contiene el Join**--- Ejercicio 5 **Crea un DataFrame a partir del fichero de "species.csv" y reparticiona este y el DataFrame de Characters a 100 particiones**--- ###Code ###Output _____no_output_____ ###Markdown Ejercicio 6 **Obtén la clasificación de especies para cada personaje. Selecciona sólo el nombre del personaje y su clasificación de especie**Usa los datframes reparticionados--- ###Code ###Output _____no_output_____ ###Markdown Ejercicio 7 **Ejecuta la siguiente operación sobre el DataFrame del ejercicio 6 y observa la diferencia de reparto de rows entre las particiones**--- ###Code ###Output _____no_output_____
Showing the metrics of all datasets.ipynb
###Markdown Print a metrics comparison matrixIn order to make a first evaluation of the given datasets, we compute some basic metrics. For more information on the metrics and also the extraciton of metrics for the smaller datasets look at: `Evaluation metrics for picking an appropriate data set for our goals.ipynb `For the importing the four largest datasets to postgresql and evaluating their metrics look at: `Importing the large data sets to psql and computing their metrics.ipynb`Finally, the evaluated metrics of all datasets are exported to `metadata` and imported here to visualize. ###Code def percentage(some_float): return '%i%%' % int(100 * some_float) def metrics_comparison_matrix(reviews_df): return reviews_df.apply( lambda row: [ percentage(row[i]) for i in range(0, 5) ] + [ int(row[5]), row[6], row[7] ], axis=1) import pandas as pd small_data_metrics = pd.read_csv('./metadata/initial-data-evaluation-metrics.csv') large_data_metrics = pd.read_csv('./metadata/large-datasets-evaluation-metrics.csv') metrics = metrics_comparison_matrix( pd.concat([ small_data_metrics, large_data_metrics ]) .set_index('dataset_name')) metrics.to_csv('./metadata/all-metrics-formatted.csv') metrics ###Output _____no_output_____
curso/grafico-dispersao/aula/Exercicio-Resolvido-2.ipynb
###Markdown Exercício resolvido 2 - Gráfico de dispersão Use os conhecimentos obtidos nesta aula e faça um gráfico relacionando o **peso** médio com a **altura** média de diversas espécies de animais. Dicas: - Use sua imaginação e criatividade para deixar o gráfico **óbvio**;- Volte e olhe a aula anterior ou veja o notebook de referência da aula;- Pesquise no [google](https://www.google.com/) e/ou [stackoverflow](https://stackoverflow.com/) pela sua dúvida. Conjunto de dadosO conunto de dados foi obtido em [www.dimensions.com](https://www.dimensions.com/classifications/animals) no dia 14/04/2021, e contam com dados de altura (cm) e peso (kg) de diversos tipos de animais:- cachorros;- gatos;- ursos;- camelos;- vacas;- cavalos;- pinguins;- porcos; CachorrosOs dados de altura (cm) e peso (kg) dos cachorros, contam com [11 raças diferentes](https://www.dimensions.com/collection/dogs-dog-breeds): ###Code cachorro_altura = [19.05, 25.4, 26.67, 29.21, 36.83, 52.07, 54.61, 57.15, 60.96, 62.23, 67.31] # altura em em centímetros cachorro_peso = [1.59, 4.53, 8.16, 10.2, 10.88, 22.68, 22.68, 30.62, 37.42, 45.36, 68.04] # peso em kilos raca_cachorro = ['Chihuahua', 'Poodle Toy', 'Pug', 'French Bulldog', 'Beagle', 'Chow Chow', 'Siberian Husky', 'Labrador Retriever', 'German Shepherd Dog', 'Rottweiler', 'Saint Bernard'] # nome da respectiva raça ###Output _____no_output_____ ###Markdown GatosOs dados de altura (cm) e peso (kg) dos gatos, contam com [30 raças diferentes](https://www.dimensions.com/collection/cats-cat-breeds): ###Code gatos_altura = [22.5, 22.5, 22.5, 22.5, 32.0, 38.0, 27.5, 25.5, 27.5, 25.5, 27.5, 27.5, 32.5, 27.5, 26.5, 22.5, 25.5, 22.5, 25.5, 25.5, 22.5, 35.5, 22.5, 22.5, 17.5, 22.5, 22.5, 22.5, 25.5, 25.5] # altura em em centímetros gatos_peso = [4.5, 6.0, 7.0, 4.5, 4.0, 5.5, 4.5, 4.5, 3.5, 4.5, 4.0, 4.0, 8.0, 4.5, 7.5, 3.5, 5.0, 4.0, 6.5, 6.5, 5.5, 8.0, 5.0, 4.5, 3.5, 5.5, 5.5, 5.0, 5.5, 7.0] # peso em kilos raca_gatos = ['Abyssinian Cat', 'American Shorthair Cat', 'Bengal Cat', 'Birman Cat', 'Bombay Cat', 'British Shorthair Cat', 'Burmese Cat', 'Chartreux Cat', 'Devon Rex Cat', 'Havana Brown Cat', 'Himalayan Cat', 'Korat Cat', 'Maine Coon Cat', 'Manx Cat', 'Norwegian Forest Cat', 'Oriental Cat', 'Oriental Shorthair Cat', 'Persian Cat', 'Ragamuffin Cat', 'Ragdoll Cat', 'Russian Blue Cat', 'Savannah Cat', 'Scottish Fold Cat', 'Siamese Cat', 'Singapura Cat', 'Somali Cat', 'Sphynx Cat', 'Tonkinese Cat', 'Turkish Van Cat', 'Siberian Cat'] # nome da respectiva raça ###Output _____no_output_____ ###Markdown UrsosOs dados de altura (cm) e peso (kg) dos ursos, contam com [11 raças diferentes](https://www.dimensions.com/collection/bears-ursidae): ###Code ursos_altura = [90, 86.5, 155, 68.5, 114, 127, 120.5, 152.5, 76, 76, 66] # altura em em centímetros ursos_peso = [181, 120.5, 408.5, 91, 249.5, 408, 415, 646.5, 99.5, 118, 47.5] # peso em kilos ursos_nomes = ['American Black Bear', 'Asiatic Black Bear', 'Cave Bear', 'Giant Panda Bear', 'Grizzly Bear', 'Kodiak Bear', 'Polar Bear', 'Short-Faced Bear', 'Sloth Bear', 'Spectacled Bear', 'Sun Bear'] # nome da respectiva raça ###Output _____no_output_____ ###Markdown CamelosOs dados de altura (cm) e peso (kg) dos camelos, contam com [6 raças diferentes](https://www.dimensions.com/collection/camelids-camelidae): ###Code camelos_altura = [108, 213, 213, 150, 175, 128] # altura em em centímetros camelos_peso = [137.5, 475, 500, 115, 165, 50] # peso em kilos camelos_nomes = ['Alpaca', 'Bactrian Camel', 'Dromedary Camel', 'Guanaco', 'Llama', 'Vicuña'] # nome da respectiva raça ###Output _____no_output_____ ###Markdown VacasOs dados de altura (cm) e peso (kg) da vaca, conta com [1 raça](https://www.dimensions.com/collection/cattle-bovine-bovinae): ###Code vacas_altura = [170] # altura em em centímetros vacas_peso = [771] # peso em kilos vacas_nomes = ['Dairy Cow'] # nome da respectiva raça ###Output _____no_output_____ ###Markdown CavalosOs dados de altura (cm) e peso (kg) dos cavalos, contam com [14 raças diferentes](https://www.dimensions.com/collection/horses-horse-breeds): ###Code cavalos_altura = [152.5, 154, 152.5, 150, 172.5, 160, 144.5, 91.5, 148.5, 168.5, 152.5, 91.5, 178, 162.5] # altura em em centímetros cavalos_peso = [431, 476, 499, 408.5, 907, 589.5, 476.5, 113.5, 453.5, 499, 487.5, 192.5, 1000, 465] # peso em kilos cavalos_nomes = ['Akhal-Teke', 'Andalusian Horse', 'Appaloosa Horse', 'Arabian Horse', 'Clydesdale Horse', 'Friesian Horse', 'Haflinger Horse', 'Miniature Horse', 'Morgan Horse', 'American Paint Horse', 'American Quarter Horse', 'Shetland Pony', 'Shire Horse', 'Thoroughbred Horse'] # nome da respectiva raça ###Output _____no_output_____ ###Markdown PinguinsOs dados de altura (cm) e peso (kg) dos pinguins, contam com [6 raças diferentes](https://www.dimensions.com/collection/penguins-spheniscidae): ###Code pinguins_altura = [58.5, 72, 120, 70.5, 85, 65] # altura em em centímetros pinguins_peso = [4.8, 4.25, 33.5, 6.7, 13.65, 4.8] # peso em kilos pinguins_nomes = ['Adélie Penguin', 'Chinstrap Penguin', 'Emperor Penguin', 'Gentoo Penguin', 'King Penguin', 'Macaroni Penguin'] # nome da respectiva raça ###Output _____no_output_____ ###Markdown PorcosOs dados de altura (cm) e peso (kg) dos porcos, contam com [6 raças diferentes](https://www.dimensions.com/collection/pigs-suidae): ###Code porcos_altura = [74, 93, 43.5, 62, 25.5, 67.5, 74, 83.5, 87.5] # altura em em centímetros porcos_peso = [220, 187.5, 56.5, 72.5, 8.25, 87.5, 82.5, 84, 272] # peso em kilos porcos_nomes = ['Domestic Pig', 'Giant Forest Hog', 'Miniature Pig', 'North Sulawesi Babirusa', 'Pygmy Hog', 'Red River Hog', 'Common Warthog', 'Wild Boar', 'Yorkshire Pig'] # nome da respectiva raça ###Output _____no_output_____ ###Markdown Importações Calculando valores médios ###Code ###Output _____no_output_____
Lectures notebooks/(Lectures notebooks) netology Machine learning/23. Distribution semantics (word2vec, GloVe, AdaGram) WMD/sem4_embeddings.ipynb
###Markdown Embeddings [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/PragmaticsLab/NLP-course-FinTech/blob/master/seminars/2/2_embeddings.ipynb) Word2VecВекторные модели, которые мы рассматривали до этого (tf-idf, BOW), условно называются *счётными*. Они основываются на том, что так или иначе "считают" слова и их соседей, и на основе этого строят вектора для слов. Другой класс моделей, который более повсевмёстно распространён на сегодняшний день, называется *предсказательными* (или *нейронными*) моделями. Идея этих моделей заключается в использовании нейросетевых архитектур, которые "предсказывают" (а не считают) соседей слов. Одной из самых известных таких моделей является word2vec. Технология основана на нейронной сети, предсказывающей вероятность встретить слово в заданном контексте. Этот инструмент был разработан группой исследователей Google в 2013 году, руководителем проекта был Томаш Миколов (сейчас работает в Facebook). Вот две самые главные статьи:* [Efficient Estimation of Word Representations in Vector Space](https://arxiv.org/pdf/1301.3781.pdf)* [Distributed Representations of Words and Phrases and their Compositionality](https://arxiv.org/abs/1310.4546)Полученные таким образом вектора называются *распределенными представлениями слов*, или **эмбеддингами**. Как это обучается?Мы задаём вектор для каждого слова с помощью матрицы $w$ и вектор контекста с помощью матрицы $W$. По сути, word2vec является обобщающим названием для двух архитектур Skip-Gram и Continuous Bag-Of-Words (CBOW). **CBOW** предсказывает текущее слово, исходя из окружающего его контекста. **Skip-gram**, наоборот, использует текущее слово, чтобы предугадывать окружающие его слова. Как это работает?Word2vec принимает большой текстовый корпус в качестве входных данных и сопоставляет каждому слову вектор, выдавая координаты слов на выходе. Сначала он создает словарь, «обучаясь» на входных текстовых данных, а затем вычисляет векторное представление слов. Векторное представление основывается на контекстной близости: слова, встречающиеся в тексте рядом с одинаковыми словами (а следовательно, согласно дистрибутивной гипотезе, имеющие схожий смысл), в векторном представлении будут иметь близкие координаты векторов-слов. Для вычисления близости слов используется косинусное расстояние между их векторами.С помощью дистрибутивных векторных моделей можно строить семантические пропорции (они же аналогии) и решать примеры:* *король: мужчина = королева: женщина* $\Rightarrow$ * *король - мужчина + женщина = королева* ![w2v](https://cdn-images-1.medium.com/max/2600/1*sXNXYfAqfLUeiDXPCo130w.png) ПроблемыНевозможно установить тип семантических отношений между словами: синонимы, антонимы и т.д. будут одинаково близки, потому что обычно употребляются в схожих контекстах. Поэтому близкие в векторном пространстве слова называют *семантическими ассоциатами*. Это значит, что они семантически связаны, но как именно — непонятно. RusVectōrēsНа сайте [RusVectōrēs](https://rusvectores.org/ru/) собраны предобученные на различных данных модели для русского языка, а также можно поискать наиболее близкие слова к заданному, посчитать семантическую близость нескольких слов и порешать примеры с помощью «калькулятором семантической близости».Для других языков также можно найти предобученные модели — например, модели [fastText](https://fasttext.cc/docs/en/english-vectors.html) и [GloVe](https://nlp.stanford.edu/projects/glove/) (о них чуть дальше). GensimИспользовать предобученную модель эмбеддингов или обучить свою можно с помощью библиотеки `gensim`. Вот [ее документация](https://radimrehurek.com/gensim/models/word2vec.html). Как использовать готовую модельМодели word2vec бывают разных форматов:* .vec.gz — обычный файл* .bin.gz — бинарникЗагружаются они с помощью одного и того же класса `KeyedVectors`, меняется только параметр `binary` у функции `load_word2vec_format`. Если же эмбеддинги обучены **не** с помощью word2vec, то для загрузки нужно использовать функцию `load`. Т.е. для загрузки предобученных эмбеддингов *glove, fasttext, bpe* и любых других нужна именно она.Скачаем с RusVectōrēs модель для русского языка, обученную на НКРЯ образца 2015 г. ###Code import re import gensim import logging import nltk.data import pandas as pd import urllib.request from bs4 import BeautifulSoup from nltk.corpus import stopwords from gensim.models import word2vec from nltk.tokenize import sent_tokenize, RegexpTokenizer nltk.download('punkt') urllib.request.urlretrieve("http://rusvectores.org/static/models/rusvectores2/ruscorpora_mystem_cbow_300_2_2015.bin.gz", "ruscorpora_mystem_cbow_300_2_2015.bin.gz") model_path = 'ruscorpora_mystem_cbow_300_2_2015.bin.gz' model_ru = gensim.models.KeyedVectors.load_word2vec_format(model_path, binary=True) words = ['день_S', 'ночь_S', 'человек_S', 'семантика_S', 'биткоин_S'] ###Output _____no_output_____ ###Markdown Частеречные тэги нужны, поскольку это специфика скачанной модели - она была натренирована на словах, аннотированных их частями речи (и лемматизированных). **NB!** В названиях моделей на `rusvectores` указано, какой тегсет они используют (mystem, upos и т.д.)Попросим у модели 10 ближайших соседей для каждого слова и коэффициент косинусной близости для каждого: ###Code for word in words: # есть ли слово в модели? if word in model_ru: print(word) # смотрим на вектор слова (его размерность 300, смотрим на первые 10 чисел) print(model_ru[word][:10]) # выдаем 10 ближайших соседей слова: for word, sim in model_ru.most_similar(positive=[word], topn=10): # слово + коэффициент косинусной близости print(word, ': ', sim) print('\n') else: # Увы! print('Увы, слова "%s" нет в модели!' % word) ###Output день_S [-0.02580778 0.00970898 0.01941961 -0.02332282 0.02017624 0.07275085 -0.01444375 0.03316632 0.01242602 0.02833412] неделя_S : 0.7165195941925049 месяц_S : 0.631048858165741 вечер_S : 0.5828739404678345 утро_S : 0.5676207542419434 час_S : 0.5605547428131104 минута_S : 0.5297019481658936 гекатомбеон_S : 0.4897990822792053 денек_S : 0.48224714398384094 полчаса_S : 0.48217129707336426 ночь_S : 0.478074848651886 ночь_S [-0.00688948 0.00408364 0.06975466 -0.00959525 0.0194835 0.04057068 -0.00994112 0.06064967 -0.00522624 0.00520327] вечер_S : 0.6946247816085815 утро_S : 0.57301926612854 ноченька_S : 0.5582467317581177 рассвет_S : 0.5553582906723022 ночка_S : 0.5351512432098389 полдень_S : 0.5334426164627075 полночь_S : 0.478694349527359 день_S : 0.4780748784542084 сумерки_S : 0.4390218257904053 фундерфун_S : 0.4340824782848358 человек_S [ 0.02013756 -0.02670703 -0.02039861 -0.05477146 0.00086402 -0.01636335 0.04240306 -0.00025525 -0.14045681 0.04785006] женщина_S : 0.5979775190353394 парень_S : 0.4991787374019623 мужчина_S : 0.4767409563064575 мужик_S : 0.47384002804756165 россиянин_S : 0.47190436720848083 народ_S : 0.4654741883277893 согражданин_S : 0.45378512144088745 горожанин_S : 0.44368088245391846 девушка_S : 0.44314485788345337 иностранец_S : 0.43849867582321167 семантика_S [-0.03066749 0.0053851 0.1110732 0.0152335 0.00440643 0.00384104 0.00096944 -0.03538784 -0.00079585 0.03220548] семантический_A : 0.5334584712982178 понятие_S : 0.5030269622802734 сочетаемость_S : 0.4817051291465759 актант_S : 0.47596412897109985 хронотоп_S : 0.46330299973487854 метафора_S : 0.46158894896507263 мышление_S : 0.4610119163990021 парадигма_S : 0.45796656608581543 лексема_S : 0.45688074827194214 смысловой_A : 0.4543077349662781 Увы, слова "биткоин_S" нет в модели! ###Markdown Находим косинусную близость пары слов: ###Code print(model_ru.similarity('человек_S', 'обезьяна_S')) ###Output 0.23895611 ###Markdown Что получится, если вычесть из пиццы Италию и прибавить Сибирь?* positive — вектора, которые мы складываем* negative — вектора, которые вычитаем ###Code print(model_ru.most_similar(positive=['пицца_S', 'сибирь_S'], negative=['италия_S'])[0][0]) model_ru.doesnt_match('пицца_S пельмень_S хот-дог_S ананас_S'.split()) ###Output /usr/local/lib/python3.5/dist-packages/gensim/models/keyedvectors.py:895: FutureWarning: arrays to stack must be passed as a "sequence" type such as list or tuple. Support for non-sequence iterables such as generators is deprecated as of NumPy 1.16 and will raise an error in the future. vectors = vstack(self.word_vec(word, use_norm=True) for word in used_words).astype(REAL) /usr/local/lib/python3.5/dist-packages/gensim/matutils.py:737: FutureWarning: Conversion of the second argument of issubdtype from `int` to `np.signedinteger` is deprecated. In future, it will be treated as `np.int64 == np.dtype(int).type`. if np.issubdtype(vec.dtype, np.int): ###Markdown Как обучить свою модельВ качестве обучающих данных возьмем размеченные и неразмеченные отзывы о фильмах (датасет взят с Kaggle). ###Code ! wget https://raw.githubusercontent.com/ancatmara/data-science-nlp/master/data/w2v/train/unlabeledTrainData.tsv data = pd.read_csv("unlabeledTrainData.tsv", header=0, delimiter="\t", quoting=3) len(data) data.head() ###Output _____no_output_____ ###Markdown Убираем из данных ссылки, html-разметку и небуквенные символы, а затем приводим все к нижнему регистру и токенизируем. На выходе получается массив из предложений, каждое из которых представляет собой массив слов. Здесь используется токенизатор из библиотеки `nltk`. ###Code tokenizer = nltk.data.load('tokenizers/punkt/english.pickle') def review_to_wordlist(review, remove_stopwords=False ): # убираем ссылки вне тегов review = re.sub(r"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+", " ", review) review_text = BeautifulSoup(review, "lxml").get_text() review_text = re.sub("[^a-zA-Z]"," ", review_text) words = review_text.lower().split() if remove_stopwords: stops = stopwords.words("english") words = [w for w in words if not w in stops] return(words) def review_to_sentences(review, tokenizer, remove_stopwords=False): raw_sentences = tokenizer.tokenize(review.strip()) sentences = [] for raw_sentence in raw_sentences: if len(raw_sentence) > 0: sentences.append(review_to_wordlist(raw_sentence, remove_stopwords)) return sentences #logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) sentences = [] print("Parsing sentences from training set...") for review in data["review"]: sentences += review_to_sentences(review, tokenizer) print(len(sentences)) print(sentences[0]) # это понадобится нам позже with open('clean_text.txt', 'w') as f: for s in sentences[:5000]: f.write(' '.join(s)) f.write('\n') ###Output _____no_output_____ ###Markdown Обучаем и сохраняем модель. Основные параметры:* данные должны быть итерируемым объектом * size — размер вектора, * window — размер окна наблюдения,* min_count — мин. частотность слова в корпусе,* sg — используемый алгоритм обучения (0 — CBOW, 1 — Skip-gram),* sample — порог для downsampling'a высокочастотных слов,* workers — количество потоков,* alpha — learning rate,* iter — количество итераций,* max_vocab_size — позволяет выставить ограничение по памяти при создании словаря (т.е. если ограничение превышается, то низкочастотные слова будут выбрасываться). Для сравнения: 10 млн слов = 1Гб RAM.**NB!** Обратите внимание, что тренировка модели не включает препроцессинг! Это значит, что избавляться от пунктуации, приводить слова к нижнему регистру, лемматизировать их, проставлять частеречные теги придется до тренировки модели (если, конечно, это необходимо для вашей задачи). Т.е. в каком виде слова будут в исходном тексте, в таком они будут и в модели. ###Code print("Training model...") %time model_en = word2vec.Word2Vec(sentences, workers=4, size=300, min_count=10, window=10, sample=1e-3) ###Output Training model... CPU times: user 4min 42s, sys: 1.7 s, total: 4min 43s Wall time: 1min 39s ###Markdown Смотрим, сколько в модели слов. ###Code print(len(model_en.wv.vocab)) ###Output 28308 ###Markdown Попробуем оценить модель вручную, порешав примеры. Несколько дано ниже, попробуйте придумать свои. ###Code print(model_en.wv.most_similar(positive=["woman", "actor"], negative=["man"], topn=1)) print(model_en.wv.most_similar(positive=["dogs", "man"], negative=["dog"], topn=1)) print(model_en.wv.most_similar("usa", topn=3)) print(model_en.wv.doesnt_match("comedy thriller western novel".split())) ###Output [('actress', 0.7812775373458862)] [('men', 0.6456037759780884)] [('europe', 0.7496109008789062), ('china', 0.7072895765304565), ('north', 0.7071902751922607)] novel ###Markdown Как дообучить существующую модельПри тренировке модели "с нуля" веса инициализируются случайно, однако можно использовать для инициализации векторов веса из предобученной модели, таким образом как бы дообучая ее.Сначала посмотрим близость какой-нибудь пары слов в имеющейся модели, чтобы потом сравнить результат с дообученной. ###Code model_en.wv.similarity('lion', 'rabbit') ###Output /usr/local/lib/python3.5/dist-packages/gensim/matutils.py:737: FutureWarning: Conversion of the second argument of issubdtype from `int` to `np.signedinteger` is deprecated. In future, it will be treated as `np.int64 == np.dtype(int).type`. if np.issubdtype(vec.dtype, np.int): ###Markdown В качестве дополнительных данных для обучения возьмем английский текст «Алисы в Зазеркалье». ###Code ! wget https://raw.githubusercontent.com/ancatmara/data-science-nlp/master/data/w2v/train/alice.txt with open("alice.txt", 'r', encoding='utf-8') as f: text = f.read() text = re.sub('\n', ' ', text) sents = sent_tokenize(text) punct = '!"#$%&()*+,-./:;<=>?@[\]^_`{|}~„“«»†*—/\-‘’' clean_sents = [] for sent in sents: s = [w.lower().strip(punct) for w in sent.split()] clean_sents.append(s) print(clean_sents[:2]) ###Output [['through', 'the', 'looking-glass', 'by', 'lewis', 'carroll', 'chapter', 'i', 'looking-glass', 'house', 'one', 'thing', 'was', 'certain', 'that', 'the', 'white', 'kitten', 'had', 'had', 'nothing', 'to', 'do', 'with', 'it', '', 'it', 'was', 'the', 'black', 'kitten’s', 'fault', 'entirely'], ['for', 'the', 'white', 'kitten', 'had', 'been', 'having', 'its', 'face', 'washed', 'by', 'the', 'old', 'cat', 'for', 'the', 'last', 'quarter', 'of', 'an', 'hour', 'and', 'bearing', 'it', 'pretty', 'well', 'considering', 'so', 'you', 'see', 'that', 'it', 'couldn’t', 'have', 'had', 'any', 'hand', 'in', 'the', 'mischief']] ###Markdown Чтобы дообучить модель, надо сначала ее сохранить, а потом загрузить. Все параметры тренировки (размер вектора, мин. частота слова и т.п.) будут взяты из загруженной модели, т.е. задать их заново нельзя.**NB!** Дообучить можно только полную модель, а `KeyedVectors` — нельзя. Поэтому сохранять модель нужно в соотвествующем формате. Подробнее о разнице [вот тут](https://radimrehurek.com/gensim/models/keyedvectors.html). ###Code model_path = "movie_reviews.model" print("Saving model...") model_en.save(model_path) model = word2vec.Word2Vec.load(model_path) model.build_vocab(clean_sents, update=True) model.train(clean_sents, total_examples=model.corpus_count, epochs=5) ###Output _____no_output_____ ###Markdown Лев и кролик стали ближе друг к другу! ###Code model.wv.similarity('lion', 'rabbit') ###Output /usr/local/lib/python3.5/dist-packages/gensim/matutils.py:737: FutureWarning: Conversion of the second argument of issubdtype from `int` to `np.signedinteger` is deprecated. In future, it will be treated as `np.int64 == np.dtype(int).type`. if np.issubdtype(vec.dtype, np.int): ###Markdown Можно нормализовать вектора, тогда модель будет занимать меньше RAM. Однако после этого её нельзя дотренировывать. Здесь используется L2-нормализация: вектора нормализуются так, что если сложить квадраты всех элементов вектора, в сумме получится 1. Кроме того, сохраним не полные вектора, а `KeyedVectors`. ###Code model.init_sims(replace=True) model_path = "movies_alice.bin" print("Saving model...") model_en.wv.save_word2vec_format(model_path, binary=True) ###Output Saving model... ###Markdown ОценкаЭто, конечно, хорошо, но как понять, какая модель лучше? Или вот, например, я сделал свою модель, а как понять, насколько она хорошая?Для этого существуют специальные датасеты для оценки качества дистрибутивных моделей. Основных два: один измеряет точность решения задач на аналогии (про Россию и пельмени), а второй используется для оценки коэффициента семантической близости. Word SimilarityЭтот метод заключается в том, чтобы оценить, насколько представления о семантической близости слов в модели соотносятся с "представлениями" людей.| слово 1 | слово 2 | близость | |------------|------------|----------|| кошка | собака | 0.7 | | чашка | кружка | 0.9 | Для каждой пары слов из заранее заданного датасета мы можем посчитать косинусное расстояние, и получить список таких значений близости. При этом у нас уже есть список значений близостей, сделанный людьми. Мы можем сравнить эти два списка и понять, насколько они похожи (например, посчитав корреляцию). Эта мера схожести должна говорить о том, насколько модель хорошо моделирует расстояния до слова. АналогииДругая популярная задача для "внутренней" оценки называется задачей поиска аналогий. Как мы уже разбирали выше, с помощью простых арифметических операций мы можем модифицировать значение слова. Если заранее собрать набор слов-модификаторов, а также слов, которые мы хотим получить в результаты модификации, то на основе подсчёта количества "попаданий" в желаемое слово мы можем оценить, насколько хорошо работает модель.В качестве слов-модификаторов мы можем использовать семантические аналогии. Скажем, если у нас есть некоторое отношение "страна-столица", то для оценки модели мы можем использовать пары наподобие "Россия-Москва", "Норвегия-Осло", и т.д. Датасет будет выглядеть следующм образом:| слово 1 | слово 2 | отношение | |------------|------------|---------------|| Россия | Москва | страна-столица| | Норвегия | Осло | страна-столица|Рассматривая случайные две пары из этого набора, мы хотим, имея триплет (Россия, Москва, Норвегия) хотим получить слово "Осло", т.е. найти такое слово, которое будет находиться в том же отношении со словом "Норвегия", как "Россия" находится с Москвой. Датасеты для русского языка можно скачать на странице с моделями на RusVectores. Посчитаем качество нашей модели НКРЯ на датасете про аналогии: ###Code ! wget https://raw.githubusercontent.com/ancatmara/data-science-nlp/master/data/w2v/evaluation/ru_analogy_tagged.txt res = model_ru.accuracy('ru_analogy_tagged.txt') print(res[4]['incorrect'][:10]) ###Output [('МАЛЬЧИК_S', 'ДЕВОЧКА_S', 'ДЕД_S', 'БАБКА_S'), ('МАЛЬЧИК_S', 'ДЕВОЧКА_S', 'КОРОЛЬ_S', 'КОРОЛЕВА_S'), ('МАЛЬЧИК_S', 'ДЕВОЧКА_S', 'ПРИНЦ_S', 'ПРИНЦЕССА_S'), ('МАЛЬЧИК_S', 'ДЕВОЧКА_S', 'ОТЧИМ_S', 'МАЧЕХА_S'), ('МАЛЬЧИК_S', 'ДЕВОЧКА_S', 'ПАСЫНОК_S', 'ПАДЧЕРИЦА_S'), ('БРАТ_S', 'СЕСТРА_S', 'ДЕД_S', 'БАБКА_S'), ('БРАТ_S', 'СЕСТРА_S', 'ОТЧИМ_S', 'МАЧЕХА_S'), ('БРАТ_S', 'СЕСТРА_S', 'ПАСЫНОК_S', 'ПАДЧЕРИЦА_S'), ('ПАПА_S', 'МАМА_S', 'ДЕД_S', 'БАБКА_S'), ('ПАПА_S', 'МАМА_S', 'ОТЧИМ_S', 'МАЧЕХА_S')] ###Markdown ВизуализацияНа полученную модель можно посмотреть, визуализировав ее, например, на плоскости. t-SNE**t-SNE** (*t-distributed Stochastic Neighbor Embedding*) — техника нелинейного снижения размерности и визуализации многомерных переменных. Она разработана специально для данных высокой размерности Л. ван дер Маатеном и Д. Хинтоном, [вот их статья](http://jmlr.org/papers/volume9/vandermaaten08a/vandermaaten08a.pdf). t-SNE — это итеративный алгоритм, основанный на вычислении попарных расстояний между всеми объектами (в том числе поэтому он довольно медленный).![tsne](https://raw.githubusercontent.com/maryszmary/nlp-netology/master/3/TSNE.jpg)Изобразим на плоскости 1000 самых частотных слов из коллекции текстов про кино: ###Code from nltk import FreqDist from tqdm import tqdm_notebook as tqdm from sklearn.manifold import TSNE top_words = [] fd = FreqDist() for s in tqdm(sentences): fd.update(s) for w in fd.most_common(1000): top_words.append(w[0]) print(top_words[:50:]) top_words_vec = model[top_words] top_words_vec = model[top_words] %%time tsne = TSNE(n_components=2, random_state=0) top_words_tsne = tsne.fit_transform(top_words_vec) # !pip install bokeh from bokeh.models import ColumnDataSource, LabelSet from bokeh.plotting import figure, show, output_file from bokeh.io import output_notebook output_notebook() p = figure(tools="pan,wheel_zoom,reset,save", toolbar_location="above", title="word2vec T-SNE (eng model, top1000 words)") source = ColumnDataSource(data=dict(x1=top_words_tsne[:,0], x2=top_words_tsne[:,1], names=top_words)) p.scatter(x="x1", y="x2", size=8, source=source) labels = LabelSet(x="x1", y="x2", text="names", y_offset=6, text_font_size="8pt", text_color="#555555", source=source, text_align='center') p.add_layout(labels) show(p) ###Output _____no_output_____ ###Markdown Чтобы вычислить преобразование t-SNE быстрее (и иногда еще и эффективнее), можно сперва снизить размерность исходных данных с помощью, например, SVD, и потом применять t-SNE: ###Code from sklearn.decomposition import TruncatedSVD svd_50 = TruncatedSVD(n_components=50) top_words_vec_50 = svd_50.fit_transform(top_words_vec) top_words_tsne2 = TSNE(n_components=2, random_state=0).fit_transform(top_words_vec_50) output_notebook() p = figure(tools="pan,wheel_zoom,reset,save", toolbar_location="above", title="word2vec T-SNE (eng model, top1000 words, +SVD)") source = ColumnDataSource(data=dict(x1=top_words_tsne2[:,0], x2=top_words_tsne2[:,1], names=top_words)) p.scatter(x="x1", y="x2", size=8, source=source) labels = LabelSet(x="x1", y="x2", text="names", y_offset=6, text_font_size="8pt", text_color="#555555", source=source, text_align='center') p.add_layout(labels) show(p) ###Output _____no_output_____ ###Markdown FastTextFastText использует не только эмбеддинги слов, но и эмбеддинги n-грам. В корпусе каждое слово автоматически представляется в виде набора символьных n-грамм. Скажем, если мы установим n=3, то вектор для слова "where" будет представлен суммой векторов следующих триграм: "" (где "" символы, обозначающие начало и конец слова). Благодаря этому мы можем также получать вектора для слов, отсутствуюших в словаре, а также эффективно работать с текстами, содержащими ошибки и опечатки.* [Статья](https://aclweb.org/anthology/Q17-1010)* [Сайт](https://fasttext.cc/)* [Тьюториал](https://fasttext.cc/docs/en/support.html)* [Вектора для 157 языков](https://fasttext.cc/docs/en/crawl-vectors.html)* [Вектора, обученные на википедии](https://fasttext.cc/docs/en/pretrained-vectors.html) (отдельно для 294 разных языков)* [Репозиторий](https://github.com/facebookresearch/fasttext)Есть библиотека `fasttext` для питона (с готовыми моделями можно работать и через `gensim`). ###Code ! git clone https://github.com/facebookresearch/fastText.git ! pip3 install fastText/. import fasttext # так можно обучить свою модель ft_model = fasttext.train_unsupervised('clean_text.txt', minn=3, maxn=4, dim=300) ft_model.get_word_vector("movie") ft_model.get_nearest_neighbors('actor') ft_model.get_analogies("woman", "man", "actor") # проблема с опечатками решена ft_model.get_nearest_neighbors('actr') # проблема с out of vocabulary словами - тоже ft_model.get_nearest_neighbors('moviegeek') ###Output _____no_output_____
Genetics.ipynb
###Markdown Genetics ###Code from genomics import * add_codon(12) ###Output _____no_output_____ ###Markdown TODO Eukaryotic 5'UTR sequence Kozak consensus sequenceACCAUGGThe Kozak consensus sequence, Kozak consensus or Kozak sequence is a sequence which occurs on eukaryotic mRNA and has the consensus (gcc)gccRccAUGG. The Kozak consensus sequence plays a major role in the initiation of the translation process.[1] The sequence was named after the scientist who discovered it, Marilyn Kozak.The sequence is identified by the notation (gcc)gccRccAUGG, which summarizes data analysed by Kozak from a wide variety of sources (about 699 in all)[2] as follows:a lower-case letter denotes the most common base at a position where the base can nevertheless vary;upper-case letters indicate highly conserved bases, i.e. the 'AUGG' sequence is constant or rarely, if ever, changes, with the exception being the IUPAC ambiguity code [3] 'R' which indicates that a purine (adenine or guanine) is always observed at this position (with adenine being claimed by Kozak to be more frequent); andthe sequence in parentheses (gcc) is of uncertain significance. Variations in the consensus sequenceThe Kozak consensus has been variously described as:{{cite journal |last1=Tang |first1=Sen-Lin |last2=Chang |first2=Bill C.H. |last3=Halgamuge |first3=Saman K. |title=Gene functionality's influence on the second codon: A large-scale survey of second codon composition in three domains |journal=Genomics |date=August 2010 |volume=96 |issue=2 |pages=92–101 |doi=10.1016/j.ygeno.2010.04.001 |url=https://www.sciencedirect.com/science/article/pii/S0888754310000984 |accessdate=3 August 2018}}``` (gcc)gccRccAUGG (Kozak 1987) AGNNAUGN ANNAUGG ACCAUGG (Spotts et al., 1997, mentioned in Kozak 2002) GACACCAUGG (''H. sapiens HBB, HBD'', ''R. norvegicus Hbb'', etc.) ``` ###Code print(generate_dna()) print(transcribe_dna_to_rna(generate_dna())) codon_count = lambda x: random.randint(10,100) sequence = generate_dna(10, codon_count) rna = transcribe_dna_to_rna(sequence) proteins = translate_rna(rna) print("DNA") print(sequence) print() print("mRNA from DNA via transcription") print(rna) print() print("Proteins from mRNA via translation") for protein in proteins: print(protein) print() print("Angiotensin-1") print("Asp-Arg-Val-Tyr-Ile-His-Pro-Phe-His-Leu") print("DRVYIHPFHL") print(">NP_000020.1:34-43 angiotensinogen preproprotein [Homo sapiens]") print("DRVYIHPFHL") seq = openFasta("Angiotensinogen.fa") for key in seq: rna = transcribe_dna_to_rna(seq[key]) polypeptides = translate_rna(rna) if polypeptides: print() print(key) print() print("BEGIN PROTEIN SEQUENCES") print() for i,p in enumerate(polypeptides): print(f">RBC_000000.0{i} 1:{len(p)} {key[1:]}") print_wrap(p, offsets=False) ###Output SKIPPED NUCLEOTIDES: 1 to 40 1 : GAAGAAGCUGCCGUUGUUCUGGGUACUACAGCAGAAGGGU : 40 SKIPPED NUCLEOTIDES: 1499 to 1593 1 : GGCCAGGGCCCCAGAACACAGUGCCUGGCAAGGCCUCUGCCCCUGGCCUUUGAGGCAAAGGCCAGCAGCA : 70 71 : GAUAACAACCCCGGACAAAUCAGCG : 95 SKIPPED NUCLEOTIDES: 1699 to 1716 1 : AAGCCUGCAGCGGCACAA : 18 SKIPPED NUCLEOTIDES: 1834 to 1933 1 : AACAAAAAAGUGUUCCCUUUUCAAGUUGAGAACAAAAAUUGGGUUUUAAAAUUAAAGUAUACAUUUUUGC : 70 71 : AUUGCCUUCGGUUUGUAUUUAGUGUCUUGA : 100 SKIPPED NUCLEOTIDES: 1940 to 1943 1 : GAAC : 4 SKIPPED NUCLEOTIDES: 1959 to 1987 1 : UGUCUGUAAUACCUUAGUUUUUUCCACAG : 29 SKIPPED NUCLEOTIDES: 2033 to 2044 1 : AUUUCUGUUUGA : 12 PEPTIDE SEQUENCE W/O END CODON >NM_000029.4 Homo sapiens angiotensinogen (AGT), mRNA BEGIN PROTEIN SEQUENCES >RBC_000000.00 1:485 NM_000029.4 Homo sapiens angiotensinogen (AGT), mRNA MRKRAPQSEMAPAGVRLRATILCLLAWAGLAAGDRVYIHPFHLVIHNERTCEQLAKANAGKPKDPTFIPA PIQAKTSPVDEKALQDQLVLVAAKLDTEDKLRAAMVGMLANFLGFRIYGMHRELWGVVHGATVLSPTAVF GTLASLYLGALDHTADRLQAILGVPWKDKNCTSRLDAHKVLSALQAVQGLLVAQGRADRQAQLLLSTVVG VFTAPGLHLKQPFVQGLALYTPVVLPRSLDFTELDVAAEKIDRFMQAVTGWKTGCSLMGARVDRTLAFNT YVHFQGKMKGFSLLAEPQEFWVDNRTSVSVPMLSGMGTFQHWRDIQDNFSVTQVPFTERACLLLIQPHYA SDLDKVEGLTFQQNSLNWMKKLSPRTIHLTMPQLVLQGSYDLQDLLAQAELPAILHTELNLQKLRNDRIR VGEVLNRIFFELEADEREPTESTQQLNKPEVLEVTLNRPFLFAVYDQRATALHFLGRVANPLRTA >RBC_000000.01 1:34 NM_000029.4 Homo sapiens angiotensinogen (AGT), mRNA MCHPQSPTFSSNESTLRWKAAVSPWSKCAAWREQ >RBC_000000.02 1:38 NM_000029.4 Homo sapiens angiotensinogen (AGT), mRNA MHLPVCWVYFREWGWGGKNQCLARDYCSKKNSNRPACL >RBC_000000.03 1:1 NM_000029.4 Homo sapiens angiotensinogen (AGT), mRNA M >RBC_000000.04 1:4 NM_000029.4 Homo sapiens angiotensinogen (AGT), mRNA MTSV >RBC_000000.05 1:14 NM_000029.4 Homo sapiens angiotensinogen (AGT), mRNA MLVIFEQYVKDART >RBC_000000.06 1:24 NM_000029.4 Homo sapiens angiotensinogen (AGT), mRNA MRNHRWLFLPCVRNKRLATIRLQK
spark/PyDelhi/PySpark.ipynb
###Markdown If the notebook is run locally, then sc (SparkContext) would be pre-configured. If running using binder, we need to create SparkContext. ###Code #This notebook comes with a pre-configured sparkContext called sc try: sc except NameError: sc = SparkContext(master='spark://master:7077') with open("data/sequence.txt") as f: sequence = [x.strip('\n') for x in f.readlines()] file_rdd = sc.parallelize(sequence) with open("data/people.json") as f: json_data = [x.strip('\n') for x in f.readlines()] json_rdd = sc.parallelize(json_data) else: file_rdd = sc.textFile("data/sequence.txt") json_rdd = sc.textFile("data/people.json") sc #RDDs dummy_list = range(1000) #this is a list print type(dummy_list) rddlist = sc.parallelize(dummy_list) #this is a RDD print type(rddlist) #More RDDs print json_rdd.collect() print type(json_rdd.collect()) #Spark supports text files, SequenceFiles, and any other Hadoop InputFormat. start_time = time() filtered_rdd = file_rdd.filter(lambda x: len(x) < 2) end_time = time() print "Time taken (in seconds) = " + str(end_time - start_time) start_time = time() filtered_data = file_rdd.filter(lambda x: len(x) < 2).collect() end_time = time() print "Time taken (in seconds) = " + str(end_time - start_time) start_time = time() mapped_rdd = file_rdd.map(lambda x: 2*x) end_time = time() print "Time taken (in seconds) = " + str(end_time - start_time) start_time = time() mapped_data = file_rdd.map(lambda x: 2*x).collect() end_time = time() print "Time taken (in seconds) = " + str(end_time - start_time) print type(filtered_rdd) print type(filtered_data) print type(mapped_rdd) print type(mapped_data) print "Conclusion: RDDs are lazy. They do nothing unless there is an action is called." start_time = time() print len(file_rdd.map(lambda x: 2*x).filter(lambda x: len(x)>1).take(10)) end_time = time() print "Time taken (in seconds) = " + str(end_time - start_time) start_time = time() print len(file_rdd.map(lambda x: 2*x).filter(lambda x: len(x)>1).take(100000)) end_time = time() print "Time taken (in seconds) = " + str(end_time - start_time) start_time = time() print len(file_rdd.map(lambda x: 2*x).filter(lambda x: len(x)>1).collect()) end_time = time() print "Time taken (in seconds) = " + str(end_time - start_time) print "Lazy is better." start_time = time() print "We want to count the number of 1, 2, ... digit numbers." # file_path = "data/sequence.txt" # file_rdd = sc.textFile(file_path) mapped_rdd = file_rdd.map(lambda a: (len(a), 1)) count_rdd = mapped_rdd.reduceByKey(lambda a, b: a+b).sortByKey() print count_rdd.collect() end_time = time() print "Time taken (in seconds) = " + str(end_time - start_time) start_time = time() print "We want to count the number of 1, 2, ... digit numbers." mapped_data = np.asarray(map(lambda a: (len(a), 1), file_rdd.collect())) # count_map = mapped_rdd.reduceByKey(lambda a, b: a+b).sortByKey().collect() # print count_map end_time = time() print "Time taken (in seconds) = " + str(end_time - start_time) print "Lets add all the numbers. We have two ways of doing that." print "Approach 1: update a counter variable" counter = 0 def increment_counter(x): global counter counter+=x mapped_rdd = file_rdd.map(lambda a: int(a)) mapped_rdd.foreach(increment_counter) print "Sum using first approach: ", counter print "Approach 2: use reduce operation" print "Sum using second appraoch: ", mapped_rdd.reduce(operator.add) print "Which one is correct?" accum = sc.accumulator(0) mapped_rdd.foreach(lambda x: accum.add(x)) print("Actual sum: ", accum.value) print "So far we talked about big data. What about structured big data?" sqlContext = SQLContext(sc) sqlContext #dataframes df = sqlContext.read.json("data/people.json") df.show() print "A DataFrame is the structured version of RDD. This is the familiar relational view of the data." df.printSchema() print "DF can infer schema on its own. We can always override the inferred schema." rdd_df = file_rdd.map(lambda a: Row(a)).toDF() rdd_df.show() rdd_df.printSchema() # rdd_df = file_rdd.map(lambda a: Row(int(a))).toDF() # rdd_df.show() # rdd_df.printSchema() df.show() print "DF can be queried in two ways: API and sql queries" print "First method: API" df.select(df['first_name'], df['gender']).show() df.groupBy(df["gender"]).count().show() df.groupBy(df["email"]).agg(func.count(df["email"]).alias("count")).orderBy("count", ascending=False).show() print "Second method: sql" df.registerTempTable("people") sqlContext.sql("SELECT * FROM people WHERE gender = 'Female'").show() print "We can define our own functions as well." domain = func.udf(lambda s: s.split('@')[1], StringType()) df.select(domain(df.email).alias('domain'))\ .groupBy('domain').agg(func.count('domain').alias("count")).orderBy("count", ascending=False).show() ###Output We can define our own functions as well. +--------------------+-----+ | domain|count| +--------------------+-----+ | alibaba.com| 8| | 163.com| 7| | examiner.com| 7| | friendfeed.com| 6| | lulu.com| 6| | free.fr| 6| | fda.gov| 6| | apple.com| 6| | woothemes.com| 6| | cornell.edu| 6| | sourceforge.net| 6| | mlb.com| 6| | wikia.com| 5| | engadget.com| 5| |pagesperso-orange.fr| 5| | usa.gov| 5| | wordpress.org| 5| | cbslocal.com| 5| | ucla.edu| 5| | pbs.org| 5| +--------------------+-----+ only showing top 20 rows
RGB2Normal_CeyhunIbolar.ipynb
###Markdown ###Code %%capture %cd /content !rm -r RGBD2Normal !git clone https://github.com/cibolar/RGBD2Normal ###Output _____no_output_____ ###Markdown /content/drive/MyDrive/RGBD2Normal/pre_trained ###Code %cd /content/RGBD2Normal ########################## # Test normal estimation # RGBD input # coupled with train_RGBD_ms.py # Jin Zeng, 20181031 ######################### import sys sys.path.append('/content/RGBD2Normal/models/') sys.path.append('/content/RGBD2Normal/loader/') sys.path.append('/content/RGBD2Normal/pre_trained/') import cv2 import sys, os import torch import argparse import timeit import numpy as np import scipy.misc as misc import torch.nn as nn import torch.nn.functional as F import torchvision.models as models from os.path import join as pjoin import scipy.io as io from torch.autograd import Variable from torch.utils import data from tqdm import tqdm from models import get_model, get_lossfun from loader import get_data_path, get_loader from pre_trained import get_premodel from utils import norm_imsave, change_channel from models.eval import eval_normal_pixel, eval_print from loader.loader_utils import png_reader_32bit, png_reader_uint8 def test(args): # Setup Model # Setup the fusion model (RGB+Depth) model_name_F = args.arch_F model_F = get_model(model_name_F, True) # concat and output model_F = torch.nn.DataParallel(model_F, device_ids=range(torch.cuda.device_count())) # Setup the map model if args.arch_map == 'map_conv': model_name_map = args.arch_map model_map = get_model(model_name_map, True) # concat and output model_map = torch.nn.DataParallel(model_map, device_ids=range(torch.cuda.device_count())) if args.model_full_name != '': # Use the full name of model to load print("Load training model: " + args.model_full_name) checkpoint = torch.load(pjoin(args.model_savepath, args.model_full_name)) model_F.load_state_dict(checkpoint['model_F_state']) model_map.load_state_dict(checkpoint["model_map_state"]) # Setup image if args.imgset: print("Test on dataset: {}".format(args.dataset)) data_loader = get_loader(args.dataset) data_path = get_data_path(args.dataset) v_loader = data_loader(data_path, split=args.test_split, img_size=(args.img_rows, args.img_cols), img_norm=args.img_norm) evalloader = data.DataLoader(v_loader, batch_size=1) print("Finish Loader Setup") model_F.cuda() model_F.eval() if args.arch_map == 'map_conv': model_map.cuda() model_map.eval() sum_mean, sum_median, sum_small, sum_mid, sum_large, sum_num = [], [], [], [], [], [] evalcount = 0 with torch.no_grad(): for i_val, (images_val, labels_val, masks_val, valids_val, depthes_val, meshdepthes_val) in tqdm( enumerate(evalloader)): images_val = Variable(images_val.contiguous().cuda()) labels_val = Variable(labels_val.contiguous().cuda()) masks_val = Variable(masks_val.contiguous().cuda()) valids_val = Variable(valids_val.contiguous().cuda()) depthes_val = Variable(depthes_val.contiguous().cuda()) if args.arch_map == 'map_conv': outputs_valid = model_map(torch.cat((depthes_val, valids_val[:, np.newaxis, :, :]), dim=1)) outputs, outputs1, outputs2, outputs3, output_d = model_F(images_val, depthes_val, outputs_valid.squeeze(1)) else: outputs, outputs1, outputs2, outputs3, output_d = model_F(images_val, depthes_val, valids_val) outputs_n, pixelnum, mean_i, median_i, small_i, mid_i, large_i = eval_normal_pixel(outputs, labels_val, masks_val) outputs_norm = np.squeeze(outputs_n.data.cpu().numpy(), axis=0) labels_val_norm = np.squeeze(labels_val.data.cpu().numpy(), axis=0) images_val = np.squeeze(images_val.data.cpu().numpy(), axis=0) images_val = images_val + 0.5 images_val = images_val.transpose(1, 2, 0) depthes_val = np.squeeze(depthes_val.data.cpu().numpy(), axis=0) depthes_val = np.transpose(depthes_val, [1, 2, 0]) depthes_val = np.repeat(depthes_val, 3, axis=2) outputs_norm = change_channel(outputs_norm) labels_val_norm = (labels_val_norm + 1) / 2 labels_val_norm = change_channel(labels_val_norm) # if (i_val+1)%10 == 0: misc.imsave(pjoin(args.testset_out_path, "{}_MS_hyb.png".format(i_val + 1)), outputs_norm) misc.imsave(pjoin(args.testset_out_path, "{}_gt.png".format(i_val + 1)), labels_val_norm) misc.imsave(pjoin(args.testset_out_path, "{}_in.jpg".format(i_val + 1)), images_val) misc.imsave(pjoin(args.testset_out_path, "{}_depth.png".format(i_val + 1)), depthes_val) # accumulate the metrics in matrix if ((np.isnan(mean_i)) | (np.isinf(mean_i)) == False): sum_mean.append(mean_i) sum_median.append(median_i) sum_small.append(small_i) sum_mid.append(mid_i) sum_large.append(large_i) sum_num.append(pixelnum) evalcount += 1 if (i_val + 1) % 10 == 0: print("Iteration %d Evaluation Loss: mean %.4f, median %.4f, 11.25 %.4f, 22.5 %.4f, 30 %.4f" % ( i_val + 1, mean_i, median_i, small_i, mid_i, large_i)) # Summarize the result eval_print(sum_mean, sum_median, sum_small, sum_mid, sum_large, sum_num, item='Pixel-Level') avg_mean = sum(sum_mean) / evalcount sum_mean.append(avg_mean) avg_median = sum(sum_median) / evalcount sum_median.append(avg_median) avg_small = sum(sum_small) / evalcount sum_small.append(avg_small) avg_mid = sum(sum_mid) / evalcount sum_mid.append(avg_mid) avg_large = sum(sum_large) / evalcount sum_large.append(avg_large) print( "evalnum is %d, Evaluation Image-Level Mean Loss: mean %.4f, median %.4f, 11.25 %.4f, 22.5 %.4f, 30 %.4f" % ( evalcount, avg_mean, avg_median, avg_small, avg_mid, avg_large)) sum_matrix = np.transpose([sum_mean, sum_median, sum_small, sum_mid, sum_large]) if args.model_full_name != '': sum_file = args.model_full_name[:-4] + '.csv' np.savetxt(sum_file, sum_matrix, fmt='%.6f', delimiter=',') print("Saving to %s" % (sum_file)) # end of dataset test else: if os.path.isdir(args.out_path) == False: os.mkdir(args.out_path) print("Read Input Image from : {}".format(args.img_path)) for i in os.listdir(args.img_path): if not i.endswith('.jpg'): continue print(i) input_f = args.img_path + i depth_f = args.depth_path + i[:-4] + '.png' output_f = args.out_path + i[:-4] + '_rgbd.png' img = cv2.imread(input_f) orig_size = img.shape[:-1] if args.img_rot: img = np.transpose(img, (1, 0, 2)) img = np.flipud(img) img = cv2.resize(img, (args.img_rows, args.img_cols)) # Need resize the image to model inputsize else: img = cv2.resize(img, (args.img_cols, args.img_rows)) # Need resize the image to model inputsize img = img.astype(np.float) if args.img_norm: img = (img - 128) / 255 # NHWC -> NCHW img = img.transpose(2, 0, 1) img = np.expand_dims(img, 0) img = torch.from_numpy(img).float() if args.img_rot: depth = png_reader_32bit(depth_f, (args.img_rows, args.img_cols)) depth = np.transpose(depth, (1, 0)) depth = np.flipud(depth) # valid = png_reader_uint8(mask_f, (args.img_rows,args.img_cols)) # valid = np.transpose(valid, (1,0)) # valid = np.flipud(valid) else: depth = png_reader_32bit(depth_f, (args.img_rows, args.img_cols)) # valid = png_reader_uint8(mask_f, (args.img_rows,args.img_cols)) depth = depth.astype(float) # Please change to the scale so that scaled_depth=1 corresponding to real 10m depth # matterpot depth=depth/40000 scannet depth=depth/10000 depth = depth / (args.d_scale) if depth.ndim == 3: # to dim 2 depth = depth[:, :, 0] # if valid.ndim == 3: #to dim 2 # valid = valid[:,:,0] # valid = 1-depth # valid[valid>1] = 1 valid = (depth > 0.0001).astype(float) # valid = depth.astype(float) depth = depth[np.newaxis, :, :] depth = np.expand_dims(depth, 0) valid = np.expand_dims(valid, 0) depth = torch.from_numpy(depth).float() valid = torch.from_numpy(valid).float() if torch.cuda.is_available(): model_F.cuda() model_F.eval() if args.arch_map == 'map_conv': model_map.cuda() model_map.eval() images = Variable(img.contiguous().cuda()) depth = Variable(depth.contiguous().cuda()) valid = Variable(valid.contiguous().cuda()) else: images = Variable(img) depth = Variable(depth) valid = Variable(valid) with torch.no_grad(): if args.arch_map == 'map_conv': outputs_valid = model_map(torch.cat((depth, valid[:, np.newaxis, :, :]), dim=1)) outputs, outputs1, outputs2, outputs3, output_d = model_F(images, depth, outputs_valid.squeeze(1)) else: outputs, outputs1, outputs2, outputs3, output_d = model_F(images, depth, outputs_valid) outputs_norm = norm_imsave(outputs) outputs_norm = np.squeeze(outputs_norm.data.cpu().numpy(), axis=0) # outputs_norm = misc.imresize(outputs_norm, orig_size) outputs_norm = np.array(change_channel(outputs_norm)) outputs_norm = outputs_norm.transpose(1, 2, 0) outputs_norm = (255*outputs_norm).astype(np.uint8) cv2.imwrite(output_f, outputs_norm) print("Complete") # end of test on no dataset images parser = argparse.ArgumentParser(description='Params') parser.add_argument('--arch_RGB', nargs='?', type=str, default='vgg_16_in', help='Architecture for RGB to use [\'vgg_16,vgg_16_in etc\']') parser.add_argument('--arch_D', nargs='?', type=str, default='unet_3_mask_in', help='Architecture for Depth to use [\'unet_3, unet_3_mask, unet_3_mask_in etc\']') parser.add_argument('--arch_F', nargs='?', type=str, default='fconv_ms', help='Architecture for Fusion to use [\'fconv,fconv_in, fconv_ms etc\']') parser.add_argument('--arch_map', nargs='?', type=str, default='map_conv', help='Architecture for confidence map to use [\'mask, map_conv etc\']') parser.add_argument('--model_savepath', nargs='?', type=str, default='./checkpoint/FCONV_MS', help='Path for model saving [\'checkpoint etc\']') parser.add_argument('--model_full_name', nargs='?', type=str, default='', help='The full name of the model to be tested.') parser.add_argument('--dataset', nargs='?', type=str, default='matterport', help='Dataset to use [\'nyuv2, matterport, scannet, etc\']') parser.add_argument('--test_split', nargs='?', type=str, default='', help='The split of dataset in testing') parser.add_argument('--loss', nargs='?', type=str, default='l1', help='Loss type: cosine, l1') parser.add_argument('--model_num', nargs='?', type=str, default='2', help='Checkpoint index [\'1,2,3, etc\']') parser.add_argument('--img_rows', nargs='?', type=int, default=256, help='Height of the input image, 256(mt), 240(nyu)') parser.add_argument('--img_cols', nargs='?', type=int, default=320, help='Width of the input image, 320(yinda and nyu)') parser.add_argument('--testset', dest='imgset', action='store_true', help='Test on set from dataloader, decided by --dataset | True by default') parser.add_argument('--no_testset', dest='imgset', action='store_false', help='Test on single image | True by default') parser.set_defaults(imgset=True) parser.add_argument('--testset_out_path', nargs='?', type=str, default='./result/mt_clean_small', help='Path of the output normal') parser.add_argument('--img_path', nargs='?', type=str, default='../Depth2Normal/Dataset/normal/', help='Path of the input image') parser.add_argument('--depth_path', nargs='?', type=str, default='../Depth2Normal/Dataset/normal/', help='Path of the input image, mt_data_clean!!!!!!!!!') parser.add_argument('--ir_path', nargs='?', type=str, default='../Depth2Normal/Dataset/ir_mask/', help='Path of the input image, mt_data_clean!!!!!!!!!') parser.add_argument('--out_path', nargs='?', type=str, default='../Depth2Normal/Dataset/normal/', help='Path of the output normal') parser.add_argument('--d_scale', nargs='?', type=int, default=40000, help='Depth scale for depth input. Set the scale to make the 1 in scaled depth equal to 10m.\ Only valid testing using image folder') parser.add_argument('--img_norm', dest='img_norm', action='store_true', help='Enable input image scales normalization [0, 1] | True by default') parser.add_argument('--no-img_norm', dest='img_norm', action='store_false', help='Disable input image scales normalization [0, 1] | True by default') parser.set_defaults(img_norm=True) parser.add_argument('--img_rotate', dest='img_rot', action='store_true', help='Enable input image transpose | False by default') parser.add_argument('--no-img_rotate', dest='img_rot', action='store_false', help='Disable input image transpose | False by default') parser.set_defaults(img_rot=False) !mkdir /content/RGBD2Normal/result args = parser.parse_args("") args.arch_F = 'fconv_ms' args.arch_map = 'map_conv' args.imgset = False args.img_path = '/content/RGBD2Normal/sample_pic/mt_rgb/' args.depth_path = '/content/RGBD2Normal/sample_pic/mt_depth/' args.d_scale = 40000 args.img_rows = 256 args.img_cols = 320 args.model_savepath = '/content/drive/MyDrive/RGBD2Normal/checkpoint/FCONV_MS/' args.model_full_name = 'fconv_ms_matterport_l1_2_hybrid_best.pkl' args.out_path = '/content/RGBD2Normal/result/demo_rgbd_mp/' test(args) ###Output Load training model: fconv_ms_matterport_l1_2_hybrid_best.pkl Read Input Image from : /content/RGBD2Normal/sample_pic/mt_rgb/ a250e8fe53bc4025816b3c48a34c7367_i1_0.jpg
labs/2.1.3.ipynb
###Markdown Тест с нагреваемой трубой ###Code def doall(a, temp): b = np.arange(len(a)) + 1 global test_id # plt.figure(figsize=(15, 6)) k, t = np.polyfit(b, a, 1) mnk_a, mnk_b, sigma_a, sigma_b = eval_mnk(b, a) assert(abs(mnk_a -t) + abs(mnk_b - k) < 1e-8) print("\n___Опыт " + str(test_id) + "____" ) plt.plot(b, a, 'o') b = np.r_[[0], b] plt.plot(b, k * b + t, label="["+str(test_id)+"] "+str(temp)+"$C^o$") #plt.xlim(-0.5, b.max() + 0.5) #plt.ylim(-100, a.max() * 1.1) l = 0.7 #m c = k * l * 2 RE_c = prodErrorR([0.001 / l, sigma_b / mnk_b]) sciPrintR(c, RE_c, "c (скорость звука) = ") m = 29e-3 r = 8.31 t0 = 273 temp += t0 gamma = m * c ** 2 / r / temp RE_gamma = prodErrorR([0.1 / temp, RE_c, RE_c]) sciPrintR(gamma, RE_gamma, "gamma = ") test_id += 1 global ct ct.append((c, temp)) ct = [] test_id = 1 plt_lab_figure(8, 2094) doall(np.array([257, 496, 746, 988, 1228, 1480, 1722, 1978]), 22) doall(np.array([266.7, 510.7, 760, 1014.3, 1267, 1521, 1773, 2038]), 40) doall(np.array([269.7, 519.5, 774.3, 1034, 1296, 1545, 1804, 2062]), 50) doall(np.array([277, 527.6, 786, 1050, 1310, 1566, 1830, 2094]), 60) plt.legend() plt.title("Тест с нагреваемой трубой") plt.savefig("2.1.3_1_a.png", papertype="a4", format="png", bbox_inches=0) plt.show() ct = np.array(ct) print(ct) print(ct[:, 1]) plt.figure(figsize=(14, 7)) plt.scatter(np.log(ct[:,1]), np.log(ct[:,0] + 273)) k,t = np.polyfit(np.log(ct[:,1]), np.log(ct[:,0] + 273), deg=1) grid = np.linspace(np.log(ct[:,1]).min(), np.log(ct[:,1]).max(), 1000) plt.plot(grid, grid*k + t, color="red") plt.grid() #plt.xlim(xmin=0, xmax=grid[-1]*1.05) #plt.ylim(ymin=0, ymax=k*grid[-1]*1.05 + t) plt.show() ###Output [[ 343.65 295. ] [ 354.105 313. ] [ 359.045 323. ] [ 363.85 333. ]] [ 295. 313. 323. 333.] ###Markdown !convert 2.1.3_1_a.png 2.1.3_1_a.pdf Тест с раздвижной трубой ###Code test_id = 0 def do2(freq, a): l = 700 m = 29e-3 r = 8.31 t0 = 273 # a -= a.min() global test_id test_id += 1 b = np.arange(len(a))[::-1] + 1 k, t = np.polyfit(b, a, 1) mnk_a, mnk_b, sigma_a, sigma_b = eval_mnk(b, a) #print(mnk_a, mnk_b, sigma_a, sigma_b, t, k) assert(abs(mnk_a -t) + abs(mnk_b - k) < 1e-8) print("\n___Опыт " + str(test_id) + "____" ) print("Частота = ", freq.mean()) additions = pd.DataFrame([a], columns=list(range(1, len(a) + 1))) display(additions) c = freq.mean() * k*2. / 1000 #Relative Error RE_c = prodErrorR([sigma_b / mnk_b, freq.std() / freq.mean()]) sciPrintR(c, RE_c, "c (скорость звука) = ") gamma = c**2 * m / (r * (t0 + 23)) RE_gamma = prodErrorR([RE_c, RE_c, 0.01/r, 2/(t0+23)]) sciPrintR(gamma, RE_gamma, "Гамма = ") plt.plot(b, a, 'o') plt.plot(b, k * b + t, label="[" + str(test_id) + "] " + str(int(freq.mean())) + "Hz") plt_lab_figure(7, 230) do2(np.array([3153, 3149, 3147]), np.array([23, 17.6, 12.1, 6.6, 1.2]) * 10) do2(np.array([4278, 4274, 4273]), np.array([23, 19.1, 15.01, 11, 6.9, 2.9]) * 10) do2(np.array([5017, 5012, 5010]), np.array([23, 19.6, 16.2, 12.8, 9.3, 5.9, 2.5])* 10) plt.title("Тест с раздвижной трубой") plt.grid() plt.legend() plt.savefig("2.1.3_2_a.png", papertype="a4", format="png", bbox_inches=0) plt.show() !convert 2.1.3_2_a.png 2.1.3_2_a.pdf ###Output ___Опыт 1____ Частота = 3149.66666667
evaluate_training_set_size.ipynb
###Markdown Plots ###Code import numpy as np import matplotlib_settings import matplotlib.pyplot as plt n_train = np.load("data/n_train.npy") mapes_qrnn = np.load("data/mapes_qrnn.npy") crpss_qrnn = np.load("data/crps_qrnn.npy") ql_qrnn = np.load("data/quantile_losses_qrnn.npy") mapes_bmci = np.load("data/mapes_bmci.npy") crpss_bmci = np.load("data/crps_bmci.npy") ql_bmci = np.load("data/quantile_losses_bmci.npy") ###Output _____no_output_____ ###Markdown MAPE & CRPS ###Code means_qrnn = mapes_qrnn.mean(axis = 1) std_qrnn = mapes_qrnn.std(axis = 1) means_bmci = mapes_bmci.mean(axis = 1) std_bmci = mapes_bmci.std(axis = 1) plt.style.use("/home/simonpf/.config/matplotlib/paper") fig, ax = plt.subplots(1, 2, figsize = (8,4)) ax[0].plot(n_train, means_qrnn, label = "QRNN", lw = 2, c = "C1") ax[0].fill_between(n_train, means_qrnn - std_qrnn, means_qrnn + std_qrnn, label = "QRNN", lw = 2, alpha = 0.3, color = "C1") ax[0].plot(n_train, means_bmci, label = "BMCI", lw = 2, c = "C2") ax[0].fill_between(n_train, means_bmci - std_bmci, means_bmci + std_bmci, label = "BMCI", lw = 2, alpha = 0.3, color = "C2") ax[0].set_title("(a) MAPE", loc = "left") ax[0].set_xscale("log") ax[0].set_xlim([10**3, 10**6]) ax[0].set_xlabel("$n_{train}$") ax[0].set_ylabel("MAPE") ax[0].set_ylim([0.0, 4.0]) means_qrnn = crpss_qrnn.mean(axis = 1) std_qrnn = crpss_qrnn.std(axis = 1) means_bmci = crpss_bmci.mean(axis = 1) std_bmci = crpss_bmci.std(axis = 1) ax[1].plot(n_train, means_qrnn, label = "QRNN", lw = 2, c = "C1") ax[1].fill_between(n_train, means_qrnn - std_qrnn, means_qrnn + std_qrnn, lw = 2, alpha = 0.3, color = "C1") ax[1].plot(n_train, means_bmci, label = "BMCI", lw = 2, c = "C2") ax[1].fill_between(n_train, means_bmci - std_bmci, means_bmci + std_bmci, lw = 2, alpha = 0.3, color = "C2") ax[1].set_title("(b) CRPS", loc = "left") ax[1].set_xscale("log") ax[1].set_xlim([10**3, 10**6]) ax[1].set_xlabel("$n_{train}$") ax[1].set_ylabel("CRPS") ax[1].set_ylim([0.0, 0.7]) ax[1].legend(loc = "upper center", bbox_to_anchor = [-0.15, -0.2], ncol = 2, fancybox = False) plt.tight_layout() fig.savefig("plots/mape_crps.pdf", bbox_inches = "tight") fig, axs = plt.subplots(1, 3, figsize = (12, 4)) mean_ql_qrnn = np.mean(ql_qrnn, axis = 1) std_ql_qrnn = np.std(ql_qrnn, axis = 1) mean_ql_bmci = np.mean(ql_bmci, axis = 1) std_ql_bmci = np.std(ql_bmci, axis = 1) # 10th percentile axs[0].plot(n_train, mean_ql_qrnn[:, 1], label = "QRNN", lw = 2, c = "C1") axs[0].fill_between(n_train, mean_ql_qrnn[:, 1] - std_ql_qrnn[:, 1], mean_ql_qrnn[:, 1] + std_ql_qrnn[:, 1], alpha = 0.4, color = "C1") axs[0].plot(n_train, mean_ql_bmci[:, 1], c = "C2") axs[0].fill_between(n_train, mean_ql_bmci[:, 1] - std_ql_bmci[:, 1], mean_ql_bmci[:, 1] + std_ql_bmci[:, 1], alpha = 0.4, color = "C2") axs[0].set_title(r"(a) $\tau = 0.1$", loc = "left") axs[0].set_xlim([10 ** 3, 10 ** 6]) axs[0].set_ylim([0.0, 0.3]) axs[0].set_xlabel(r"$n_{train}$") axs[0].set_xscale("log") axs[0].set_ylabel(r"$\mathcal{L}_{0.1}$") # median axs[1].plot(n_train, mean_ql_qrnn[:, 5], label = "QRNN", lw = 2, c = "C1") axs[1].fill_between(n_train, mean_ql_qrnn[:, 5] - std_ql_qrnn[:, 5], mean_ql_qrnn[:, 5] + std_ql_qrnn[:, 5], alpha = 0.4, color = "C1") axs[1].plot(n_train, mean_ql_bmci[:, 5], label = "BMCI", c = "C2") axs[1].fill_between(n_train, mean_ql_bmci[:, 5] - std_ql_bmci[:, 5], mean_ql_bmci[:, 5] + std_ql_bmci[:, 5], alpha = 0.4, color = "C2") axs[1].set_title(r"(b) $\tau = 0.5$", loc = "left") axs[1].set_xlabel(r"$n_{train}$") axs[1].set_xscale("log") axs[1].set_xlim([10 ** 3, 10 ** 6]) axs[1].set_ylim([0.0, 0.3]) axs[1].set_ylabel(r"$\mathcal{L}_{0.5}$") axs[1].legend(loc = "lower center", bbox_to_anchor = [0.5, -0.4], ncol = 2, fancybox = False) # 90th percentile axs[2].plot(n_train, mean_ql_qrnn[:, 10], label = "QRNN", lw = 2, c = "C1") axs[2].fill_between(n_train, mean_ql_qrnn[:, 10] - std_ql_qrnn[:, 10], mean_ql_qrnn[:, 10] + std_ql_qrnn[:, 10], alpha = 0.4, color = "C1") axs[2].plot(n_train, mean_ql_bmci[:, 10], label = "BMCI", c = "C2") axs[2].fill_between(n_train, mean_ql_bmci[:, 10] - std_ql_bmci[:, 10], mean_ql_bmci[:, 10] + std_ql_bmci[:, 10], alpha = 0.4, color = "C2") axs[2].set_title(r"(c) $\tau = 0.9$", loc = "left") axs[2].set_xlabel(r"$n_{train}$") axs[2].set_xscale("log") axs[2].set_ylim([0.0, 0.3]) axs[2].set_xlim([10 ** 3, 10 ** 6]) axs[2].set_ylabel(r"$\mathcal{L}_{0.9}$") plt.tight_layout() fig.savefig("plots/quantile_losses.pdf", bbox_inches = "tight") ###Output _____no_output_____
notebooks/Matplotlib in Pyhton.ipynb
###Markdown Data Visualization ###Code import numpy as np import matplotlib.pyplot as plt ###Output _____no_output_____ ###Markdown plt.plot for line plots ###Code # plt.plot? # plot(x, y, color='green', marker='o', linestyle='dashed',... linewidth=2, markersize=12) y = np.array([1,2,3,4,5,6,7,8,9]) plt.plot(y) # The array y passed is the y - coordinate, indexes are the x coordinates plt.show() y = y**2 plt.plot(y,marker='o') # The array y passed is the y - coordinate, indexes are the x coordinates plt.show() x = np.array([1,2,3,4,5,6,7,8,9]) y = np.array([1,4,9,16,25,36,49,64,81]) plt.plot(x,y,color="red",label='Stock Data',marker='^') # After plt.plot is mentioned plt.legend() plt.xlabel("X - Axis") plt.ylabel("Y - Axis") plt.title("Stock Data Representation") plt.show() plt.plot([1,2,3,4],[1,2,3,4],color='red',label='red label') plt.plot([1,2,3,4],[1,4,9,16],color='orange',label='orange label') plt.axis([0, 5, 0, 18]) plt.legend() plt.show() ###Output _____no_output_____ ###Markdown plt.scatter() ###Code x = np.array([1,2,3,4,5,6,7,8,9,10]) y1 = x y2 = x**2 plt.scatter(x,y1,color='red',label='Stock Data') plt.legend() plt.ylabel("Stock along this axis -> ") plt.show() plt.scatter(x,y2,color='red',label='Stock Data') plt.legend() plt.ylabel("Stock along this axis -> ") plt.show() plt.scatter(x,y2,color='green',label='Stock Data', marker='^') plt.legend() plt.ylabel("Stock along this axis -> ") plt.show() x = np.random.random((1000,2)) for ix in range(x.shape[0]): plt.scatter(x[ix,0],x[ix,1],c='green',marker='+') plt.show() ###Output _____no_output_____ ###Markdown Bar Graphs plt.bar() ###Code numbers = np.random.randint(0,10,5) indices = np.arange(5) print(numbers, indices, sep='\n') plt.bar(indices,numbers,label='label 1') plt.legend() plt.show() # plt.bar? # Syntax # plt.bar( # x, # height, # width=0.8, # bottom=None, # *, # align='center', # data=None, # **kwargs, # ) plt.bar(indices,numbers,width=0.2,label='label 1',color='red',align='center') plt.bar(indices+0.2,numbers*2,width=0.2,label='label 2',color='green') plt.legend() plt.xlabel("X label") plt.ylabel("Y label") plt.title(" This is the title") plt.show() ## Horizontal bar graph plt.barh(indices,numbers,label='label 1',color='red',align='center') plt.legend() plt.xlabel("X label") plt.ylabel("Y label") plt.title(" This is the title") plt.show() ###Output _____no_output_____ ###Markdown plt.pie() for pie charts ###Code sections = ['Algebra','Calculus','Coding','Algorithms'] values = [90,80,70,100] plt.pie(values,labels=sections,radius=1.5,explode=(0,1,0,0),shadow=True) plt.show() ###Output _____no_output_____ ###Markdown Histograms and Normal Distributions ###Code ## generating a 1-D normal distribution u = 5 sigma = 2 ## Standard normal distribution where u = 0 and sigma = 1 x1 = np.random.randn(1000) ## Normal distribution with u = 5 and sigma = 2 x2 = u + sigma*np.random.randn(1000) print(x1.shape) print(x2.shape) print(x2) plt.hist(x1,50) plt.xlabel("x - values") plt.ylabel("p(x)") plt.show() plt.hist(x2,100) plt.xlabel("x - values") plt.ylabel("p(x)") plt.show() vals = np.round(x2) z = np.unique(vals,return_counts=True) print(z) ## If I want to make a scatter plot x = np.random.randn(100) y = np.zeros(x.shape) plt.scatter(x,y) plt.show() ###Output _____no_output_____ ###Markdown Multivariate Normal Distribution ###Code mean = np.array([0.0, 0.0]) cov = np.array([[1,0],[0,1]]) ## sigma(x,y) = 0, so x and y are independent dist = np.random.multivariate_normal(mean,cov,1000) print(dist) plt.scatter(dist[:,0],dist[:,1]) plt.show() mean = np.array([5.0, 6.0]) cov = np.array([[1.3,0.4],[0.4,1.9]]) ## sigma(x,y) = 0.4, so x and y are dependent, positive co-relation dist = np.random.multivariate_normal(mean,cov,1000) print(dist) plt.scatter(dist[:,0],dist[:,1],color="orange") plt.show() ###Output _____no_output_____ ###Markdown Subplots ###Code x = np.array([1,2,3,4,5,6,7,8,9,10]) y1 = x y2 = x**2 y3 = x**3 y4 = x**4 plt.figure(figsize=(8,8)) plt.subplot(211) plt.plot(x,y1,color="red",label='Stock Data',marker='^') plt.legend() plt.subplot(212) plt.plot(x,y2,color="green",label='Stock Data',marker='o') plt.legend() plt.show() plt.figure(figsize=(8,8)) plt.subplot(121) plt.plot(x,y1,color="red",label='Stock Data',marker='^') plt.legend() plt.subplot(122) plt.plot(x,y2,color="green",label='Stock Data',marker='o') plt.legend() plt.show() plt.figure(figsize=(8,8)) plt.subplot(221) plt.plot(x,y1,color="red",label='Stock Data',marker='^') plt.legend() plt.subplot(222) plt.plot(x,y2,color="green",label='Stock Data',marker='o') plt.legend() plt.subplot(223) plt.plot(x,y2,color="blue",label='Stock') plt.legend() plt.subplot(224) plt.plot(x,y2,color="orange",label='Stock Data',marker='*') plt.legend() plt.show() plt.figure(figsize=(10,10)) plt.subplot(221) plt.title("Subplot 1 of 2 x 2") plt.plot(x,y1,color="red",label='Stock Data',marker='^') plt.legend() plt.subplot(222) plt.title("Subplot 2 of 2 x 2") plt.plot(x,y2,color="green",label='Stock Data',marker='o') plt.legend() plt.subplot(223) plt.title("Subplot 3 of 2 x 2") plt.plot(x,y2,color="blue",label='Stock') plt.legend() plt.subplot(224) plt.title("Subplot 4 of 2 x 2") plt.plot(x,y2,color="orange",label='Stock Data',marker='*') plt.legend() plt.show() from sklearn.datasets import make_regression,make_classification,make_blobs,make_moons from matplotlib import pyplot as plt X,Y = make_classification(n_samples =100,n_features=2,n_informative=2,n_redundant=0,n_classes=2) plt.figure(0,figsize=(8,8)) print(X.shape) print(Y.shape) plt.subplot(221) plt.scatter(X[:,0],X[:,1],c=Y,edgeColor='k') plt.subplot(222) X1, Y1 = make_classification(n_samples=200,n_features=2, n_redundant=0, n_informative=2, n_clusters_per_class=1, n_classes=3) plt.scatter(X1[:,0],X1[:,1],c=Y1,edgeColor='k') plt.subplot(223) X2, Y2 = make_blobs(n_features=2, centers=3) plt.scatter(X2[:,0],X2[:,1],c=Y2+1,edgeColor='k') plt.subplot(224) plt.title("Regression") X3, Y3= make_regression(n_features=1,n_samples=300,bias=4,noise=8) print(X3.shape,Y3.shape) plt.scatter(X3,Y3,color='green') plt.show() ###Output (100, 2) (100,) (300, 1) (300,)
docs/5_deep-learning-computation/5.2.ipynb
###Markdown 5.2. 参数管理一旦我们选择了架构并设置了超参数,我们就进入了训练阶段。此时,我们的目标是找到使损失函数最小化的参数值。经过训练后,我们将需要使用这些参数来做出未来的预测。此外,有时我们希望提取参数,以便在其他环境中复用它们,将模型保存到磁盘,以便它可以在其他软件中执行,或者为了获得科学的理解而进行检查。大多数情况下,我们可以忽略声明和操作参数的具体细节,而只依靠深度学习框架来完成繁重的工作。然而,当我们离开具有标准层的层叠架构时,我们有时会陷入声明和操作参数的麻烦中。在本节中,我们将介绍以下内容:* 访问参数,用于调试、诊断和可视化。* 参数初始化。* 在不同模型组件间共享参数我们首先关注具有单隐藏层的多层感知机。 ###Code import paddle from paddle import nn net = nn.Sequential(nn.Linear(4, 8), nn.ReLU(), nn.Linear(8, 1)) X = paddle.rand([2, 4]) net(X) ###Output _____no_output_____ ###Markdown 5.2.1. 参数访问我们从已有模型中访问参数。当通过Sequential类定义模型时,我们可以通过索引来访问模型的任意层。这就像模型是一个列表一样。每层的参数都在其属性中。如下所示,我们可以检查第二个全连接层的参数。 ###Code print(net[2].state_dict()) ###Output OrderedDict([('weight', Parameter containing: Tensor(shape=[8, 1], dtype=float32, place=CUDAPlace(0), stop_gradient=False, [[ 0.71925110], [-0.09674287], [ 0.48484957], [ 0.11552629], [-0.10340047], [ 0.81542194], [-0.43466821], [ 0.46107769]])), ('bias', Parameter containing: Tensor(shape=[1], dtype=float32, place=CUDAPlace(0), stop_gradient=False, [0.]))]) ###Markdown 5.2.1.1. 目标参数注意,每个参数都表示为参数(parameter)类的一个实例。要对参数执行任何操作,首先我们需要访问底层的数值。有几种方法可以做到这一点。有些比较简单,而另一些则比较通用。下面的代码从第二个神经网络层提取偏置,提取后返回的是一个参数类实例,并进一步访问该参数的值。 ###Code print(type(net[2].bias)) print(net[2].bias) print(net[2].bias.value) ###Output <class 'paddle.fluid.framework.ParamBase'> Parameter containing: Tensor(shape=[1], dtype=float32, place=CUDAPlace(0), stop_gradient=False, [0.]) <bound method PyCapsule.value of Parameter containing: Tensor(shape=[1], dtype=float32, place=CUDAPlace(0), stop_gradient=False, [0.])> ###Markdown 参数是复合的对象,包含值、梯度和额外信息。这就是为什么我们需要显式请求值的原因。除了值之外,我们还可以访问每个参数的梯度。由于我们还没有调用这个网络的反向传播,所以参数的梯度处于初始状态。 ###Code net[2].weight.grad == None ###Output /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/paddle/fluid/dygraph/varbase_patch_methods.py:373: UserWarning:  Warning: tensor.grad will return the tensor value of the gradient.  warnings.warn(warning_msg) ###Markdown 5.2.1.2. 一次性访问所有参数当我们需要对所有参数执行操作时,逐个访问它们可能会很麻烦。当我们处理更复杂的块(例如,嵌套块)时,情况可能会变得特别复杂,因为我们需要递归整个树来提取每个子块的参数。下面,我们将通过演示来比较访问第一个全连接层的参数和访问所有层。 ###Code print(*[(name, param.shape) for name, param in net[0].named_parameters()]) print(*[(name, param.shape) for name, param in net.named_parameters()]) ###Output ('weight', [4, 8]) ('bias', [8]) ('0.weight', [4, 8]) ('0.bias', [8]) ('2.weight', [8, 1]) ('2.bias', [1]) ###Markdown 这为我们提供了另一种访问网络参数的方式,如下所示。 ###Code net.state_dict()['2.bias'] ###Output _____no_output_____ ###Markdown 5.2.1.3. 从嵌套块收集参数让我们看看,如果我们将多个块相互嵌套,参数命名约定是如何工作的。为此,我们首先定义一个生成块的函数(可以说是块工厂),然后将这些块组合到更大的块中。 ###Code def block1(): return nn.Sequential(nn.Linear(4, 8), nn.ReLU(), nn.Linear(8, 4), nn.ReLU()) def block2(): net = nn.Sequential() for i in range(4): # 在这里嵌套 net.add_sublayer(f'block {i}', block1()) return net rgnet = nn.Sequential(block2(), nn.Linear(4, 1)) rgnet(X) ###Output _____no_output_____ ###Markdown 现在我们已经设计了网络,让我们看看它是如何组织的。 ###Code print(rgnet) ###Output Sequential( (0): Sequential( (block 0): Sequential( (0): Linear(in_features=4, out_features=8, dtype=float32) (1): ReLU() (2): Linear(in_features=8, out_features=4, dtype=float32) (3): ReLU() ) (block 1): Sequential( (0): Linear(in_features=4, out_features=8, dtype=float32) (1): ReLU() (2): Linear(in_features=8, out_features=4, dtype=float32) (3): ReLU() ) (block 2): Sequential( (0): Linear(in_features=4, out_features=8, dtype=float32) (1): ReLU() (2): Linear(in_features=8, out_features=4, dtype=float32) (3): ReLU() ) (block 3): Sequential( (0): Linear(in_features=4, out_features=8, dtype=float32) (1): ReLU() (2): Linear(in_features=8, out_features=4, dtype=float32) (3): ReLU() ) ) (1): Linear(in_features=4, out_features=1, dtype=float32) ) ###Markdown 因为层是分层嵌套的,所以我们也可以像通过嵌套列表索引一样访问它们。例如,我们下面访问第一个主要的块,其中第二个子块的第一层的偏置项。 ###Code print(rgnet[0].state_dict()['block 0.0.bias']) ###Output Parameter containing: Tensor(shape=[8], dtype=float32, place=CUDAPlace(0), stop_gradient=False, [0., 0., 0., 0., 0., 0., 0., 0.]) ###Markdown 5.2.2. 参数初始化我们知道了如何访问参数,现在让我们看看如何正确地初始化参数。我们在 4.8节 中讨论了良好初始化的必要性。深度学习框架提供默认随机初始化。然而,我们经常希望根据其他规则初始化权重。深度学习框架提供了最常用的规则,也允许创建自定义初始化方法。 默认情况下,Paddle会根据一个范围均匀地初始化权重和偏置矩阵,这个范围是根据输入和输出维度计算出的。Paddle的nn.init模块提供了多种预置初始化方法。 5.2.2.1. 内置初始化 让我们首先调用内置的初始化器。下面的代码将所有权重参数初始化为标准差为0.01的高斯随机变量,且将偏置参数设置为0。 ###Code def init_normal(m): if type(m) == nn.Linear: paddle.nn.initializer.Normal(mean=0.0, std=0.01) paddle.zeros(m.bias) net.apply(init_normal) net[0].weight[0],net[0].state_dict()['bias'] ###Output _____no_output_____ ###Markdown 我们还可以将所有参数初始化为给定的常数(比如1)。 ###Code def init_constant(m): if type(m) == nn.Linear: paddle.nn.initializer.Constant(value=1) paddle.zeros(m.bias) #nn.init.normal_(m.weight, mean=0, std=0.01) #nn.init.zeros_(m.bias) net.apply(init_normal) net[0].weight[0],net[0].state_dict()['bias'] ###Output _____no_output_____ ###Markdown 我们还可以对某些块应用不同的初始化方法。例如,下面我们使用Xavier初始化方法初始化第一层,然后第二层初始化为常量值42。 ###Code def xavier(m): if type(m) == nn.Linear: paddle.nn.initializer.XavierUniform(m.weight) def init_42(m): if type(m) == nn.Linear: paddle.nn.initializer.Constant(42) net[0].apply(xavier) net[2].apply(init_42) print(net[0].weight[0]) print(net[2].weight) ###Output Tensor(shape=[8], dtype=float32, place=CUDAPlace(0), stop_gradient=False, [ 0.12369687, 0.16349538, -0.63969749, 0.51602465, 0.48513484, -0.02029708, 0.29068446, -0.19858840]) Parameter containing: Tensor(shape=[8, 1], dtype=float32, place=CUDAPlace(0), stop_gradient=False, [[ 0.71925110], [-0.09674287], [ 0.48484957], [ 0.11552629], [-0.10340047], [ 0.81542194], [-0.43466821], [ 0.46107769]]) ###Markdown 5.2.2.2. 自定义初始化 有时,深度学习框架没有提供我们需要的初始化方法。在下面的例子中,我们使用以下的分布为任意权重参数 w 定义初始化方法:![](https://ai-studio-static-online.cdn.bcebos.com/400bc2321f1f4011bb117b26f543d793f9ac015511d64eda8717ceb09c2df4db)同样,我们实现了一个my_init函数来应用到net。 ###Code def my_init(m): if type(m) == nn.Linear: print( "Init", *[(name, param.shape) for name, param in m.named_parameters()][0]) paddle.nn.initializer.XavierUniform(m.weight, -10, 10) h=paddle.abs(m.weight)>=5 h=paddle.to_tensor(h) m=paddle.to_tensor(m.weight) m*=h net.apply(my_init) net[0].weight[:2] ###Output Init weight [4, 8] Init weight [8, 1] ###Markdown 注意,我们始终可以直接设置参数。 ###Code net[0].weight[:] += 1 net[0].weight[0, 0] = 42 net[0].weight[0] ###Output _____no_output_____ ###Markdown 5.2.3. 参数绑定有时我们希望在多个层间共享参数。让我们看看如何优雅地做这件事。在下面,我们定义一个稠密层,然后使用它的参数来设置另一个层的参数。 ###Code # 我们需要给共享层一个名称,以便可以引用它的参数。 shared = nn.Linear(8, 8) net = nn.Sequential(nn.Linear(4, 8), nn.ReLU(), shared, nn.ReLU(), shared, nn.ReLU(), nn.Linear(8, 1)) net(X) # 检查参数是否相同 print(net[2].weight[0] == net[4].weight[0]) net[2].weight[0, 0] = 100 # 确保它们实际上是同一个对象,而不只是有相同的值。 print(net[2].weight[0] == net[4].weight[0]) ###Output Tensor(shape=[8], dtype=bool, place=CUDAPlace(0), stop_gradient=False, [True, True, True, True, True, True, True, True]) Tensor(shape=[8], dtype=bool, place=CUDAPlace(0), stop_gradient=False, [True, True, True, True, True, True, True, True])
mushroom/Mushroom Edibility.ipynb
###Markdown Mushroom Edibility Dataset Contents* DataSet* Description* Evaluation* Data Set* Import Data* Explore the Data Import Data ###Code import pandas as pd import numpy as np import pylab as plt # Set the global default size of matplotlib figures plt.rc('figure', figsize=(10, 5)) # Size of matplotlib figures that contain subplots fizsize_with_subplots = (10, 10) # Size of matplotlib histogram bins bin_size = 10 mushroomDf = pd.read_csv('data/mushrooms.csv') ###Output _____no_output_____ ###Markdown Description Of Data ###Code mushroomDf.describe() ###Output _____no_output_____ ###Markdown Info Of Data ###Code mushroomDf.info() # Set up a grid of plots fig = plt.figure(figsize=fizsize_with_subplots) features = mushroomDf.drop(['class'], axis=1) fig_dims = (2, 1) for column in features: plt.subplot2grid(fig_dims, (0,0)) mushroomDf[column].value_counts().plot(kind='bar', title=column + ' Distribution') plt.show() ###Output _____no_output_____ ###Markdown As seen above graphs, we can eliminate feature veil-type which has only one unique value ###Code for column in features: print(pd.crosstab(mushroomDf['class'], mushroomDf[column])) print('\n===================================================\n') ###Output cap-shape b c f k s x class e 404 0 1596 228 32 1948 p 48 4 1556 600 0 1708 =================================================== cap-surface f g s y class e 1560 0 1144 1504 p 760 4 1412 1740 =================================================== cap-color b c e g n p r u w y class e 48 32 624 1032 1264 56 16 16 720 400 p 120 12 876 808 1020 88 0 0 320 672 =================================================== bruises f t class e 1456 2752 p 3292 624 =================================================== odor a c f l m n p s y class e 400 0 0 400 0 3408 0 0 0 p 0 192 2160 0 36 120 256 576 576 =================================================== gill-attachment a f class e 192 4016 p 18 3898 =================================================== gill-spacing c w class e 3008 1200 p 3804 112 =================================================== gill-size b n class e 3920 288 p 1692 2224 =================================================== gill-color b e g h k n o p r u w y class e 0 96 248 204 344 936 64 852 0 444 956 64 p 1728 0 504 528 64 112 0 640 24 48 246 22 =================================================== stalk-shape e t class e 1616 2592 p 1900 2016 =================================================== stalk-root ? b c e r class e 720 1920 512 864 192 p 1760 1856 44 256 0 =================================================== stalk-surface-above-ring f k s y class e 408 144 3640 16 p 144 2228 1536 8 =================================================== stalk-surface-below-ring f k s y class e 456 144 3400 208 p 144 2160 1536 76 =================================================== stalk-color-above-ring b c e g n o p w y class e 0 0 96 576 16 192 576 2752 0 p 432 36 0 0 432 0 1296 1712 8 =================================================== stalk-color-below-ring b c e g n o p w y class e 0 0 96 576 64 192 576 2704 0 p 432 36 0 0 448 0 1296 1680 24 =================================================== veil-type p class e 4208 p 3916 =================================================== veil-color n o w y class e 96 96 4016 0 p 0 0 3908 8 =================================================== ring-number n o t class e 0 3680 528 p 36 3808 72 =================================================== ring-type e f l n p class e 1008 48 0 0 3152 p 1768 0 1296 36 816 =================================================== spore-print-color b h k n o r u w y class e 48 48 1648 1744 48 0 48 576 48 p 0 1584 224 224 0 72 0 1812 0 =================================================== population a c n s v y class e 384 288 400 880 1192 1064 p 0 52 0 368 2848 648 =================================================== habitat d g l m p u w class e 1880 1408 240 256 136 96 192 p 1268 740 592 36 1008 272 0 =================================================== ###Markdown Edibles ###Code from sklearn import preprocessing labelEncoder = preprocessing.LabelEncoder() transformMatrix = mushroomDf.apply(labelEncoder.fit_transform) edibles = transformMatrix.loc[transformMatrix['class'] == 0] poisonous = transformMatrix.loc[transformMatrix['class'] == 1] fig_size = plt.rcParams["figure.figsize"] # New figure size fig_size[0] = 20 fig_size[1] = 20 plt.rcParams["figure.figsize"] = fig_size edibles.hist() plt.show() ###Output _____no_output_____ ###Markdown Poisonous ###Code poisonous.hist(color = "red") plt.show() # comparing quantities of edible and poisionous mushrooms on basis of cap color def autolabel(rects,fontsize=14): #Attach a text label above each bar displaying its height for rect in rects: height = rect.get_height() ax.text(rect.get_x() + rect.get_width()/2., 1*height,'%d' % int(height), ha='center', va='bottom',fontsize=fontsize) feature = 'cap-color' features = mushroomDf[feature].value_counts() m_height = features.values.tolist() features.axes feature_labels = features.axes[0].tolist() poisonous_cc = [] edible_cc = [] for featureValue in feature_labels: size = len(mushroomDf[mushroomDf[feature] == featureValue].index) edibles = len(mushroomDf[(mushroomDf[feature] == featureValue) & (mushroomDf['class'] == 'e')].index) edible_cc.append(edibles) poisonous_cc.append(size-edibles) #PLOT Preparations and Plotting ind = np.arange(10) width = 0.40 fig, ax = plt.subplots(figsize=(12,7)) edible_bars = ax.bar(ind, edible_cc , width, color='#ADFF2F') poison_bars = ax.bar(ind+width, poisonous_cc, width, color='#DA70D6') #Add some text for labels, title and axes ticks ax.set_xlabel(feature, fontsize=20) ax.set_ylabel('quantity', fontsize=20) ax.set_title('Edible and Poisonous Mushrooms Based on ' + feature, fontsize=22) ax.set_xticks(ind + width / 2) ax.set_xticklabels(('brown', 'gray','red','yellow','white','buff','pink','cinnamon','purple','green'), fontsize = 12) ax.legend((edible_bars, poison_bars),('edible','poisonous'),fontsize=17) autolabel(edible_bars, 10) autolabel(poison_bars, 10) plt.show() #Obtain total number of mushrooms for each 'odor' feature = 'odor' odors = mushroomDf[feature].value_counts() odor_height = odors.values.tolist() odor_labels = odors.axes[0].tolist() #comparing quantities of edible and poisionous mushrooms on basis of odor poisonous_od = [] edible_od = [] for odor in odor_labels: size = len(mushroomDf[mushroomDf['odor'] == odor].index) edibles = len(mushroomDf[(mushroomDf['odor'] == odor) & (mushroomDf['class'] == 'e')].index) edible_od.append(edibles) poisonous_od.append(size-edibles) #PLOT Preparations and Plotting ind = np.arange(9) width = 0.40 fig, ax = plt.subplots(figsize=(12,7)) edible_bars = ax.bar(ind, edible_od , width, color='#ADFF2F') poison_bars = ax.bar(ind+width, poisonous_od , width, color='#DA70D6') #Add some text for labels, title and axes ticks ax.set_xlabel("Odor",fontsize=20) ax.set_ylabel('Quantity',fontsize=20) ax.set_title('Edible and Poisonous Mushrooms Based on Odor',fontsize=22) ax.set_xticks(ind + width / 2) ax.set_xticklabels(('none', 'foul','fishy','spicy','almond','anise','pungent','creosote','musty'), fontsize = 12) ax.legend((edible_bars,poison_bars),('edible','poisonous'),fontsize=17) autolabel(edible_bars, 10) autolabel(poison_bars, 10) plt.show() print(edible_od) print(poisonous_od) ###Output _____no_output_____ ###Markdown Naive Bayes Classifier ###Code from sklearn.naive_bayes import MultinomialNB from sklearn.metrics import accuracy_score naiveBayes = MultinomialNB() mushroomMx = mushroomDf.sample(frac=1).reset_index(drop=True) labelEncoder = preprocessing.LabelEncoder() transformMatrix = mushroomMx.apply(labelEncoder.fit_transform) dataLength = len(transformMatrix) testDataLength = int(len(transformMatrix)*0.1) trainData = transformMatrix[testDataLength:] testData = transformMatrix[:testDataLength] feautres = trainData.drop(['class'], axis=1) edibility = trainData['class'] trainY = naiveBayes.fit(trainData.drop(['class'], axis=1), trainData['class']) testDataX = transformMatrix.drop(['class'], axis=1).as_matrix() testDataY = transformMatrix['class'].as_matrix() predicted = trainY.predict(testDataX) accuracy = accuracy_score(testDataY, predicted) print('Accuracy: %',accuracy) print('Error Rate: %', 1 - accuracy) import pandas as pd import numpy as np from sklearn.ensemble import RandomForestClassifier def clean_column(df, column): column_value = column + '_value'; values = sorted(df[column].unique()) value_mapping = dict(zip(values, range(0, len(values) + 1))) df[column_value] = df[column].map(value_mapping).astype(int) df = df.drop([column], axis=1) return df def clean_data(df, columns): for column in columns: df = clean_column(df, column) return df def clean_df(df): columns = [ 'class', 'cap-shape', 'cap-surface', 'cap-color', 'bruises', 'odor', 'gill-attachment', 'gill-spacing', 'gill-size', 'gill-color', 'stalk-shape', 'stalk-root', 'stalk-surface-above-ring', 'stalk-surface-below-ring', 'stalk-color-above-ring', 'stalk-color-below-ring', 'veil-type', 'veil-color', 'ring-number', 'ring-type', 'spore-print-color', 'population', 'habitat' ] return clean_data(df, columns) df = pd.read_csv('./data/mushrooms.csv') df = clean_df(df) df = df.sample(frac=1).reset_index(drop=True) data_length = len(df) test_data_length = int(data_length*0.1) train_data = transformMatrix[test_data_length:] test_data = transformMatrix[:test_data_length] train_data = train_data.values test_data = test_data.values clf = RandomForestClassifier(n_estimators=100) train_features = train_data[:, 1:] train_target = train_data[:, 0] test_features = test_data[:, 1:] test_target = test_data[:, 0] # Fit the model to our training data clf = clf.fit(train_features, train_target) score = clf.score(test_features, test_target) print( "Mean accuracy of Random Forest: {0}".format(score) ) ###Output Mean accuracy of Random Forest: 1.0
notebooks/.ipynb_checkpoints/06-fs-fit-final-model-checkpoint.ipynb
###Markdown Final Model ###Code import sys import inspect #Add the scripts directory to the sys path sys.path.append("../src/data") sys.path.append("../src/features") from make_dataset import get_data from data_processor import DataProcessor import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import shap from sklearn.model_selection import train_test_split, GridSearchCV from sklearn.pipeline import Pipeline from sklearn.linear_model import LinearRegression from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor import xgboost as xgb from sklearn.metrics import mean_absolute_error import joblib # Show all rows and columns in the display pd.set_option("display.max_columns", None) pd.set_option("display.max_rows", None) import warnings warnings.filterwarnings('ignore') ###Output _____no_output_____ ###Markdown Create Model object ###Code dp = DataProcessor(cols_to_remove=["parcelid", "propertyzoningdesc", "rawcensustractandblock", "regionidneighborhood", "regionidzip", "censustractandblock"], datecol="transactiondate") xgb_reg = xgb.sklearn.XGBRegressor(learning_rate=0.01, n_estimators=1039, max_depth=3, min_child_weight=1, gamma=0.4, max_delta_step=0, subsample=1.0, colsample_bytree=0.9, colsample_bylevel=1, colsample_bynode=1, reg_lambda=1, reg_alpha=1, scale_pos_weight=1, missing=None, objective='reg:squarederror', eval_metric='mae', seed=0, booster='gbtree', verbosity=0, nthread=-1) final_model = Pipeline([ ("dataprocessor", dp), ("xgb_reg", xgb_reg) ]) ###Output _____no_output_____ ###Markdown Fit Final Model ###Code #get the train data X_train, y_train = get_data(data_string="train") final_model.fit(X_train, y_train) ###Output _____no_output_____ ###Markdown Score Test Dataset ###Code #get the test data X_test, y_test = get_data(data_string="test") y_pred = final_model.predict(X_test) ###Output _____no_output_____ ###Markdown Evaluate Model and Compare with Baseline ###Code print("XGBoost model - {0:.5f}".format(mean_absolute_error(y_test, y_pred))) y_pred_baseline = pd.Series(np.zeros(len(y_test))) y_pred_baseline[:] = y_train.median() print("XGBoost model - {0:.4f}".format(mean_absolute_error(y_test, y_pred_baseline))) ###Output XGBoost model - 0.0697 ###Markdown As explained in previous notebook, we can try some more feature engineering, dimensionality reduction or/and try other models such as Gradient Boosting, AdaBoost to see if we can reduce MAE further Plot the Model Results Actuals vs Predictions ###Code plt.figure(figsize=(10,10)) plt.scatter(y_test, y_pred) plt.xlabel("Actuals") plt.ylabel("Predictions") plt.xlim(-5,5) plt.ylim(-5,5) plt.show() ###Output _____no_output_____ ###Markdown Actuals vary from -4 to 4 whereas our predictions vary from -1 to 1. Our predictive model lacks in this aspect. ###Code plt.figure(figsize=(16,10)) plt.hist([y_test, y_pred], label=["Actual", "Predicted"], bins=100) plt.yscale("log") plt.legend(loc="upper left") plt.show() ###Output _____no_output_____ ###Markdown Predicted values has less variance compared to the actuals Feature Importances ###Code plt.figure(figsize=(20,15)) xgb.plot_importance(xgb_reg, xlabel=None, ax=plt.gca()) ###Output _____no_output_____ ###Markdown Model Explainability using SHAP ###Code X_test_transformed = dp.transform(X_test) explainer = shap.TreeExplainer(xgb_reg) shap_values = explainer.shap_values(X_test_transformed) shap.summary_plot(shap_values, X_test_transformed, plot_type="bar") ###Output _____no_output_____ ###Markdown The features that are having greater impact on the predictions are1. taxamount - The total property tax assessed for that assessment year2. finishedsquarefeet12 - Finished living area3. taxvaluedollarcnt - The total tax assessed value of the parcel4. poolcnt - Number of pools on the lot (if any)5. calculatedfinishedsquarefeet - Calculated total finished living area of the home 6. lotsizesquarefeet - Area of the lot in square feet7. transactiondate_month - month when the sale happened8. taxdelinquencyflag_Y - Property taxes for this parcel are past due as of 20159. buildingqualitytypeid - Overall assessment of condition of the building from best (lowest) to worst (highest)10. latitude11. longitude` Since we are predicting **logerror = log(Zestimate) - log(SalePrice)**, we are predicting where Zillow model (predictng Zestimate) is lacking and what features are contributing to it. The above 10 features can probably help improve Zillow model with its prediction ###Code shap.summary_plot(shap_values, X_test_transformed) ###Output _____no_output_____ ###Markdown 1. **taxamount** - low values of tax amount indicates positive values of logerror. This implies that the Zestimate is higher than SalePrice2. **finishedsquarefeet12** - higher Finished Living area square feet indicates higher logerror which implies higher Zestimate3. **structuretaxvaluedollarcnt** - The assessed value of the built structure on the parcel - higher values indicate higher Zestimate.We can use the shap values to explain where the logerror is positive or negative and inturn helps us understand where Zillow model is overestimating or understimating. Save Model ###Code joblib.dump(final_model, "../models/final_model.pkl") ###Output _____no_output_____
Notebooks/Burgers' Equation PINN.ipynb
###Markdown **Two functions**1. $f(x,t)$ -> function to calculate the residual of the NN output2. $u(x,t)$ -> NN* $n_u$ is intial and boundary points * sample -> (t, x) * if sample[0] in (0, 1) or sample[1] in (-1,1): add to BC_IC_pts * else: add to collocation points * $n_f$ is collocation points* $n_u$ = 100 and $n_f$ = 10,000* With 8 Hidden layers with each 40 neurons, gives an $L_2$ error of $5.6e−04$ ###Code DATA_PATH = "../Data/burgers_shock.mat" data_dict = scipy.io.loadmat(DATA_PATH) n_u, n_f = 100, 10000 x_data,t_data, u_data = data_dict['x'], data_dict['t'], data_dict['usol'] x_data.shape, t_data.shape, u_data.shape u_t, u_x = meshgrid(t_data, x_data) u_t.shape, u_x.shape u_data_transformed = u_data.flatten()[:, None] # (25600,1) training_points = np.hstack((u_t.flatten()[:, None], u_x.flatten()[:, None])) # (25600, 2) IC_X, IC_Y = list(), list() # Initial and boundary points CC_X, CC_Y = list(), list() # Collocation points for idx, sample in enumerate(training_points): t, x = sample if t in [0,1] or x in [-1,1]: IC_X.append(sample) IC_Y.append(u_data_transformed[idx]) else: CC_X.append(sample) CC_Y.append(u_data_transformed[idx]) IC_X = np.array(IC_X) IC_Y = np.array(IC_Y) CC_X = np.array(CC_X) CC_Y = np.array(CC_Y) n_u_idx = list(np.random.choice(len(IC_X), n_u)) n_f_idx = list(np.random.choice(len(CC_X), n_f)) u_x = torch.tensor(IC_X[n_u_idx, 1:2], requires_grad=True).float() u_t = torch.tensor(IC_X[n_u_idx, 0:1], requires_grad=True).float() u_u = torch.tensor(IC_Y[n_u_idx, :], requires_grad=True).float() f_x = torch.tensor(CC_X[n_f_idx, 1:2], requires_grad=True).float() f_t = torch.tensor(CC_X[n_f_idx, 0:1], requires_grad=True).float() f_u = torch.tensor(CC_Y[n_f_idx, :], requires_grad=True).float() train_x = torch.cat((u_x, f_x), dim=0) train_t = torch.cat((u_t, f_t), dim=0) train_u = torch.cat((u_u, f_u), dim=0) class PhysicsINN(nn.Module): ''' Physics Informed Neural Network Written: Siddesh Sambasivam Suseela ''' def __init__(self, num_layers:int=2, num_neurons:int=20) -> None: super(PhysicsINN, self).__init__() self.num_layers = num_layers self.num_neurons = num_neurons # Each hidden layer contained 20 neurons and a hyperbolic tangent activation function. self.activation_func = torch.nn.Tanh ordered_layers = list() ordered_layers.append(("input_layer", nn.Linear(2, self.num_neurons))) ordered_layers.append(("input_activation", self.activation_func())) # Create num_layers-2 linear layers with num_neuron neurons and tanh activation function for i in range(self.num_layers-2): ordered_layers.append(("layer_%d" % (i+1), nn.Linear(self.num_neurons, self.num_neurons))) ordered_layers.append(("layer_%d_activation" % (i+1), self.activation_func())) ordered_layers.append(("output_layer", nn.Linear(self.num_neurons, 1))) self.net = nn.Sequential(OrderedDict(ordered_layers)) self.init_weights() def init_weights(self, ) -> None: """ Initializes the weights and biases of all the layers in the model NOTE: According to the paper, the model's weights are initialized by xaviers' distribution and biases are initialized as zeros """ for param in self.parameters(): if len(param.shape) >= 2: torch.nn.init.xavier_normal_(param, ) elif len(param.shape) == 1: torch.nn.init.zeros_(param) def forward(self, inputs) -> torch.Tensor: '''returns the output from the model''' out = self.net(inputs) return out model = PhysicsINN(4, 40) # Flexible HP # 1. Hidden layers # 2. Num_neurons # 3. Activation functions # Check the layer sizes for param in model.parameters(): print(type(param), param.size()) EPOCHS = 100 optimizer = torch.optim.LBFGS(model.parameters()) t_bar = trange(EPOCHS) for epoch in t_bar: def closure(): optimizer.zero_grad() output = model(torch.cat((train_t, train_x), dim=1)) u_grad_x = torch.autograd.grad(output, train_x, retain_graph=True, create_graph=True, grad_outputs=torch.ones_like(output),allow_unused=True)[0] u_grad_xx = torch.autograd.grad(u_grad_x, train_x, retain_graph=True, create_graph=True, grad_outputs=torch.ones_like(output),allow_unused=True)[0] u_grad_t = torch.autograd.grad(output, train_t, retain_graph=True, create_graph=True, grad_outputs=torch.ones_like(output),allow_unused=True)[0] f = u_grad_t + output*u_grad_x - (0.01/np.pi) * u_grad_xx mse_f = torch.mean(torch.square(f)) mse_u = torch.mean(torch.square(output - train_u)) loss = mse_f + mse_u loss.backward() t_bar.set_description("loss: %.20f" % loss.item()) t_bar.refresh() # to show immediately the update return loss optimizer.step(closure) ###Output loss: 0.00021063242456875741: 100%|██████████| 100/100 [01:53<00:00, 1.13s/it] ###Markdown Neural Network has 2 Hidden layers with 40 neurons1. For 100 Epochs: $0.9e-1$2. For 200 Epochs: $0.6e-3$0.029139706864953041080.02671100944280624390 ###Code test_X = [[], [], []] test_Y = [[], [], []] for idx, sample in enumerate(training_points): t, x = sample if t == 0.25: test_X[0].append(sample) test_Y[0].append(u_data_transformed[idx]) if t == 0.50: test_X[1].append(sample) test_Y[1].append(u_data_transformed[idx]) if t == 0.75: test_X[2].append(sample) test_Y[2].append(u_data_transformed[idx]) test_X[0][0], test_Y[0][1] fig, ax = plt.subplots(figsize=(8,5)) ax.plot(test_Y[0], linewidth=5) ax.plot(model(torch.tensor(test_X[0]).float()).detach().numpy(), "r--", linewidth=5) fig, axs = plt.subplots(1,3, sharey=True, figsize=(20,5)) width = 6 for i,t in enumerate([0.25, 0.50, 0.75]): axs[i].set_title(f"$U(t,x)$ at t={t}") axs[i].plot(test_Y[i], linewidth=width, label="ground truth") axs[i].plot(model(torch.tensor(test_X[i]).float()).detach().numpy(), "r--", linewidth=width, label='prediction') axs[i].legend(loc='upper right') # axs[i].set_xlim(-1,1) # axs[i].set_ylim(-1,1) fig.savefig('model_prediction.png') np.stack((model(torch.tensor(test_X[i]).float()).detach().numpy().flatten(), np.array([list(x) for x in test_X[0]])[:, 1]), axis=-1) model(torch.tensor(test_X[i]).float()).detach().numpy()[1] ###Output _____no_output_____
code/data_cleaning/clean_prices.ipynb
###Markdown Identify files ###Code # Get list of TAQ files taq_price_folder = '../../data/taq/prices/' taq_price_files = glob.glob(taq_price_folder + '*.parquet') taq_price_files_dates = [x.split('/')[-1].split('_')[0].split('.')[0] for x in taq_price_files] taq_price_files_dates = list(set(taq_price_files_dates)) # Get list of CRSP files crsp_price_folder = '../../../HFZoo/data/crsp/daily/' crsp_price_files = glob.glob(crsp_price_folder + '*.parquet') crsp_price_files_dates = [x.split('/')[-1].split('.')[0] for x in crsp_price_files] ###Output _____no_output_____ ###Markdown Misc Data ###Code ## Delisting returns conn = wrds.Connection(**{"wrds_username": "sa400"}) crspmsedelist_df = conn.raw_sql(""" select DLSTDT, PERMNO, dlret from crsp.msedelist """) crspmsedelist_df['date'] = pd.to_datetime(crspmsedelist_df['dlstdt']) ###Output Loading library list... Done ###Markdown Functions Clean ###Code all_times = ['9:30:00', '9:35:00', '9:40:00', '9:45:00', '9:50:00', '9:55:00', '10:00:00', '10:05:00', '10:10:00', '10:15:00', '10:20:00', '10:25:00', '10:30:00', '10:35:00', '10:40:00', '10:45:00', '10:50:00', '10:55:00', '11:00:00', '11:05:00', '11:10:00', '11:15:00', '11:20:00', '11:25:00', '11:30:00', '11:35:00', '11:40:00', '11:45:00', '11:50:00', '11:55:00', '12:00:00', '12:05:00', '12:10:00', '12:15:00', '12:20:00', '12:25:00', '12:30:00', '12:35:00', '12:40:00', '12:45:00', '12:50:00', '12:55:00', '13:00:00', '13:05:00', '13:10:00', '13:15:00', '13:20:00', '13:25:00', '13:30:00', '13:35:00', '13:40:00', '13:45:00', '13:50:00', '13:55:00', '14:00:00', '14:05:00', '14:10:00', '14:15:00', '14:20:00', '14:25:00', '14:30:00', '14:35:00', '14:40:00', '14:45:00', '14:50:00', '14:55:00', '15:00:00', '15:05:00', '15:10:00', '15:15:00', '15:20:00', '15:25:00', '15:30:00', '15:35:00', '15:40:00', '15:45:00', '15:50:00', '15:55:00', '16:00:00'] def clean_taq(date): # Get TAQ files taq_price_files_date = glob.glob(taq_price_folder + date + '*.parquet') taq_df = pd.concat([pd.read_parquet(x) for x in taq_price_files_date]) # Clean up TAQ df columns taq_df.columns = [x.lower() for x in taq_df.columns] # Handle any missing times index = pd.MultiIndex.from_product( [taq_df["permno"].unique(), all_times], names=["permno", "time"] ) index_df = pd.DataFrame(index=index).reset_index() taq_df = ( taq_df.merge(index_df, on=["permno", "time"], how="right") .sort_values(by=["permno"]) .astype({'time': 'category'}) ) taq_df = taq_df.sort_values(by = ['permno', 'time']) # Forward fill in entries taq_df[['price', 'cusip9', 'symbol', 'ticker_identifier']] = taq_df.groupby(['permno'])[ ['price', 'cusip9', 'symbol', 'ticker_identifier']].ffill() taq_df['date'] = int(date) # Add date taq_df['datetime'] = pd.to_datetime(taq_df['date'], format = '%Y%m%d') + pd.to_timedelta(taq_df['time']) taq_df['time'] = taq_df['time'].astype(str) # Add returns taq_df = taq_df.sort_values(by = ['permno', 'datetime']).reset_index(drop = True) taq_df['return'] = taq_df.groupby(['permno'])['price'].pct_change() return taq_df def clean_crsp(date): # Get CRSP file crsp_df = pd.read_parquet(crsp_price_folder + date + ".parquet") # Fix columns crsp_df.columns = [x.lower() for x in crsp_df] crsp_df[['ret', 'retx']] = crsp_df[['ret', 'retx']].apply(pd.to_numeric, errors = 'coerce') crsp_df['date'] = pd.to_datetime(crsp_df['date'], format = '%Y%m%d') # Infer close-to-open adjusted overnight returns crsp_df['prc'] = np.abs(crsp_df['prc']) crsp_df['openprc'] = np.abs(crsp_df['openprc']) crsp_df['ret_open_close_intraday'] = (crsp_df['prc']-crsp_df['openprc'])/crsp_df['openprc'] crsp_df['ret_close_open_adj'] = (1+crsp_df['ret'])/(1+crsp_df['ret_open_close_intraday']) - 1 crsp_df['retx_close_open_adj'] = (1+crsp_df['retx'])/(1+crsp_df['ret_open_close_intraday']) - 1 # Create dataframes for start and end of the day crsp_df_start = crsp_df.copy() crsp_df_end = crsp_df.copy() crsp_df_start['time'] = '09:30:00' crsp_df_end['time'] = '16:00:00' # Add prices and returns crsp_df_start['price'] = crsp_df_start['openprc'] crsp_df_start['return'] = crsp_df_start['ret_close_open_adj'] crsp_df_start['returnx'] = crsp_df_start['retx_close_open_adj'] crsp_df_end['price'] = crsp_df_end['prc'] crsp_df_end['return'] = crsp_df_end['ret_open_close_intraday'] # Delisting return to end of day CRSP crsp_df_end = crsp_df_end.merge(crspmsedelist_df, on = ['date', 'permno'], how = 'left') # Add dates crsphf_df = pd.concat([crsp_df_start, crsp_df_end], ignore_index = True) crsphf_df['datetime'] = crsphf_df['date'] + pd.to_timedelta(crsphf_df['time']) return crsphf_df def merge_crsp_taq(taq_df, crsphf_df): # Combine CRSP with TAQ merge_df = taq_df.astype({'permno': 'str'}).merge( crsphf_df.astype({'permno': 'str'}), on=["permno", "datetime"], how="outer").sort_values( by=["permno", "datetime"] ) # Combined prices and returns - prefer CRSP prices (first/last) merge_df["price"] = merge_df["price_y"].fillna(merge_df["price_x"]) # Drop permnos where CRSP and TAQ price differ to much (mismatch) mismatches = merge_df.query('abs(log(price_y/price_x)) > 0.5 & time_y == "09:30:00"') if len(mismatches): permno_drops = mismatches['permno'].values merge_df = merge_df.query('permno not in @permno_drops').copy() print(f'Dropping ({", ".join(mismatches["symbol"].unique())}) \ due to match errors (date = {merge_df["datetime"].iloc[0].date()})') # First return should use CRSP to include dividends merge_df['return'] = merge_df.groupby(['permno'])['price'].pct_change() merge_df["return"] = np.where( merge_df["time_y"] == "09:30:00", merge_df["return_y"], merge_df["return"] ) # Last return will be CRSP if we are missing TAQ data merge_df['return'] = np.where( (merge_df['time_y'] == "16:00:00") & (merge_df['return_x'].isna()), merge_df['return_y'], merge_df['return'] ) # Adjust last return to handle delisting merge_df['return'] = np.where( (merge_df['time_y'] == "16:00:00"), (1+merge_df['return'])*(1+merge_df['dlret'].fillna(0))-1, merge_df['return'] ) # Dividend unadjusted returns - just have retx for first observation merge_df['returnx'] = np.where( merge_df["time_y"] == "09:30:00", merge_df["returnx"], merge_df["return"] ) # Fill in missing data merge_df[["permco", "shrout"]] = merge_df.groupby(["permno"])[["permco", "shrout"]].ffill() merge_df["date"] = pd.to_datetime(merge_df["datetime"].iloc[0].date()) merge_df['time'] = merge_df['datetime'].dt.time.astype(str) # Fix dtypes merge_df["permno"] = pd.Categorical(merge_df["permno"]) merge_df["permco"] = pd.Categorical(merge_df["permco"]) # Add market equity info merge_df["meq"] = ( merge_df["shrout"] * merge_df["price"] ) # / merge_df['cfacpr'] * merge_df['cfacshr'] merge_df["ME"] = merge_df.groupby(["datetime", "permco"])["meq"].transform("sum") merge_df["meq_day_max_permno"] = merge_df.groupby(["permno"])["meq"].transform("max") merge_df["meq_day_max_permco"] = merge_df.groupby(["permco"])["meq"].transform("max") merge_df = ( merge_df.query("meq_day_max_permno == meq_day_max_permco") .drop(["meq_day_max_permno", "meq_day_max_permco"], axis=1) .copy() ) # Subset merge_df = merge_df[['datetime', 'date', 'time', 'permco', 'permno', 'symbol', 'price', 'shrout', 'return', 'returnx', 'ME']].reset_index(drop = True) return merge_df def resample_merged(merge_df): ## Resample so every permno has 79 observations # Ensure there are 79 unique times in the data if merge_df["datetime"].nunique() < 79: raise Exception("Missing datetimes") # Construct multiindex and merge to get dataframe with all permnos * 79 times index = pd.MultiIndex.from_product( [merge_df["permno"].unique(), merge_df["datetime"].unique()], names=["permno", "datetime"] ) index_df = pd.DataFrame(index=index).reset_index() resample_df = ( merge_df.merge(index_df, on=["permno", "datetime"], how="right") .sort_values(by=["permno", "datetime"]) .drop(["time"], axis=1) ) # Fix missing data resample_df["date"] = merge_df["date"].iloc[0] ffill_cols = ["permco", "symbol", "shrout", 'ME'] resample_df[ffill_cols] = resample_df.groupby(['permno'])[ffill_cols].ffill() # Interpolate log prices and fill in missing prices/returns resample_df['log_price'] = np.log(resample_df['price']) resample_df['log_price_last'] = resample_df.groupby(['permno'])['log_price'].transform('last') resample_df['log_price_first'] = resample_df.groupby(['permno'])['log_price'].transform('first') resample_df['interp_beta'] = (resample_df['log_price_last'] - resample_df['log_price_first'])/78 resample_df['count'] = resample_df.groupby(['permno'])['datetime'].cumcount() resample_df['log_price_interp'] = resample_df['log_price_first'] + resample_df['count']*resample_df['interp_beta'] resample_df['price'] = resample_df['price'].fillna(np.exp(resample_df['log_price_interp'])) resample_df['return'] = np.where(resample_df['datetime'].dt.time.astype(str) == '09:30:00', resample_df['return'], resample_df.groupby(['permno'])['price'].pct_change()) resample_df['returnx'] = np.where(resample_df['datetime'].dt.time.astype(str) == '09:30:00', resample_df['returnx'], resample_df.groupby(['permno'])['price'].pct_change()) resample_df = resample_df.drop(['log_price', 'log_price_last', 'log_price_first', 'interp_beta', 'count', 'log_price_interp'], axis = 1) return resample_df ###Output _____no_output_____ ###Markdown Main ###Code output_folder = '../../data/proc/clean_prices/' for x in tqdm(glob.glob(output_folder + '*')): os.remove(x) %%time def clean_data(date): # Clean data try: taq_df = clean_taq(date) crsphf_df = clean_crsp(date) merge_df = merge_crsp_taq(taq_df, crsphf_df) # Filter to just taq permnos taq_permnos = taq_df['permno'].astype(str).unique() merge_df = merge_df.query('permno in @taq_permnos') final_df = resample_merged(merge_df) except: print(date) raise Exception() return final_df def process_date(date): # Get clean data final_df = clean_data(date) # Save mc = [] table = pa.Table.from_pandas(final_df) filename = date + '.parquet' pq.write_table(table, output_folder + filename, metadata_collector=mc) mc[-1].set_file_path(filename) return mc # Pyarrow metadata_collector = [] def cb(value): filename_str = value[0].strftime('%Y%m%d') return filename_str with Pool(24) as p: for mc in tqdm(p.imap_unordered(process_date, np.sort(taq_price_files_dates)), total = len(taq_price_files_dates), smoothing = 0.1): # Add to metadata metadata_collector.append(mc[0]) continue # Write the ``_metadata`` parquet file with row groups statistics of all files table_schema = pa.Table.from_pandas(clean_data(taq_price_files_dates[0])).schema pq.write_metadata( table_schema, output_folder + '_metadata', metadata_collector=metadata_collector ) ###Output 25%|██▌ | 1347/5284 [02:31<07:59, 8.21it/s] ###Markdown Check Results ###Code %%time # Folder with clean prices for all stocks data_folder = '../../data/proc/clean_prices/' # Read all files in data folder filter_ds = pq.ParquetDataset( glob.glob(data_folder + '*.parquet'), metadata = pq.read_metadata(data_folder + '_metadata') ) rawdata_df = filter_ds.read_pandas().to_pandas() date = '20000929' taq_df = clean_taq(date) crsphf_df = clean_crsp(date) temp_df = merge_crsp_taq(taq_df, crsphf_df) # Check for giant returns rawdata_df['abslret'] = abs(np.log(1+rawdata_df['return'])) rawdata_df.sort_values(by = 'abslret', ascending = False).head(20) rawdata_df.query('permno == "84398"').plot('datetime', 'price') rawdata_df.query('permno == "14593"').plot('datetime', 'log_price') rawdata_df.groupby(['permno'])['symbol'].apply(lambda x: x.astype(str).unique()) ###Output _____no_output_____
Jupyter Notebook/Jupyter_Analysis.ipynb
###Markdown We can notice that Prague is the leader in total cases, however if we look on the relative cases per 100 000 people, the picture is quite different. ###Code ### Computing mean age of infected persons for each day #creating a list of dates period = pd.date_range("2020-03-01", "2021-12-24", freq='D').astype(str).tolist() #dict where will be stored values and for loop for computation f = {} for i in period: day = covid.data[covid.data["datum"] == i] f[i] = day["vek"].mean() import numpy as np def moving_average(x, n): """ Computes moving average """ return np.convolve(x, np.ones(n), 'valid') / n ### Plotting 7 days moving avarage of age from datetime import date, datetime #preparing x and y values x = list(f.keys()) x = [datetime.strptime(d,'%Y-%m-%d').date() for d in x]# unpack a list of pairs into two tuples y = list(f.values()) #setting plot stysle plt.style.use('seaborn') #plot plt.plot(x[6:], moving_average(y,7), color = "green", linestyle = "-") #naming x and y axis plt.xlabel('Datum') plt.ylabel('Age') # displaying the title plt.title("7 Day Moving Average of Age of Infected Persons") plt.show() ###Output _____no_output_____ ###Markdown Thanks to our infomrations in our dataset we could explore how number of infections differe between men and women. And also expore average age of infected persons in our oberved period. At the beginning of the pandemic the average age was well above 40 years and peaked around 50 years old. Iterestingly, we can notice some seasonality, the average year of infected persons tend to decrease during summer. These are the months when the total infections are relatively low. ###Code from statsmodels.graphics.tsaplots import plot_acf from statsmodels.tsa.ar_model import AutoReg from pandas.plotting import autocorrelation_plot from pandas.plotting import lag_plot df = covid.data["id"].groupby(covid.data["datum"]).count() #root mean squared error def rmse(true_val, pred_val): squared_error = 0 if len(true_val) == len(pred_val): for idx in range(len(true_val)): squared_error += (true_val[idx] - pred_val[idx])**2 mse = squared_error / len(true_val) rmse = mse**(1/2) return rmse fig, ax = plt.subplots(figsize=(16,8)) plot_acf(df, lags=50, ax=ax) plt.axhline(y=0.5, color="green") plt.xticks(np.arange(1, 51, 1)) plt.ylim([0,1]) # we know there is only a positive correlation plt.show() # 17 lags above 0.5 lag_plot(df) # obvious relationship # spliting dataframe to test and train df_train = df.iloc[:-10] df_test = df.iloc[-10:] # fitting model and predicting model = AutoReg(df_train.values, lags=17, old_names = False).fit() forecasts = model.forecast(10).tolist() test_values = df_test.tolist() rmse(test_values, forecasts) fig = plt.subplots(figsize=(12,8)) # predicted values - green plt.plot(forecasts, color="green") # true values - blue plt.plot(test_values,color="blue") plt.show() # from data we can explore there is some correlation, so we can apply autoregression model # the result is depictured above ###Output _____no_output_____
preprocessing_statistics.ipynb
###Markdown Metadata Access ###Code import numpy as np # import pyaudio import audio_metadata from os import listdir from os.path import isfile, join import matplotlib.pyplot as plt data_path = 'data/crblp/wav/' audiofiles = [join(data_path,f) for f in listdir(data_path) if isfile(join(data_path, f))] print(audiofiles[0]) print(len(audiofiles)) metadata = audio_metadata.load(audiofiles[0]) print(metadata, '\n') print(type(metadata.streaminfo.duration)) print(metadata.streaminfo.duration,'in seconds') listofdurations = [] countofbadwaves = 0 for wavfile in audiofiles: try: meta = audio_metadata.load(wavfile) listofdurations.append(meta.streaminfo.duration) except: countofbadwaves += 1 print(wavfile,'has bad header') print('Length of Wavfile Durations List:',len(listofdurations)) print('No. of Bad header Wavfiles:',countofbadwaves) ###Output _____no_output_____ ###Markdown Duration Stats ###Code listofdurations.sort() print('Audio Time Stats') print('----------------') print('Size of Array:',len(listofdurations)) print('Maximum:',round(max(listofdurations),2)) print('Minimum:',round(min(listofdurations),2)) print('Mean',round(sum(listofdurations)/len(listofdurations),2)) print('Median:',round(listofdurations[int(len(listofdurations)/2)],2)) print('LoQuart:',round(listofdurations[int(len(listofdurations)/2) - int(len(listofdurations)/4)],2)) print('UpQuart:',round(listofdurations[int(len(listofdurations)/2) + int(len(listofdurations)/4)],2)) plt.figure(figsize=(16,8)) from matplotlib import pyplot as plt # data = np.random.normal(0, 20, 1000) data = listofdurations # fixed bin size bins = np.arange(0, 20, 0.1) # fixed bin size plt.xlim([0, 20]) plt.hist(data, bins=bins, alpha=0.5) plt.title('Audio Playback Time Distribution') plt.xticks(np.arange(0, 20, 1.0)) plt.xlabel('Playback Time') plt.ylabel('File Count') plt.show() ###Output _____no_output_____ ###Markdown File Ranging ###Code validtimes = [] for f in audiofiles: try: t = audio_metadata.load(f).streaminfo.duration if t>=1 and t<=2: validtimes.append(f) except: print('Bad Header:',f) print(len(validtimes)) print(validtimes[0]) print(validtimes[len(validtimes)-1]) file = open('data_RangedAudiofileList_1to2.txt','w') for f in validtimes: file.write(f) file.write('\n') file.close() ###Output _____no_output_____ ###Markdown Character Frequency Distribution ###Code import csv import data_dekhabet as dkb lookup = dkb.tokenlookup leng = len(lookup) countlook = [0]*leng print(lookup) print(leng) print(countlook) csvf = 'dekhabet_dataLabelsRanged.csv' counter = [] with open(csvf, 'r') as csvFile: reader = csv.reader(csvFile) for row in reader: ctext = [] text = row[4] text = text.strip("'-!$[]") text = text.split(',') i=0 if 'Tokens' in text: pass else: for t in range(0,len(text)): i = int(text[t]) counter.append(lookup[i]) csvFile.close() import pandas from collections import Counter # a = ['a', 'a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'd', 'e', 'e', 'e', 'e', 'e'] letter_counts = Counter(counter) print(letter_counts) df = pandas.DataFrame.from_dict(letter_counts, orient='index') df.plot(kind='bar',figsize=(8,6)) ###Output _____no_output_____ ###Markdown Google OpenSLR Stats ###Code import pandas as pd slrtsv_path = 'data/asr_bengali/utt_spk_text.tsv' df = pd.read_csv(slrtsv_path, sep='\t') df ###Output _____no_output_____ ###Markdown Find unique characters ###Code listofuniques = [] engletters = 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890-…,!?“' for index, row in df.iterrows(): if index%10000==0: print(index,listofuniques) for c in row[2]: if c not in engletters and len(c) <= 1: if c not in listofuniques: listofuniques.append(c) listofuniques.sort() print(listofuniques, len(listofuniques)) for i in range(0,15): listofuniques.pop(0) print(listofuniques) listofuniques.pop(len(listofuniques)-1) print(listofuniques) ###Output ['ঁ', 'ং', 'ঃ', 'অ', 'আ', 'ই', 'ঈ', 'উ', 'ঊ', 'ঋ', 'এ', 'ঐ', 'ও', 'ঔ', 'ক', 'খ', 'গ', 'ঘ', 'ঙ', 'চ', 'ছ', 'জ', 'ঝ', 'ঞ', 'ট', 'ঠ', 'ড', 'ঢ', 'ণ', 'ত', 'থ', 'দ', 'ধ', 'ন', 'প', 'ফ', 'ব', 'ভ', 'ম', 'য', 'র', 'ল', 'শ', 'ষ', 'স', 'হ', '়', 'া', 'ি', 'ী', 'ু', 'ূ', 'ৃ', 'ে', 'ৈ', 'ো', 'ৌ', '্', 'ৎ', 'ৗ', 'ড়', 'ঢ়', 'য়', '০', '১', '২', '৩', '৪', '৫', '৬', '৭', '৮', '৯', 'ৰ'] ###Markdown Transcript Parsing ###Code import pandas as pd slrtsv_path = 'data/asr_bengali/utt_spk_text.tsv' df = pd.read_csv(slrtsv_path, sep='\t') df import pandas as pd df = pd.read_csv('data/openslr_bengali/openslr_transcript_ranged25-35.csv') import data_dekhabet as dk b = dk.banglaletters d = dk.banglalookup s = dk.banglashongkha i = 0; parsed_transcript = [] error_chars = [] for index, row in df.iterrows(): # print('{:02d}: {}'.format(index,row[2])) # for c in row[2]: # print('{} '.format(c),end='') # print('') sentence = '' vectotr = [] buffer = '' for c in row[2]: buffer += c # print(c, sentence, len(buffer)) if c == ' ': if buffer[len(buffer)-2]=='র' or buffer[len(buffer)-2]=='়': sentence = sentence[:-1] vector = vector[:-1] sentence += d[b.index(c)] vector.append(d.index(d[b.index(c)])) elif c == '়': sentence = sentence[:-2] sentence += 'yo' elif c in dk.banglanokaars or c in s: sentence += d[b.index(c)] elif c in dk.banglakaars: sentence = sentence[:-1] sentence += d[b.index(c)] elif c == ' ' and buffer[len(buffer)-2]=='র': sentence = sentence[:-1] sentence += d[b.index(c)] else: try: sentence += d[b.index(c)]+'o' except: if c not in error_chars: error_chars.append(c) parsed_transcript.append(sentence) i += 1 if i%5000==0: print('{} sentences parsed.'.format(i), '=> ',parsed_transcript[i-1]) # print(sentence,'\n') print('{} sentences parsed.'.format(len(parsed_transcript))) print('{} error characters faced:'.format(len(error_chars))) print(error_chars) df = df.assign(Dekhascript = parsed_transcript) df df.to_csv('data/asr_bengali/openslr_transcript.csv') ###Output _____no_output_____ ###Markdown Audio file and Time Range management ###Code import numpy as np # import pyaudio import audio_metadata as am import os from os.path import isfile, join import matplotlib.pyplot as plt import pandas as pd data_path = 'data/asr_bengali/data/' # audiofiles = [join(data_path,f) for f in os.listdir(data_path) if isfile(join(data_path, f))] # audiofiles listOfFiles = list() for (dirpath, dirnames, filenames) in os.walk(data_path): listOfFiles += [os.path.join(dirpath, file) for file in filenames if file.endswith('.flac')] print(len(listOfFiles)) print(listOfFiles[0:5]) print(am.load(listOfFiles[0]).streaminfo.duration) df = pd.read_csv('data/asr_bengali/openslr_transcript.csv') df ###Output _____no_output_____ ###Markdown ProgressBar Function ###Code import time, sys from IPython.display import clear_output def update_progress(progress, endprogress): bar_length = 40 if isinstance(progress, int): progress = float(progress) if not isinstance(progress, float): progress = 0 if progress < 0: progress = 0 if progress >= 1: progress = 1 block = int(round(bar_length * progress)) clear_output(wait = True) text = "Progress: [{0}] {1:.1f}%".format( "#" * block + "-" * (bar_length - block), progress*100) print(text, str(int(round(progress*endprogress)))+'/'+str(endprogress)) i = 0 durationlist = [] for index, row in df.iterrows(): fl = 'data/asr_bengali/data/{}/{}.flac'.format(row['Filename'][0:2], row['Filename']) durationlist.append(am.load(fl).streaminfo.duration) update_progress(index / len(df)) update_progress(1) len(durationlist) df = df.assign(DurationSec = durationlist) df df.to_csv('data/asr_bengali/openslr_transcript.csv', index=False) df = pd.read_csv('data/asr_bengali/openslr_transcript.csv') df = df.drop(['Unnamed: 0'], axis = 1) df df.to_csv('data/asr_bengali/openslr_transcript.csv', index=False) df = pd.read_csv('data/asr_bengali/openslr_transcript.csv') print(df['DurationSec'].describe()) listodur = df['DurationSec'].tolist() listodur.sort() plt.figure(figsize=(16,8)) from matplotlib import pyplot as plt data = listodur max_x = 10 bins = np.arange(0, max_x, 0.1) # fixed bin size plt.xlim([0, max_x]) plt.hist(data, bins=bins, alpha=0.5) plt.title('Audio Playback Time Distribution') plt.xticks(np.arange(0, max_x, 1.0)) plt.xlabel('Playback Time') plt.ylabel('File Count') plt.show() listodurt = [] for i in listodur: if i>=2.5 and i<=3.5: listodurt.append(i) print(len(listodurt)) print('this is {:.1f}% the original dataset'.format(len(listodurt)/len(listodur)*100)) ###Output 61133 this is 47.9% the original dataset ###Markdown OpenSLR Spectrogram Processing ###Code import pandas as pd import data_wav2specto as w2s import progressbar as progbar df = pd.read_csv('data/asr_bengali/openslr_transcript.csv') df.head() ### MEMORY ERROR IF USED IN JUPYTER ### # durationrange = [2.5, 3.5] # data_dir = 'data/asr_bengali/data/' # count = 0 # l = len(df) # for i, row in df.iterrows(): # progbar.update_progress(i/l, l) # wavfile = data_dir + '{}/{}.flac'.format(row['Filename'][0:2], row['Filename']) # if row['DurationSec']>=durationrange[0] and row['DurationSec']>=durationrange[1]: # # w2s.graph_spectrogram(wavfile) # w2s.graph_melcepstrum(wavfile) # count += 1 # progbar.update_progress(1,l) # print(count, 'mel spectrograms calculated') import pandas as pd df = pd.read_csv('data/asr_bengali/openslr_transcript.csv') df dfr = df[(df['DurationSec']>=2.5) & (df['DurationSec']<=3.5)] dfr.to_csv('data/openslr_transcript_ranged2.csv', index=False) dfr import pandas as pd import data_dekhabet as dkb import progressbar as prgs csvf = 'data/openslr_bengali/openslr_transcript_ranged.csv' dfr = pd.read_csv(csvf) vector = [] l = len(dfr) prgs.printProgressBar(0,l) for index, row in dfr.iterrows(): vc = [] for c in str(row['Dekhascript']): vc.append(dkb.tokenlookup2.index(c)) vector.append(vc) prgs.printProgressBar(index,l) dfr = dfr.assign(Vector = vector) dfr dfr.to_csv(csvf, index=False) ###Output _____no_output_____
content/02_operations02.ipynb
###Markdown More StringsThis is not an exhaustive list of all of Python's advanced string processing techniques, but it's a good foundation from which you can explore other resources to learn more. Printing Quotation MarksWe've seen how strings are separated by quotation marks, but what if you want to actually __*print*__ a quotation mark? How would you print this sentence to the screen:`USNA's colors are Blue and Gold`Does the code below do it? ###Code s = "USNA's colors are Blue and Gold" print(s) ###Output _____no_output_____ ###Markdown It does. Maybe that's a clean solution to the problem. Just use double quotes to define the string, and single quotes internal to the string.Assume we want to print this:`These are "double quotes" and these are 'single quotes'`Does this code work? ###Code s = "These are "double quotes" and these are 'single quotes'" print(s) ###Output _____no_output_____ ###Markdown What error message do you get when you run that code?There is a way to handle quotation marks and many other special characters that you'll see throughout the course. The term we use is **"escaping"** the special character [(more here)](https://docs.python.org/3/reference/lexical_analysis.htmlstring-and-bytes-literals). The escape character for strings is the backslash (`\`), and we use it like this: ###Code s = "These are \"double quotes\" and these are \'single quotes\'" print(s) ###Output _____no_output_____ ###Markdown The code looks a little busy, but the more you use the syntax, the more you'll become comfortable with it. Notice that Python doesn't print the backslash character itself. Using a backslash character in a string is the same as telling Python: "*When you see a backslash character, actually print what comes immediately after it, not the backslash itself.*"So what do you do if you actually want to print a backslash character, like this:`Here is a directory path in MS-Windows: c:\smith\Documents`The definition above still holds. Just use two backslashes! ###Code s = "Here is a directory path in MS-Windows: c:\\smith\\Documents" print(s) ###Output _____no_output_____ ###Markdown Accessing Individual Characters (revisited)In the [first notebook on strings](02_operations01.ipynb) we examined how to access individual characters. The example we gave was pretty straightforward because we chose the string to manipulate. What happens if you don't know the string in advance? What if you prompt the user for a string and then need to find specific characters?Here's an example of finding the length of a user-entered string and accessing individual characters. ###Code s = input("Enter a string: ") length = len(s) print("Number of characters in your string:", length) print("The first character in your string is:", s[0]) print("The last character in your string is:", s[-1]) ###Output _____no_output_____ ###Markdown I never explained it, but what do you think Python's [len()](https://docs.python.org/3/library/functions.html) function does in line 5 in the code above? String SlicingCarving up strings in python is known as *slicing*. While strings are immutable (unchangeable), you can still slice parts of them to create substrings and assemble the parts (concatenate them) in various ways. Here are some syntax rules for various slicing operations (assume we have a string variable called `s`):`s[start:end]` The substring in `s` from the character at position `start` to the character at position `end`-1.`s[start:]` The substring in `s` from the character at position `start` to the end of the string.`s[:end]` The substring in `s` from the beginning of the string to the character at position `end`-1.`s[:]` A complete copy of `s`.Below is an example of slicing a string. Try to predict what will be printed in each example, then run the code to check your work. ###Code s = "Here is a string we can use to test" print(s[5:13]) s2 = s[6:] print(s2) s2 = s[:8] print(s2) print(s[:16] + s[27:]) ###Output _____no_output_____ ###Markdown A Roundabout Way to Mutate a String Using SlicingIn the [first string notebook](02_operations01.ipynb), I said that you can't mutate a string (change individual characters). So, for example, how would we insert a new word into the middle of a string? The code below demonstrates one technique: ###Code s1 = input("Enter a string: ") word = input("Enter a word to insert in the middle: ") middle = len(s1) // 2 part1 = s1[:middle] # end = middle - 1 part2 = s1[middle:] # start = middle print("Your new string is: ", part1 + word + part2) ###Output _____no_output_____ ###Markdown What's the difference between division using `/` and division using `//`? [(hint)](https://docs.python.org/3/library/stdtypes.htmltypesnumeric) Type ConversionsSo far our use of Python's [input()](https://docs.python.org/3/library/functions.htmlinput) function has been limited to string data, but what about getting numerical input from the user? Run the code below. ###Code n = input("Enter an integer: ") print("2n =", 2*n) ###Output _____no_output_____ ###Markdown Interesting, right? It doesn't crash, but it doesn't exactly do what we want. That's because Python's [input()](https://docs.python.org/3/library/functions.htmlinput) function assumes that everything you type is a string, and if you want it to represent some other type it's up to you to do the conversion. So how do you convert the string `"5"` into the integer `5`? Use Python's [int()](https://docs.python.org/3/library/functions.html) function. ###Code n = input("Enter an integer: ") integer = int(n) print("2n =", 2*integer) ###Output _____no_output_____ ###Markdown Converting data from one type to another is called *casting*. When casting input to integers, a common technique is to combine the use of [int()](https://docs.python.org/3/library/functions.html) with [input()](https://docs.python.org/3/library/functions.htmlinput) on a single line like this: ###Code n = int(input("Enter an integer: ")) print("2n =", 2*n) ###Output _____no_output_____ ###Markdown You can use [int()](https://docs.python.org/3/library/functions.html) to cast floats to integers as well. What happens when you run the code below? ###Code pi = 3.14159 print("Int pi =", int(pi)) ###Output _____no_output_____ ###Markdown You can also cast numeric types into strings using Python's [str()](https://docs.python.org/3/library/functions.html) function. ###Code n = 42 pi = 3.14159 s = str(n) + str(pi) print(s) ###Output _____no_output_____
examples/Movie-Lens/1M/Movie-Lens-1M-Content-Builder.ipynb
###Markdown Enhancing item features with TMDB ###Code import re def clean_text(text): EMPTY = ' ' if text is None: return EMPTY text = text.replace("\n", " ").replace("(", " ").replace(")", " ").replace("\r", " ").replace("\t", " ").lower() text = re.sub('<pre><code>.*?</code></pre>', EMPTY, text) text = re.sub('<code>.*?</code>', EMPTY, text) def replace_link(match): return EMPTY if re.match('[a-z]+://', match.group(1)) else match.group(1) text = re.sub('<a[^>]+>(.*)</a>', replace_link, text) text = re.sub('<.*?>', EMPTY, text) return text def get_movie_details_from_tmdb(movie_id, title, year): year = int(year) search = tmdb.Search() response = search.movie(query=title) results = response['results'] if len(results) == 0: tn = title.split(",")[0] search = tmdb.Search() response = search.movie(query=tn) results = response['results'] if len(results) == 0: tn = title.split(":")[0] search = tmdb.Search() response = search.movie(query=tn) results = response['results'] if len(results) == 0: tn = title.split("(")[0] search = tmdb.Search() response = search.movie(query=tn) results = response['results'] from functools import cmp_to_key def cmp(m1, m2): edst_1 = editdistance(title.lower(), m1['title'].lower()) edst_2 = editdistance(title.lower(), m2['title'].lower()) if 'release_date' not in m1: return 1 if 'release_date' not in m2: return -1 year_diff_1 = np.abs(pd.to_datetime(m1['release_date']).year - year) year_diff_2 = np.abs(pd.to_datetime(m2['release_date']).year - year) score_1 = 0.3 * edst_1 + year_diff_1 score_2 = 0.3 * edst_2 + year_diff_2 return -1 if score_1 <= score_2 else 1 results = list(sorted(results, key=cmp_to_key(cmp))) if len(results) > 0: movie = tmdb.Movies(results[0]['id']) keywords = [k['name'] for k in movie.keywords()['keywords']] info = movie.info() original_language = info['original_language'] overview = clean_text(info['overview']) runtime = info['runtime'] tagline = clean_text(info['tagline']) original_title = info['original_title'] title = info['title'] release_date = info['release_date'] return {"movie_id":movie_id,"title":title, "keywords":keywords, "original_language":original_language, "overview":overview, "runtime":runtime, "tagline":tagline, 'original_title':original_title, "release_date":release_date, "success":True} else: return {"movie_id":movie_id,"title":title, "keywords":[], "original_language":'', "overview":'', "runtime":-1, "tagline":'', 'original_title':'',"release_date":str(year), "success":False} get_movie_details_from_tmdb(movie_id=100,title="Toy Story", year=1995) movies.head(3).apply(lambda m:get_movie_details_from_tmdb(m['title'],m['year'])['overview'], axis=1) tmdb_data = {} titles_years = list(zip(movies['movie_id'], movies['title'],movies['year'])) # overviews = Parallel(n_jobs=8)(delayed(get_movie_details_from_tmdb)(title,year) for title,year in tqdm_notebook(titles_years)) for movie_id,title,year in tqdm_notebook(titles_years): if movie_id in tmdb_data: continue movie_detail = get_movie_details_from_tmdb(movie_id=movie_id, title=title, year=year) tmdb_data[movie_id] = movie_detail unsuccessful =[k for k,v in tmdb_data.items() if not v['success']] len(unsuccessful) movies[movies.movie_id.isin(unsuccessful)].head(30).tail(5) movie_id = "3854" movie_detail = get_movie_details_from_tmdb(movie_id=movie_id, title="Jaguar", year=1999) movie_detail if movie_detail["success"]: tmdb_data[movie_id] = movie_detail else: print("Fail") unsuccessful =[k for k,v in tmdb_data.items() if not v['success']] len(unsuccessful) tmdb_df = pd.DataFrame.from_records(list(tmdb_data.values())) tmdb_df.drop(columns=["success"], inplace=True) tmdb_df.shape assert tmdb_df.shape[0] == len(list(tmdb_data.values())) tmdb_df.to_csv("tmdb_data.csv", sep="\t", index=False) movies.shape tmdb_df.rename(columns={"title":"tmdb_title"}, inplace=True) movies = movies.merge(tmdb_df, on="movie_id") movies.shape movies.to_csv("movies.csv", sep="\t", index=False) user_movie_counts = ratings.groupby(["user_id"])[["movie_id"]].count() user_movie_counts.head() user_movie_counts.sort_values(by=["movie_id"]).head(100) movies = pd.read_csv("movies.csv", sep="\t", engine="python") users = pd.read_csv("users.csv", sep="\t") ratings = pd.read_csv("ratings.csv", sep="\t") ###Output _____no_output_____
Trabajo-especializacion/notebooks/00_features-selection.ipynb
###Markdown Creación del dataset ###Code import pandas as pd import numpy as np path_original = "..\\data\\original\\" path_proc = "..\\data\\processed\\" path_ext = "..\\data\\external\\" ###Output _____no_output_____ ###Markdown Selección de variables ###Code # Lista de variables seleccionadas sel = pd.read_csv(path_ext + "feat_selection.csv") # Convertir a lists sel = sel.Features.values.tolist() len(sel) # Dataset de trabajo data = pd.read_csv(path_original + "data_original.csv") data.head() # Selección de variables data = data[sel] data.head() ###Output _____no_output_____ ###Markdown Creación de variable ID El ID único de cada individuo se crea mediante la concatenación de los siguientes campos: SRVY_YR: año de la encuesta HHX: número de vivienda FMX: número de familia FPX: número de inviduo dentro de la familia(mientras sean datos de un único año no se usará el año como ID) ###Code # data["id"] = data["SRVY_YR"].astype(str) + data["HHX"].astype(str) + data["FMX"].astype(str) + data["FPX"].astype(str) # Nuevo Id data["id"] = data["HHX"].astype(str) + data["FMX"].astype(str) + data["FPX"].astype(str) # Se descartan las variables usadas data = data.drop(["SRVY_YR","HHX","FMX","FPX"], axis=1) # Chequea que sean valores únicos print("Cantidad de registros: " + str(data.shape[0])) print("Cantidad de id únicos: " + str(len(np.unique(data["id"])))) ###Output Cantidad de registros: 25417 Cantidad de id únicos: 25417 ###Markdown Variable Target La variable target es **AMIGR**: "¿ha padecido migraña o cefaleas severas en los últimos 3 meses?". Los registros con valores 7 (se rehusa a responder), 8 (no corresponde) y 9 (no sabe responder) en esta variable son removidos. Los valores 2 (no) se cambian a 0. ###Code data = data[(data["AMIGR"] == 1) | (data["AMIGR"] == 2)] data.loc[(data["AMIGR"] == 2),"AMIGR"] = 0 print("Cantidad de registros: " + str(data.shape[0])) print("Cantidad de columnas: " + str(data.shape[1])) # Chequea categorías data.AMIGR.unique() # Rename target data = data.rename(columns={"AMIGR":"target"}) data.info() ###Output <class 'pandas.core.frame.DataFrame'> Int64Index: 25403 entries, 0 to 25416 Data columns (total 55 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 REGION 25403 non-null int64 1 SEX 25403 non-null int64 2 RACERPI2 25403 non-null int64 3 AGE_P 25403 non-null int64 4 R_MARITL 25403 non-null int64 5 DOINGLWA 25403 non-null int64 6 WRKLYR4 25403 non-null int64 7 HYPYR1 8045 non-null float64 8 HYPMED2 8225 non-null float64 9 CHLYR 7921 non-null float64 10 CHLMDNW2 5969 non-null float64 11 ANGEV 25403 non-null int64 12 MIEV 25403 non-null int64 13 HRTEV 25403 non-null int64 14 STREV 25403 non-null int64 15 EPHEV 25403 non-null int64 16 COPDEV 25403 non-null int64 17 ASPMEDAD 5954 non-null float64 18 ASPONOWN 11692 non-null float64 19 AASSTILL 3444 non-null float64 20 ULCYR 1795 non-null float64 21 CANEV 25403 non-null int64 22 DIBEV1 25403 non-null int64 23 DIBPILL1 4768 non-null float64 24 INSLN1 4768 non-null float64 25 AHAYFYR 25403 non-null int64 26 SINYR 25403 non-null int64 27 CBRCHYR 25403 non-null int64 28 KIDWKYR 25403 non-null int64 29 LIVYR 25403 non-null int64 30 ARTH1 25403 non-null int64 31 PAINECK 25403 non-null int64 32 PAINLB 25403 non-null int64 33 PAINFACE 25403 non-null int64 34 target 25403 non-null int64 35 PREGNOW 6115 non-null float64 36 FLA1AR 25403 non-null int64 37 CIGSDAY 3708 non-null float64 38 VIGFREQW 25403 non-null int64 39 VIGMIN 12003 non-null float64 40 MODFREQW 25403 non-null int64 41 MODMIN 16099 non-null float64 42 ALC12MWK 20744 non-null float64 43 ALCAMT 16595 non-null float64 44 AHEIGHT 25403 non-null int64 45 AWEIGHTP 25403 non-null int64 46 BMI 25403 non-null int64 47 APOX 25403 non-null int64 48 AHEP 25403 non-null int64 49 LIVEV 25403 non-null int64 50 ASICPUSE 25403 non-null int64 51 ASISLEEP 25403 non-null int64 52 PROXYSA 25403 non-null int64 53 AFLHC29_ 10869 non-null float64 54 id 25403 non-null object dtypes: float64(17), int64(37), object(1) memory usage: 10.9+ MB ###Markdown Selección de la población de estudio El dataset a utilizar contiene la información relevada de adultos mayores de 18 años. Se considerarán sólo los pacientes que: No padezcan enfermedades mentales graves que provoquen la pérdida del contacto con la realidad, tales como esquizofrenia No padezcan sindromes que deterioren las capacidades psíquicas, tales como la demencia senil No padezcan cáncer al momento de la encuesta No se encuentren embarazadas No padezcan addicción a sustancias de abuso como alcohol o drogasSe utilzan las siguientes variables para filtrar la población de estudio: Conservar CANEV == 2. Pacientes que nunca hayan sido diagnosticados con cáncer. Descartar PREGNOW == 1. Pacientes actualmente embarazadas. Descartar PROXYSA == 1. Pacientes con discapacidad física o mental que les prohíbe responder la encuesta por sí mismos. Descartar AFLHC29_ == 1, 2 y 7. Pacientes con algún tipo de limitación física como consecuencia del uso de alcohol o drogas. ###Code # Filtrado data = data[(data["CANEV"] == 2) & (data["PREGNOW"] != 1) & (data["PROXYSA"] != 1) & (data["AFLHC29_"].isin([1,2,7]) == False)] # Descarta variables usadas data = data.drop(["CANEV","PREGNOW","PROXYSA","AFLHC29_"], axis=1) print("Cantidad de registros: " + str(data.shape[0])) print("Cantidad de columnas: " + str(data.shape[1])) ###Output Cantidad de registros: 13479 Cantidad de columnas: 51 ###Markdown Recodificación de variables Estado civil ###Code # 0: menor de 14 años. No debería haber data[data["R_MARITL"] == 0] # 1-2-3 => 1 (casado) data.loc[((data["R_MARITL"] == 1) | (data["R_MARITL"] == 2) | (data["R_MARITL"] == 3)), "R_MARITL"] = np.int(1) # 4 => 2 (viudo) data.loc[data["R_MARITL"] == 4, "R_MARITL"] = np.int(2) # 5-6 => 3 (separado) data.loc[((data["R_MARITL"] == 5) | (data["R_MARITL"] == 6)), "R_MARITL"] = np.int(3) # 7 => 4 (soltero) data.loc[data["R_MARITL"] == 7, "R_MARITL"] = np.int(4) # 8 => 5 (en pareja) data.loc[data["R_MARITL"] == 8, "R_MARITL"] = np.int(5) # 9 => NaN (desconocido) data.loc[data["R_MARITL"] == 9, "R_MARITL"] = np.nan # Chequea categorías data.R_MARITL.unique() ###Output _____no_output_____ ###Markdown Situación laboral Actual ¿Tiene trabajo actualmente? ###Code # 1,2,4 => 1 (si) data.loc[((data["DOINGLWA"] == 1) | (data["DOINGLWA"] == 2) | (data["DOINGLWA"] == 4)), "DOINGLWA"] = np.int(1) # 3,5 => 0 (no) data.loc[((data["DOINGLWA"] == 3) | (data["DOINGLWA"] == 5)), "DOINGLWA"] = np.int(0) # 7,8,9 => NaN (desconocido) data.loc[((data["DOINGLWA"] == 7) | (data["DOINGLWA"] == 8) | (data["DOINGLWA"] == 9)), "DOINGLWA"] = np.nan # Chequea categorías data.DOINGLWA.unique() ###Output _____no_output_____ ###Markdown Últimos 12 meses ¿Tuvo trabajo en los últimos 12 meses? ###Code # 0,1 => 1 (si) data.loc[((data["WRKLYR4"] == 0) | (data["WRKLYR4"] == 1)), "WRKLYR4"] = np.int(1) # 2,3 => 0 (no) data.loc[((data["WRKLYR4"] == 2) | (data["WRKLYR4"] == 3)), "WRKLYR4"] = np.int(0) # 7,8,9 => NaN (desconocido) data.loc[((data["WRKLYR4"] == 7) | (data["WRKLYR4"] == 8) | (data["WRKLYR4"] == 9)), "WRKLYR4"] = np.nan # Chequea categorías data.WRKLYR4.unique() ###Output _____no_output_____ ###Markdown Medicamentos Aspirina Se unificarán las siguientes variables: ASPMEDAD: toma aspirina por recomendación médica. ASPONOWN: toma aspirina sin recomendación médica.Considerándose la pregunta: "¿Toma aspirina actualmente?". Los NaN correspondena individuos que no cumplen con la población en estudio (adultos mayores de 40 que alguna vez se les ha recomendado que tomen aspirina). ###Code # Los NaN son convertidos a 0, dado que no cumplen con la condición de la población en estudio. data.loc[(data["ASPMEDAD"].isna() == True), "ASPMEDAD"] = np.int(0) data.loc[(data["ASPONOWN"].isna() == True), "ASPONOWN"] = np.int(0) data[["ASPMEDAD","ASPONOWN"]] conditions = [ (data['ASPMEDAD'] == 1) | (data['ASPONOWN'] == 1), # una de las respuestas es "si" (data['ASPMEDAD'] == 2) | (data['ASPONOWN'] == 2), # la respuesta es "no" (data['ASPMEDAD'] == 0) & (data['ASPONOWN'] == 0)] # la respuesta es "no" por no ser parte de la población choices = [1, 0, 0] data['ASP'] = np.select(conditions, choices, default=np.nan) data[["ASPMEDAD","ASPONOWN", "ASP"]].head() # Chequea categorías data.ASP.unique() # Descarta variables usadas data = data.drop(["ASPMEDAD","ASPONOWN"], axis=1) ###Output _____no_output_____ ###Markdown Enfermedades crónicas Diabetes Se reformula la pregunta: "¿alguna vez le han diagnosticado diabetes o pre-diabetes?" ###Code # 1 => 1 (si) data.loc[data["DIBEV1"] == 1, "DIBEV1"] = np.int(1) # 2 => 0 (no) data.loc[data["DIBEV1"] == 2, "DIBEV1"] = np.int(0) # 3 => 1 (prediabetes) data.loc[data["DIBEV1"] == 3, "DIBEV1"] = np.int(1) # 7,8,9 => NaN (desconocido) data.loc[((data["DIBEV1"] == 7) | (data["DIBEV1"] == 8) | (data["DIBEV1"] == 9)), "DIBEV1"] = np.nan # Chequea categorías data.DIBEV1.unique() ###Output _____no_output_____ ###Markdown Limitaciones físicas ¿Posee algún tipo de limitación física/funcional? ###Code # 1 => 1 (si) data.loc[data["FLA1AR"] == 0, "FLA1AR"] = np.int(1) # 2 => 0 (no) data.loc[data["FLA1AR"] == 2, "FLA1AR"] = np.int(0) # 3 => nan (no lo sabe) data.loc[data["FLA1AR"] == 3, "FLA1AR"] = np.nan # Chequea categorías data.FLA1AR.unique() ###Output _____no_output_____ ###Markdown Hábitos Uso de PC ¿Qué tan frecuente utiliza la computadora? ###Code # 1 => 0 (nunca o casi nunca) data.loc[data["ASICPUSE"] == 1, "ASICPUSE"] = np.int(0) # 2 => 1 (a veces) data.loc[data["ASICPUSE"] == 2, "ASICPUSE"] = np.int(1) # 3 => 2 (casi todos los días) data.loc[data["ASICPUSE"] == 3, "ASICPUSE"] = np.int(2) # 4 => 3 (todos los días) data.loc[data["ASICPUSE"] == 4, "ASICPUSE"] = np.int(3) # 7,8,9 => NaN (desconocido) data.loc[((data["ASICPUSE"] == 7) | (data["ASICPUSE"] == 8) | (data["ASICPUSE"] == 9)), "ASICPUSE"] = np.nan # Chequea categorías data.ASICPUSE.unique() ###Output _____no_output_____ ###Markdown Horas de sueño En promedio ¿cuántas horas duerme en un periodo de 24 horas? ###Code # 97,98,99 => nan (desconocido) data.loc[((data["ASISLEEP"] == 97) | (data["ASISLEEP"] == 98) | (data["ASISLEEP"] == 99)), "ASISLEEP"] = np.nan # Chequea categorías data.ASISLEEP.unique() ###Output _____no_output_____ ###Markdown Fumar ¿Cuántos cigarros (de cualquier tipo) fuma al día?. Esta pregunta es sólo para fumadores, los NaN son no fumadores. ###Code # Cantidad de cigarrillos que fuma por día (todo los tipos) # 97,98,99 => nan (desconocido) data.loc[((data["CIGSDAY"] == 97) | (data["CIGSDAY"] == 98) | (data["CIGSDAY"] == 99)), "AHEIGHT"] = np.nan # Los NaN son convertidos a 0, dado que no cumplen con la condición de la población en estudio. data.loc[(data["CIGSDAY"].isna() == True), "CIGSDAY"] = np.int(0) # Chequea categorías data.CIGSDAY.unique() ###Output _____no_output_____ ###Markdown Ejercicio físico Se unifican las preguntas de "¿Cuántas veces por semana realiza ejercicico?" y "¿Cuántos minutos de ejericicio realiza?" a la pregunta: "¿Cuntos minutos de ejercico realiza por semana?". Separado según la intensidad del ejercicio: - **VIG**: ejercicio vigoroso. - **MOD**: ejercicio liviano o moderado. **Vigoroso** ###Code # Frecuencia semanal # 00,95,96 => 0 (nunca) data.loc[((data["VIGFREQW"] == 0) | (data["VIGFREQW"] == 95) | (data["VIGFREQW"] == 96)), "VIGFREQW"] = np.int(0) # 97,98,99 => nan (desconocido) data.loc[((data["VIGFREQW"] == 97) | (data["VIGFREQW"] == 98) | (data["VIGFREQW"] == 99)), "VIGFREQW"] = np.nan # Minutos # 997,998,999 => nan (desconocido) data.loc[((data["VIGMIN"] == 997) | (data["VIGMIN"] == 998) | (data["VIGMIN"] == 999)), "VIGMIN"] = np.nan # Condiciones para calcular los minutos de ejercicio conditions = [ (data['VIGFREQW'] == 0), # no realiza ejercicio (data['VIGFREQW'].isna() == True), # Se desconoce si realiza ejercicio (data['VIGFREQW'] > 0)] # Realiza ejercicio más de 1 vez por semana choices = [0, np.nan, data['VIGFREQW'] * data['VIGMIN']] data['VIG'] = np.select(conditions, choices, default=0) data[["VIGFREQW","VIGMIN","VIG"]] data.loc[data["VIG"] > 5000, ["VIGFREQW","VIGMIN","VIG","AGE_P"]] # Se descartan las variables viejas data = data.drop(["VIGFREQW","VIGMIN"], axis=1) # Chequea categorías data.VIG.unique() ###Output _____no_output_____ ###Markdown **Moderado** ###Code # Frecuencia semanal # 00,95,96 => 0 (nunca) data.loc[((data["MODFREQW"] == 0) | (data["MODFREQW"] == 95) | (data["MODFREQW"] == 96)), "MODFREQW"] = np.int(0) # 97,98,99 => nan (desconocido) data.loc[((data["MODFREQW"] == 97) | (data["MODFREQW"] == 98) | (data["MODFREQW"] == 99)), "MODFREQW"] = np.nan # Minutos # 997,998,999 => nan (desconocido) data.loc[((data["MODMIN"] == 997) | (data["MODMIN"] == 998) | (data["MODMIN"] == 999)), "MODMIN"] = np.nan # Condiciones para calcular los minutos de ejercicio conditions = [ (data['MODFREQW'] == 0), # no realiza ejercicio (data['MODFREQW'].isna() == True), # Se desconoce si realiza ejercicio (data['MODFREQW'] > 0)] # Realiza ejercicio más de 1 vez por semana choices = [0, np.nan, data['MODFREQW'] * data['MODMIN']] data['MOD'] = np.select(conditions, choices, default=0) data[["MODFREQW","MODMIN","MOD"]] data.loc[data["MOD"] > 5000, ["MODFREQW","MODMIN","MOD","AGE_P"]] # Se descartan las variables viejas data = data.drop(["MODFREQW","MODMIN"], axis=1) # Chequea categorías data.MOD.unique() ###Output _____no_output_____ ###Markdown Consumo de alcohol Se unifican las preguntas "¿En promedio cuántas veces por semana bebió alcohol en el último año?" y "¿En promedio cuántos vasos bebe cada vez que toma?" a: ¿En promedio cuántos vasos de alcohol bebe por semana?" **Bebidas por semana** ###Code # 00,95 => 0 (nunca) data.loc[((data["ALC12MWK"] == 0) | (data["ALC12MWK"] == 95)), "ALC12MWK"] = np.int(0) # 97,98,99 => nan (desconocido) data.loc[((data["ALC12MWK"] == 97) | (data["ALC12MWK"] == 98) | (data["ALC12MWK"] == 99)), "ALC12MWK"] = np.nan # NaN => 0 (No bebe) data.loc[(data['ALC12MWK'].isna() == True), "ALC12MWK"] = np.int(0) # Chequea categorías data.ALC12MWK.unique() ###Output _____no_output_____ ###Markdown **Cantidad de vasos** ###Code # 97,98,99 => nan (desconocido) data.loc[((data["ALCAMT"] == 97) | (data["ALCAMT"] == 98) | (data["ALCAMT"] == 99)), "ALCAMT"] = np.nan # NaN => 0 (No bebió en el último año) data.loc[(data['ALCAMT'].isna() == True), "ALCAMT"] = np.int(0) # Chequea categorías data.ALCAMT.unique() ###Output _____no_output_____ ###Markdown **Nueva variable** ###Code # Condiciones para calcular los minutos de ejercicio conditions = [ (data['ALC12MWK'] == 0), # no realiza ejercicio (data['ALC12MWK'] > 0)] # Realiza ejercicio más de 1 vez por semana choices = [0, data['ALC12MWK'] * data['ALCAMT']] data['ALC'] = np.select(conditions, choices, default=0) data[["ALC12MWK","ALCAMT", "ALC"]] # Chequea categorías data.ALC.unique() # Se descartan las variables viejas data = data.drop(["ALC12MWK","ALCAMT"], axis=1) ###Output _____no_output_____ ###Markdown Estado físico del paciente Altura ###Code # 96,97,98,99 => nan (desconocido) data.loc[((data["AHEIGHT"] == 96) | (data["AHEIGHT"] == 97) | (data["AHEIGHT"] == 98) | (data["AHEIGHT"] == 99)), "AHEIGHT"] = np.nan # Se convierte de pulgadas a cm data["AHEIGHT"] = data["AHEIGHT"] * 2.54 print("Mínimo valor: " + str(data["AHEIGHT"].min())) print("Máximo valor: " + str(data["AHEIGHT"].max())) ###Output Mínimo valor: 149.86 Máximo valor: 193.04 ###Markdown Peso ###Code # 996,997,998,999 => nan (desconocido) data.loc[((data["AWEIGHTP"] == 996) | (data["AWEIGHTP"] == 997) | (data["AWEIGHTP"] == 998) | (data["AWEIGHTP"] == 999)), "AWEIGHTP"] = np.nan # Se convierte de pounds a Kg data["AWEIGHTP"] = round(data["AWEIGHTP"] * 0.453592, 1) print("Mínimo valor: " + str(data["AWEIGHTP"].min())) print("Máximo valor: " + str(data["AWEIGHTP"].max())) ###Output Mínimo valor: 45.4 Máximo valor: 135.2 ###Markdown Índice de masa corporal Esta variable si bien es contínua, está indicada en el dataset original por códigos. Aquí se reemplazará por el cálculo de BMI = peso (Kg) / altura (m) al cuadrado ###Code # 9999 => nan (desconocido) data.loc[data["BMI"] == 9999, "BMI"] = np.nan data["BMI"] = round(data["AWEIGHTP"] / np.power(data["AHEIGHT"]/100,2),2) print("Mínimo valor: " + str(data["BMI"].min())) print("Máximo valor: " + str(data["BMI"].max())) ###Output Mínimo valor: 15.68 Máximo valor: 49.92 ###Markdown Variables con misma recodificación ###Code feat_list = ["HYPYR1", "HYPMED2", "CHLYR", "CHLMDNW2", "ANGEV", "MIEV", "HRTEV", "STREV", "EPHEV", "COPDEV", "AASSTILL", "ULCYR", "DIBPILL1", "INSLN1", "AHAYFYR", "SINYR", "CBRCHYR", "KIDWKYR", "LIVYR", "ARTH1", "PAINECK", "PAINLB", "PAINFACE", "APOX", "AHEP", "LIVEV"] for i in feat_list: print("Variable " + str(i)) print(" Categorías: " + str(list(data[i].unique()))) print(" Nulos: " + str(round(data[i].isna().sum()*100/len(data),2))) print() for i in feat_list: print("Transformando variable " + str(i)) # Los NaN son convertidos a 0, dado que no cumplen con la condición de la población en estudio data.loc[(data[i].isna() == True), i] = np.int(0) # 1 => 1 (si) data.loc[(data[i] == 1), i] = np.int(1) # 2 => 0 (no) data.loc[(data[i] == 2), i] = np.int(0) # 7,8,9 => NaN (desconocido) data.loc[((data[i] == 7) | (data[i] == 8) | (data[i] == 9)), i] = np.nan print("Categorías: " + str(list(data[i].unique()))) print() ###Output Transformando variable HYPYR1 Categorías: [0.0, 1.0, nan] Transformando variable HYPMED2 Categorías: [0.0, 1.0] Transformando variable CHLYR Categorías: [0.0, 1.0, nan] Transformando variable CHLMDNW2 Categorías: [0.0, 1.0] Transformando variable ANGEV Categorías: [0.0, 1.0, nan] Transformando variable MIEV Categorías: [0.0, 1.0, nan] Transformando variable HRTEV Categorías: [0.0, 1.0, nan] Transformando variable STREV Categorías: [0.0, 1.0, nan] Transformando variable EPHEV Categorías: [0.0, 1.0, nan] Transformando variable COPDEV Categorías: [0.0, 1.0, nan] Transformando variable AASSTILL Categorías: [0.0, 1.0, nan] Transformando variable ULCYR Categorías: [0.0, 1.0, nan] Transformando variable DIBPILL1 Categorías: [0.0, 1.0, nan] Transformando variable INSLN1 Categorías: [0.0, 1.0] Transformando variable AHAYFYR Categorías: [0.0, 1.0, nan] Transformando variable SINYR Categorías: [0.0, 1.0, nan] Transformando variable CBRCHYR Categorías: [0.0, 1.0, nan] Transformando variable KIDWKYR Categorías: [0.0, 1.0] Transformando variable LIVYR Categorías: [0.0, 1.0, nan] Transformando variable ARTH1 Categorías: [0.0, 1.0, nan] Transformando variable PAINECK Categorías: [1.0, 0.0, nan] Transformando variable PAINLB Categorías: [1.0, 0.0, nan] Transformando variable PAINFACE Categorías: [0.0, 1.0] Transformando variable APOX Categorías: [1.0, 0.0, nan] Transformando variable AHEP Categorías: [0.0, nan, 1.0] Transformando variable LIVEV Categorías: [0.0, nan, 1.0] ###Markdown Exportar dataset ###Code # Reordenar data = data[ [ "id", "REGION", "SEX", "AHEIGHT", "AWEIGHTP", "BMI", "AGE_P", "RACERPI2", "R_MARITL", "DOINGLWA", "WRKLYR4", "HYPYR1", "HYPMED2", "CHLYR", "CHLMDNW2", "ANGEV", "MIEV", "HRTEV", "STREV", "EPHEV", "COPDEV", "ASP", "AASSTILL", "ULCYR", "DIBEV1", "DIBPILL1", "INSLN1", "AHAYFYR", "SINYR", "CBRCHYR", "KIDWKYR", "LIVYR", "ARTH1", "PAINECK", "PAINLB", "PAINFACE", "FLA1AR", "CIGSDAY", "VIG", "MOD", "ALC", "APOX", "AHEP", "LIVEV", "ASICPUSE", "ASISLEEP", "target", ] ] # Reset index data = data.reset_index(drop=True) data.info() data.target.value_counts() # Exportar dataset data.to_csv(path_proc + "data_filter.csv", index=False) ###Output _____no_output_____
ESRGAN-old--master/ESRGAN-old--master/ESRGAN_Old_Colab.ipynb
###Markdown ESRGAN (old arch.) on ColabOfficial Github Repo: https://github.com/xinntao/ESRGAN This notebook was curated by M. Ahabb (Ahabbscience Studio) ###Code !nvidia-smi #recommended gpus are p100 and T4 ###Output Tue Jun 30 16:56:07 2020 +-----------------------------------------------------------------------------+ | NVIDIA-SMI 450.36.06 Driver Version: 418.67 CUDA Version: 10.1 | |-------------------------------+----------------------+----------------------+ | GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC | | Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. | | | | MIG M. | |===============================+======================+======================| | 0 Tesla T4 Off | 00000000:00:04.0 Off | 0 | | N/A 46C P8 9W / 70W | 0MiB / 15079MiB | 0% Default | | | | ERR! | +-------------------------------+----------------------+----------------------+ +-----------------------------------------------------------------------------+ | Processes: | | GPU GI CI PID Type Process name GPU Memory | | ID ID Usage | |=============================================================================| | No running processes found | +-----------------------------------------------------------------------------+ ###Markdown Clone ESRGAN repo ###Code !git clone https://github.com/AhabbscienceStudioPak/ESRGAN-old- ###Output Cloning into 'ESRGAN-old-'... remote: Enumerating objects: 39, done. remote: Counting objects: 100% (39/39), done. remote: Compressing objects: 100% (36/36), done. remote: Total 39 (delta 2), reused 0 (delta 0), pack-reused 0 Unpacking objects: 100% (39/39), done. ###Markdown This is optional if you want to link your google drive to the notebook to add files or pretrained models of your choice from your google drive. A list of Pre-trained models can be found here: https://upscale.wiki/wiki/Model_Database ###Code from google.colab import drive drive.mount('/content/gdrive') ###Output Go to this URL in a browser: https://accounts.google.com/o/oauth2/auth?client_id=947318989803-6bn6qk8qdgf4n4g3pfee6491hc0brc4i.apps.googleusercontent.com&redirect_uri=urn%3aietf%3awg%3aoauth%3a2.0%3aoob&response_type=code&scope=email%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdocs.test%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive.photos.readonly%20https%3a%2f%2fwww.googleapis.com%2fauth%2fpeopleapi.readonly Enter your authorization code: ·········· Mounted at /content/gdrive ###Markdown (Optional) Add Files via youtube_dl ###Code !pip install youtube_dl !mkdir -p /content/ESRGAN-old-/video_input !youtube-dl -f 18 -o "/content/ESRGAN/video_input/video.mp4" https://www.youtube.com/watch?v=ljwTaMfORzs ###Output _____no_output_____ ###Markdown Run this cell to upload images ###Code !mkdir -p /content/ESRGAN-old-/LR %cd /content/ESRGAN-old-/LR from google.colab import files uploaded = files.upload() for filename in uploaded.keys(): print('User uploaded file "{name}" with {length} bytes'.format(name=filename, length=len(uploaded[filename]))) ###Output /content/ESRGAN-old-/LR ###Markdown Run this cell if you want to upload your video. Make sure your video filename contains no spaces, e.g, "my_video" - not "my video". And upload one video per operation. ###Code !mkdir -p /content/ESRGAN-old-/video_input !mkdir -p /content/ESRGAN-old-/LR %cd /content/ESRGAN-old-/video_input from google.colab import files uploaded = files.upload() for filename in uploaded.keys(): print('User uploaded file "{name}" with {length} bytes'.format(name=filename, length=len(uploaded[filename]))) ###Output /content/ESRGAN-old-/video_input ###Markdown Run this cell to convert your video to individual frames and save them to 'LR' folder. ###Code %cd /content/ESRGAN-old-/LR !ffmpeg -i /content/ESRGAN-old-/video_input/* %04d.png ###Output /content/ESRGAN-old-/LR ffmpeg version 3.4.6-0ubuntu0.18.04.1 Copyright (c) 2000-2019 the FFmpeg developers built with gcc 7 (Ubuntu 7.3.0-16ubuntu3) configuration: --prefix=/usr --extra-version=0ubuntu0.18.04.1 --toolchain=hardened --libdir=/usr/lib/x86_64-linux-gnu --incdir=/usr/include/x86_64-linux-gnu --enable-gpl --disable-stripping --enable-avresample --enable-avisynth --enable-gnutls --enable-ladspa --enable-libass --enable-libbluray --enable-libbs2b --enable-libcaca --enable-libcdio --enable-libflite --enable-libfontconfig --enable-libfreetype --enable-libfribidi --enable-libgme --enable-libgsm --enable-libmp3lame --enable-libmysofa --enable-libopenjpeg --enable-libopenmpt --enable-libopus --enable-libpulse --enable-librubberband --enable-librsvg --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libspeex --enable-libssh --enable-libtheora --enable-libtwolame --enable-libvorbis --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx265 --enable-libxml2 --enable-libxvid --enable-libzmq --enable-libzvbi --enable-omx --enable-openal --enable-opengl --enable-sdl2 --enable-libdc1394 --enable-libdrm --enable-libiec61883 --enable-chromaprint --enable-frei0r --enable-libopencv --enable-libx264 --enable-shared libavutil 55. 78.100 / 55. 78.100 libavcodec 57.107.100 / 57.107.100 libavformat 57. 83.100 / 57. 83.100 libavdevice 57. 10.100 / 57. 10.100 libavfilter 6.107.100 / 6.107.100 libavresample 3. 7. 0 / 3. 7. 0 libswscale 4. 8.100 / 4. 8.100 libswresample 2. 9.100 / 2. 9.100 libpostproc 54. 7.100 / 54. 7.100 Input #0, mov,mp4,m4a,3gp,3g2,mj2, from '/content/ESRGAN-old-/video_input/orange.mp4': Metadata: major_brand : isom minor_version : 512 compatible_brands: isomiso2avc1mp41 encoder : Lavf58.12.100 Duration: 00:00:16.07, start: 0.000000, bitrate: 1835 kb/s Stream #0:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 640x360 [SAR 1:1 DAR 16:9], 1576 kb/s, 25.06 fps, 25 tbr, 12800 tbn, 50 tbc (default) Metadata: handler_name : VideoHandler Stream #0:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 254 kb/s (default) Metadata: handler_name : SoundHandler File '/content/ESRGAN-old-/video_input/sharif3.mp4' already exists. Overwrite ? [y/N] y Stream mapping: Stream #0:0 -> #0:0 (h264 (native) -> h264 (libx264)) Stream #0:1 -> #0:1 (aac (native) -> aac (native)) Stream #0:0 -> #1:0 (h264 (native) -> png (native)) Press [q] to stop, [?] for help [libx264 @ 0x55b671162800] using SAR=1/1 [libx264 @ 0x55b671162800] using cpu capabilities: MMX2 SSE2Fast SSSE3 SSE4.2 AVX FMA3 BMI2 AVX2 AVX512 [libx264 @ 0x55b671162800] profile High, level 3.0 [libx264 @ 0x55b671162800] 264 - core 152 r2854 e9a5903 - H.264/MPEG-4 AVC codec - Copyleft 2003-2017 - http://www.videolan.org/x264.html - options: cabac=1 ref=3 deblock=1:0:0 analyse=0x3:0x113 me=hex subme=7 psy=1 psy_rd=1.00:0.00 mixed_ref=1 me_range=16 chroma_me=1 trellis=1 8x8dct=1 cqm=0 deadzone=21,11 fast_pskip=1 chroma_qp_offset=-2 threads=3 lookahead_threads=1 sliced_threads=0 nr=0 decimate=1 interlaced=0 bluray_compat=0 constrained_intra=0 bframes=3 b_pyramid=2 b_adapt=1 b_bias=0 direct=1 weightb=1 open_gop=0 weightp=2 keyint=250 keyint_min=25 scenecut=40 intra_refresh=0 rc_lookahead=40 rc=crf mbtree=1 crf=23.0 qcomp=0.60 qpmin=0 qpmax=69 qpstep=4 ip_ratio=1.40 aq=1:1.00 Output #0, mp4, to '/content/ESRGAN-old-/video_input/sharif3.mp4': Metadata: major_brand : isom minor_version : 512 compatible_brands: isomiso2avc1mp41 encoder : Lavf57.83.100 Stream #0:0(und): Video: h264 (libx264) (avc1 / 0x31637661), yuv420p, 640x360 [SAR 1:1 DAR 16:9], q=-1--1, 25 fps, 12800 tbn, 25 tbc (default) Metadata: handler_name : VideoHandler encoder : Lavc57.107.100 libx264 Side data: cpb: bitrate max/min/avg: 0/0/0 buffer size: 0 vbv_delay: -1 Stream #0:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 128 kb/s (default) Metadata: handler_name : SoundHandler encoder : Lavc57.107.100 aac Output #1, image2, to '%04d.png': Metadata: major_brand : isom minor_version : 512 compatible_brands: isomiso2avc1mp41 encoder : Lavf57.83.100 Stream #1:0(und): Video: png, rgb24, 640x360 [SAR 1:1 DAR 16:9], q=2-31, 200 kb/s, 25 fps, 25 tbn, 25 tbc (default) Metadata: handler_name : VideoHandler encoder : Lavc57.107.100 png frame= 401 fps= 26 q=-1.0 Lq=-0.0 size= 1429kB time=00:00:16.04 bitrate= 729.4kbits/s speed=1.02x video:132837kB audio:251kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: unknown [libx264 @ 0x55b671162800] frame I:2 Avg QP:23.07 size: 19184 [libx264 @ 0x55b671162800] frame P:129 Avg QP:23.07 size: 6100 [libx264 @ 0x55b671162800] frame B:270 Avg QP:26.67 size: 1352 [libx264 @ 0x55b671162800] consecutive B-frames: 3.5% 18.0% 6.7% 71.8% [libx264 @ 0x55b671162800] mb I I16..4: 9.0% 52.3% 38.6% [libx264 @ 0x55b671162800] mb P I16..4: 4.6% 10.8% 2.6% P16..4: 35.1% 19.1% 9.1% 0.0% 0.0% skip:18.7% [libx264 @ 0x55b671162800] mb B I16..4: 0.6% 1.3% 0.3% B16..8: 32.3% 5.8% 1.0% direct: 2.1% skip:56.6% L0:36.5% L1:50.0% BI:13.5% [libx264 @ 0x55b671162800] 8x8 transform intra:59.2% inter:71.1% [libx264 @ 0x55b671162800] coded y,uvDC,uvAC intra: 47.1% 67.4% 24.3% inter: 14.4% 16.8% 1.2% [libx264 @ 0x55b671162800] i16 v,h,dc,p: 27% 49% 14% 11% [libx264 @ 0x55b671162800] i8 v,h,dc,ddl,ddr,vr,hd,vl,hu: 26% 30% 23% 2% 3% 3% 6% 2% 5% [libx264 @ 0x55b671162800] i4 v,h,dc,ddl,ddr,vr,hd,vl,hu: 32% 31% 11% 3% 5% 5% 6% 3% 5% [libx264 @ 0x55b671162800] i8c dc,h,v,p: 40% 34% 22% 3% [libx264 @ 0x55b671162800] Weighted P-Frames: Y:28.7% UV:22.5% [libx264 @ 0x55b671162800] ref P L0: 67.2% 17.3% 11.9% 3.3% 0.2% [libx264 @ 0x55b671162800] ref B L0: 94.0% 5.0% 1.0% [libx264 @ 0x55b671162800] ref B L1: 98.0% 2.0% [libx264 @ 0x55b671162800] kb/s:593.73 [aac @ 0x55b671163700] Qavg: 329.188 ###Markdown Download pretrained models ###Code import gdown print("Downloading pretrained models") output1 = '/content/ESRGAN-old-/models/RRDB_ESRGAN_x4.pth' output2 = '/content/ESRGAN-old-/models/RRDB_PSNR_x4.pth' output3 = '/content/ESRGAN-old-/models/deviantPixelHD_250000.pth' output4 = '/content/ESRGAN-old-/models/SmoothRealism.pth' output5 = '/content/ESRGAN-old-/models/Manga109Attempt.pth' print ('Downloading model RRDB_ESRGAN_x4.pth') gdown.download('https://drive.google.com/uc?id=1MJFgqXJrMkPdKtiuy7C6xfsU1QIbXEb-', output1, quiet=True) print ('Downloading model RRDB_PSNR_x4.pth') gdown.download('https://drive.google.com/uc?id=1mSJ6Z40weL-dnPvi390xDd3uZBCFMeqr', output2, quiet=True) print ('Downloading model deviantPixelHD_250000.pth by Raulsangonzalo') gdown.download('https://drive.google.com/uc?id=114yFJKeYCcr6st7aNNo9FJ8wDbEzLpdz', output3, quiet=True) print ('Downloading model SmoothRealism.pth by Joey') gdown.download('https://drive.google.com/uc?id=1Uc9RUc2YpZKpPoGQeGxNUb3Ro-U720cH', output4, quiet=True) print ('Downloading model Manga109Attempt.pth by Kingdomakrillic') gdown.download('https://drive.google.com/uc?id=1avmbwa-5dejkbakWI2WtcpmiRabs-yem', output5, quiet=True) ###Output Downloading pretrained models Downloading model RRDB_ESRGAN_x4.pth Downloading model RRDB_PSNR_x4.pth Downloading model deviantPixelHD_250000.pth by Raulsangonzalo Downloading model SmoothRealism.pth by Joey Downloading model Manga109Attempt.pth by Kingdomakrillic ###Markdown Download more pre-trained models if you want ###Code !pip install requests %cd /content/ESRGAN-old-/models import requests #print ('Downloading model Lady0101.pth by DinJerr') #url = 'https://1drv.ms/u/s!Aip-EMByJHY200rP1TW3aAdb2dkZ?e=enlvAO' #r = requests.get(url, allow_redirects=True) #open('Lady0101.pth', 'wb').write(r.content) print ('Downloading model Fatality.pth by Twittman') url1 = 'https://de-next.owncube.com/index.php/s/gPjswdm6gCegQdz/download' r1 = requests.get(url1, allow_redirects=True) open('Fatality.pth', 'wb').write(r1.content) print ('Downloading model FatalPixels.pth by Twittman') url2 = 'https://de-next.owncube.com/index.php/s/ECsEHxdoYCnFsZA/download' r2 = requests.get(url2, allow_redirects=True) open('FatalPixels.pth', 'wb').write(r2.content) print ('Downloading model Faces.pth by Twittman') url3 = 'https://de-next.owncube.com/index.php/s/YbAqNMMTtxrajF6/download' r3 = requests.get(url2, allow_redirects=True) open('Faces.pth', 'wb').write(r3.content) ###Output Requirement already satisfied: requests in /usr/local/lib/python3.6/dist-packages (2.23.0) Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests) (2020.6.20) Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests) (1.24.3) Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests) (3.0.4) Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests) (2.9) /content/ESRGAN-old-/models Downloading model Fatality.pth by Twittman Downloading model FatalPixels.pth by Twittman Downloading model Faces.pth by Twittman ###Markdown Configure the code and run the cell to upscale images/video frames ###Code #@title Upscale images/video frames %cd /content/ESRGAN-old- import sys import os.path import glob import cv2 import numpy as np import torch import architecture as arch import requests import imageio import requests import warnings warnings.filterwarnings("ignore") from google.colab import files import sys import architecture as arch Choose_device = "cuda" #@param ["cuda","cpu"] model_path = "/content/ESRGAN-old-/models/RRDB_ESRGAN_x4.pth" #@param {type:"string"} device = torch.device(Choose_device) # if you want to run on CPU, change 'cuda' -> cpu test_img_folder = 'LR/*' model = arch.RRDB_Net(3, 3, 64, 23, gc=32, upscale=4, norm_type=None, act_type='leakyrelu', \ mode='CNA', res_scale=1, upsample_mode='upconv') model.load_state_dict(torch.load(model_path), strict=True) model.eval() for k, v in model.named_parameters(): v.requires_grad = False model = model.to(device) print('Model path {:s}. \nTesting...'.format(model_path)) idx = 0 for path in glob.glob(test_img_folder): idx += 1 base = os.path.splitext(os.path.basename(path))[0] print(idx, base) # read image img = cv2.imread(path, cv2.IMREAD_COLOR) img = img * 1.0 / 255 img = torch.from_numpy(np.transpose(img[:, :, [2, 1, 0]], (2, 0, 1))).float() img_LR = img.unsqueeze(0) img_LR = img_LR.to(device) output = model(img_LR).data.squeeze().float().cpu().clamp_(0, 1).numpy() output = np.transpose(output[[2, 1, 0], :, :], (1, 2, 0)) output = (output * 255.0).round() cv2.imwrite('results/{:s}.png'.format(base), output) ###Output /content/ESRGAN-old- Model path /content/ESRGAN-old-/models/RRDB_ESRGAN_x4.pth. Testing... 1 animetest (2) ###Markdown Run this cell to encode your results into a video. ###Code !ffmpeg -f image2 -framerate 25 -i /content/ESRGAN-old-/results/%04d.png -c:v h264_nvenc -preset slow -qp 18 -pix_fmt yuv420p output.mp4 ###Output ffmpeg version 3.4.6-0ubuntu0.18.04.1 Copyright (c) 2000-2019 the FFmpeg developers built with gcc 7 (Ubuntu 7.3.0-16ubuntu3) configuration: --prefix=/usr --extra-version=0ubuntu0.18.04.1 --toolchain=hardened --libdir=/usr/lib/x86_64-linux-gnu --incdir=/usr/include/x86_64-linux-gnu --enable-gpl --disable-stripping --enable-avresample --enable-avisynth --enable-gnutls --enable-ladspa --enable-libass --enable-libbluray --enable-libbs2b --enable-libcaca --enable-libcdio --enable-libflite --enable-libfontconfig --enable-libfreetype --enable-libfribidi --enable-libgme --enable-libgsm --enable-libmp3lame --enable-libmysofa --enable-libopenjpeg --enable-libopenmpt --enable-libopus --enable-libpulse --enable-librubberband --enable-librsvg --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libspeex --enable-libssh --enable-libtheora --enable-libtwolame --enable-libvorbis --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx265 --enable-libxml2 --enable-libxvid --enable-libzmq --enable-libzvbi --enable-omx --enable-openal --enable-opengl --enable-sdl2 --enable-libdc1394 --enable-libdrm --enable-libiec61883 --enable-chromaprint --enable-frei0r --enable-libopencv --enable-libx264 --enable-shared libavutil 55. 78.100 / 55. 78.100 libavcodec 57.107.100 / 57.107.100 libavformat 57. 83.100 / 57. 83.100 libavdevice 57. 10.100 / 57. 10.100 libavfilter 6.107.100 / 6.107.100 libavresample 3. 7. 0 / 3. 7. 0 libswscale 4. 8.100 / 4. 8.100 libswresample 2. 9.100 / 2. 9.100 libpostproc 54. 7.100 / 54. 7.100 Input #0, image2, from '/content/ESRGAN-old-/results/%04d.png': Duration: 00:00:00.04, start: 0.000000, bitrate: N/A Stream #0:0: Video: png, rgb24(pc), 2560x1440, 25 tbr, 25 tbn, 25 tbc Stream mapping: Stream #0:0 -> #0:0 (png (native) -> h264 (h264_nvenc)) Press [q] to stop, [?] for help Output #0, mp4, to 'output.mp4': Metadata: encoder : Lavf57.83.100 Stream #0:0: Video: h264 (h264_nvenc) (Main) (avc1 / 0x31637661), yuv420p, 2560x1440, q=-1--1, 2000 kb/s, 25 fps, 12800 tbn, 25 tbc Metadata: encoder : Lavc57.107.100 h264_nvenc Side data: cpb: bitrate max/min/avg: 0/0/2000000 buffer size: 4000000 vbv_delay: -1 frame= 1 fps=0.0 q=13.0 Lsize= 558kB time=00:00:00.00 bitrate=58565641.0kbits/s speed=0.000276x video:557kB audio:0kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 0.141352% ###Markdown Make a zip file of your results ###Code from google.colab import files !zip -r results.zip /content/ESRGAN-old-/results ###Output adding: content/ESRGAN-old-/results/ (stored 0%) adding: content/ESRGAN-old-/results/animetest.png (deflated 4%) adding: content/ESRGAN-old-/results/baboon_ESRGAN.png (deflated 0%) ###Markdown Download Zip file ###Code files.download('results.zip') import shutil #move zip file to google drive shutil.move("./results.zip", "/content/gdrive/My Drive/results.zip") ###Output _____no_output_____
AWS/Redshift/create-cluster.ipynb
###Markdown Credentials to access AWS (__aws_access_key_id__ and __aws_secret_access_key__) are stored in ~/.aws/credentials under [datalord] profile ###Code session = boto3.Session(profile_name='datalord', region_name='us-east-1') client = session.client('redshift') ###Output _____no_output_____ ###Markdown Update the variables in the cell below. Adjust for your needs. ###Code cluster_identifier = 'datalord-rs-cluster' cluster_roles = [ 'arn:aws:iam::...AccountNumber...:role/DataLord-RH-role', # replace ...AccountNumber... with your real one ] cluster_subnet_group_name = 'datalord-sub-gr' cluster_subnet_group_descr = 'Datalord Redshift Subnet Group' cluster_subnet_ids = [ 'subnet-...SubId...', # replace ...SubId... with your real one ] user_name = 'datalord' user_password = 'Password123' # just a sample. Change it!!! ###Output _____no_output_____ ###Markdown Create Cluster Subnet GroupDocumentation for [create_cluster_subnet_group](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/redshift.htmlRedshift.Client.create_cluster_subnet_group) ###Code response = client.create_cluster_subnet_group( ClusterSubnetGroupName=cluster_subnet_group_name, Description=cluster_subnet_group_descr, SubnetIds=cluster_subnet_ids, ) response['ClusterSubnetGroup'] ###Output _____no_output_____ ###Markdown Create Redshift clusterDocumentation for [create_cluster](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/redshift.htmlRedshift.Client.create_cluster) ###Code response = client.create_cluster( ClusterIdentifier=cluster_identifier, ClusterType='single-node', NodeType='dc2.large', MasterUsername=user_name, MasterUserPassword=user_password, ClusterSubnetGroupName=cluster_subnet_group_name, PubliclyAccessible=True, IamRoles=cluster_roles, ) response['Cluster'] ###Output _____no_output_____ ###Markdown Run the cell if you want to wait until the cluster is provision and available ###Code start_time = time.time() cluster_available_waiter = client.get_waiter('cluster_available') cluster_available_waiter.wait(ClusterIdentifier=cluster_identifier, WaiterConfig={'Delay': 10, 'MaxAttempts': 999} ) print(f'Processing time: {time.time() - start_time} s') ###Output _____no_output_____
04_out_of_stock_detection.ipynb
###Markdown Total sales for all series of aggregation ###Code #export def get_series_df(train_df, rollup_matrix_csr, rollup_index, df_cal=None, fill_xmas=False): """Returns a dataframe with series for all 12 levels of aggregation. We also replace leading zeros with np.nan and if fill_xmas, replace christmas sales with average of the day before and day after christmas""" series_df = pd.DataFrame(data=rollup_matrix_csr * train_df.iloc[:, 6:].values, index=rollup_index, columns=train_df.iloc[:, 6:].columns) zero_mask = series_df.cumsum(axis=1) * 2 == series_df series_df[zero_mask] = np.nan if fill_xmas: xmas_days = df_cal[df_cal.date.str[-5:] == '12-25'].d.str[2:].astype('int16') for x in xmas_days: series_df[f'd_{x}'] = (series_df[f'd_{x-1}'] + series_df[f'd_{x+1}']) / 2 return series_df def get_stats_df(series_df): """Returns a dataframe that shows basic stats for all series in sereis_df.""" percentiles = [.005, .025, .165, .25, .5, .75, .835, .975, .995] stats_df = series_df.T.describe(percentiles).T stats_df['fraction_0'] = ((series_df == 0).sum(axis = 1) / stats_df['count']) return stats_df rollup_matrix_csr, rollup_index = get_agg(df_stv) series_df = get_series_df(df_stv, rollup_matrix_csr, rollup_index, df_cal=df_cal, fill_xmas=True) stats_df = get_stats_df(series_df) w_df = get_df_weights(df_stv, df_cal, df_prices, rollup_index, rollup_matrix_csr, start_test=1914) series_df ###Output _____no_output_____ ###Markdown How many zeros do series have?Lets first take a look at the distribution of the zeros fraction of total sales for the level 12 series. ###Code df = stats_df.loc[12] df.fraction_0.hist(bins=100) plt.title('Distribution of item_id x store_id in terms of proportion zeros') plt.xlabel('Proportion of sales days that have zero sales') plt.ylabel('Count of series') plt.show() df = stats_df.loc[11] df.fraction_0.hist(bins=100) plt.title('Distribution of item_id x state_id in terms of proportion zeros') plt.xlabel('Proportion of sales days that have zero sales') plt.ylabel('Count of series') plt.show() df = stats_df.loc[10] df.fraction_0.hist(bins=100) plt.title('Distribution of item_id aggregated over all stores') plt.xlabel('Proportion of sales days that have zero sales') plt.ylabel('Count of series') plt.show() ###Output _____no_output_____ ###Markdown Plotting item sales for different levels of aggregation ###Code #export def plot_item_series(item, series_df, state=None, fillna=False, start=0, end=1941): """Plots the level 10-12 series containing the item""" item_series_all = series_df.loc[series_df.index.get_level_values(1).str.contains(item)] if state: state_mask = item_series_all.index.get_level_values(1).str.contains(state) if fillna: item_series_all.loc[state_mask].iloc[:, start:end].fillna(fillna).T.plot(title=f'{item} overall in {state} and by store') else: item_series_all.loc[state_mask].iloc[:, start:end].T.plot(title=f'{item} overall in {state} and by store') plt.legend(bbox_to_anchor=(1,1.04), loc='lower right', ncol=1) for i in [1941 - 364*i for i in range(6) if start < 1941 - 364*i <= end]: plt.axvline(i, ls=':') plt.show() else: if fillna: item_series_all.iloc[:4, start:end].fillna(fillna).T.plot(title=f'{item} total and by state') else: item_series_all.iloc[:4, start:end].T.plot(title=f'{item} total and by state') plt.legend(bbox_to_anchor=(.5,.99), loc='upper center', ncol=1) for i in [1941 - 364*i for i in range(6) if start < 1941 - 364*i <= end]: plt.axvline(i, ls=':') plt.show() def plot_all_item_series(item, series_df, fillna=False, start=0, end=1941): plot_item_series(item, series_df, state=None, fillna=fillna, start=start, end=end) for state in ['CA', 'TX', 'WI']: plot_item_series(item, series_df, state=state, fillna=fillna, start=start, end=end) ###Output _____no_output_____ ###Markdown Lets look at the top weighted items and their zero sales streaks over different aggregation levels. We will fill nan values with -20 so they stand out ###Code top_weighted_items = w_df.loc[10].sort_values('weight', ascending=False).index plot_all_item_series(top_weighted_items[0], series_df, fillna=-20) ###Output _____no_output_____ ###Markdown There are definitely streaks of zero sales that do not look natural. I Detecting and marking out-of-stock periods Walkthrough Main functions ###Code def fix_oos(item, series_df): """Processes item and returns series that has np.nan where we think out of stock zeros occur""" item_series = series_df.loc[item].copy() item_mean = np.nanmean(item_series) x = True while x == True: item_series, new_mean, streak_length, item_streaks, limit_99 = nan_zeros(item_series, item_mean) x = new_mean > item_mean item_mean = new_mean return item_series, new_mean, streak_length, item_streaks, limit_99 def nan_zeros(item_series, item_mean): """Returns item_series with streaks replaced by nans, the new average of item series, and max_streak_length, which is the highest streak count that was not replaced with nans.""" # With the mean, we can find the probability # of a zero sales, given the item follows # the poisson distribution prob_0 = np.exp(-item_mean) # Adding this to make sure we catch long streaks that # artificially decrease our starting mean, leading to # an artificially large lowest_prob_allowed = .000_001 lowest_streak_allowed = 1 while prob_0 ** lowest_streak_allowed > lowest_prob_allowed: lowest_streak_allowed += 1 # Given the probability of a zero, we can find # the expected value of the total number of # zeros. expected_zeros = prob_0 * (~np.isnan(item_series)).sum() # Given the number of total zeros should # follow the binomial distribution, approximated # by the normal distribution, we can assume # that total zeros are below mean + 3 standard # deviations 99.85 percent of the time. std = np.sqrt((~np.isnan(item_series)).sum() * prob_0 * (1-prob_0)) limit_99 = expected_zeros + 3 * std item_streaks = mark_streaks(item_series) max_streak_length = 1 total_zeros = (item_streaks == max_streak_length).sum() while (total_zeros < limit_99) & (max_streak_length < lowest_streak_allowed): max_streak_length += 1 total_zeros = (item_streaks == max_streak_length).sum() # Now remove the zeros in streaks greater # than max_streak_length m = min(max_streak_length, lowest_streak_allowed) item_series = np.where(item_streaks > m, np.nan, item_series) new_mean = np.nanmean(item_series) return item_series, new_mean, max_streak_length, item_streaks, limit_99 ###### Mark zeros with length of consecutive zeros ###### # New version thanks to @nadare tip in sibmikes notebook, # where I learned about np.frompyfunc, and how it can # make python functions run really fast. def mark_streaks(ts): """Returns an array of the same length as ts, except positive values are replaced by zero, and zeros are replaced by the lenth of the zero streak to which they belong. ########## Example ############ ### in ### series = np.array([np.nan,3,0,0,0,2,0,0,1,0]) mark_streaks(series) ### out ### array([nan, 0., 3., 3., 3., 0., 2., 2., 0., 1.]) """ ts_nan_mask = np.isnan(ts) zeros = ~(ts > 0) * 1 accum_add_prod = np.frompyfunc(lambda x, y: int((x + y)*y), 2, 1) a = accum_add_prod.accumulate(zeros, dtype=np.object) a = np.where(a==0, 0, np.where(a < np.roll(a, -1), np.nan, a)) a = pd.Series(a).fillna(method='bfill').to_numpy() item_streaks = np.where(ts_nan_mask, np.nan, a) return item_streaks ###Output _____no_output_____ ###Markdown Main command line function ###Code #export @call_parse def make_oos_data(PATH_DATA_RAW: Param('Path to raw data', str)='data/raw', PATH_DATA_INTERIM: Param('Path to interim data', str)='data/interim') -> None: """Creates 2 csv files and stores them in the `PATH_DATA_INTERIM`. The first file is of all time series in the aggregation levels 10, 11, and 12, stored as 'oos_series_df_level_10_11_12.csv'. The second file, 'oos_sales_train_evaluation.csv', has the same format as 'sales_train_evaluation.csv', except zero streaks that are believed to be caused by a stock-out are marked with nan. """ logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s', level=logging.DEBUG, filename='log.log') logging.info('#' * 72) logging.info('#' * 72) logging.info('Using ipca to reduce lag feature dimensions') start_time = time.time() df_stv = pd.read_csv(os.path.join(PATH_DATA_RAW, 'sales_train_evaluation.csv')) df_cal = pd.read_csv(os.path.join(PATH_DATA_RAW, 'calendar.csv')) rollup_matrix_csr, rollup_index = get_agg(df_stv) series_df = get_series_df(df_stv, rollup_matrix_csr, rollup_index, df_cal=df_cal, fill_xmas=True) mask = series_df.index.get_level_values(0) > 9 items = series_df[mask].index new_series = np.array([fix_oos(item, series_df)[0] for item in items]) new_df = pd.DataFrame(new_series, columns=series_df.columns, index=series_df[mask].index) new_df.to_csv(os.path.join(PATH_DATA_INTERIM, 'oos_series_df_level_10_11_12.csv')) df_stv.iloc[:, 6:] = new_df.loc[12].values df_stv.to_csv(os.path.join(PATH_DATA_INTERIM, 'oos_sales_train_evaluation.csv'), index=False) logging.info(72 * '#') logging.info(time_taken(start_time)) make_oos_data(os.path.join(PATH_DATA, 'raw'), os.path.join(PATH_DATA, 'interim')) oos_series_df = pd.read_csv(os.path.join(PATH_DATA, 'interim/oos_series_df_level_10_11_12.csv')).set_index(['level', 'id']) pd.read_csv(os.path.join(PATH_DATA, 'interim/oos_sales_train_evaluation.csv')) ###Output _____no_output_____ ###Markdown Visualizing out of stock periods ###Code plot_all_item_series(top_weighted_items[0], oos_series_df, fillna=-50, start=999) ###Output _____no_output_____
Assignments/003_Kernel_Function_to_fit_non_linearly_separable.ipynb
###Markdown ###Code import numpy as np import matplotlib.pyplot as plt import tqdm # Transfer/Activation Functions def step(x): return x >= 0 class Perceptron: def __init__(self,features=1, alpha=0.1, bias=np.random.normal(loc=0.0,scale=0.01), weights=None, activation=step): if weights is None: self.weights=np.random.normal(loc=0.0, scale=0.01, size=features).transpose() else: self.weights = weights self.activation = activation self.alpha = alpha self.bias=bias self.features = features def __predict(self, inputn): # Private Function # implement prediction of 1 instance if self.features is 1: return self.activation(self.weights*inputn + self.bias)[0] else: return self.activation(self.weights.dot(inputn.transpose()) + self.bias) def cost(self, inputn, outputn ): # Implement the cost function return self.__predict(inputn) - outputn def predict(self, inputs): if self.features is 1: return self.activation(self.weights*(inputs) + self.bias) else: return self.activation(self.weights.dot(inputs.transpose()) + self.bias) def train(self, inputs, outputs, epochs=1): t = tqdm.tqdm(range(epochs)) for epoch in t: for i, inputn in enumerate(inputs): delta = self.__predict(inputn) - outputs[i] t.set_postfix({"loss": delta}) #print(delta, inputn, outputs[i], self.weights, self.bias) self.weight_update(delta, inputn) def weight_update(self, delta, inputs): self.weights = self.weights - self.alpha*delta*(inputs) self.bias = self.bias - self.alpha*delta #print(self.weights, self.bias) ###Output _____no_output_____ ###Markdown Xor Gate is non linearly separable ###Code X = np.array([[0,0], [0,1], [1,0], [1,1] ]) Y=np.array([0,1,1,0]) # Mapping to a 1 D space def kernel_function(x): return (x[0]-x[1])**2 perceptron = Perceptron(features=1) ###Output _____no_output_____ ###Markdown Before Training ###Code x=np.linspace(-0.5, 1.5, 200) xx, yy = np.meshgrid(x, x) roi = np.array([xx.ravel(),yy.ravel()]).T Z = perceptron.predict(kernel_function([roi[:,0], roi[:,1]])) plt.contourf(xx, yy, Z.reshape(xx.shape), levels=1) plt.scatter(X[:,0],X[:,1]) plt.xlim([-0.5,1.5]) plt.ylim([-0.5,1.5]) plt.colorbar(); perceptron.predict(np.array(kernel_function([X[:,0],X[:,1]]))) ###Output _____no_output_____ ###Markdown Training ###Code perceptron.train(kernel_function(np.array([X[:,0], X[:,1]])),Y, epochs=20) x=np.linspace(-0.5, 1.5, 200) xx, yy = np.meshgrid(x, x) roi = np.array([xx.ravel(),yy.ravel()]).T Z = perceptron.predict(kernel_function([roi[:,0], roi[:,1]])) plt.contourf(xx, yy, Z.reshape(xx.shape), levels=1) plt.scatter(X[:,0],X[:,1]) plt.xlim([-0.5,1.5]) plt.ylim([-0.5,1.5]) plt.colorbar(); perceptron.predict(kernel_function(np.array([X[:,0], X[:,1]]))) X ###Output _____no_output_____ ###Markdown XNor Gate is non linearly separable ###Code X = np.array([[0,0], [0,1], [1,0], [1,1] ]) Y=np.array([1,0,0,1]) perceptron = Perceptron(features=1) x=np.linspace(-0.5, 1.5, 200) xx, yy = np.meshgrid(x, x) roi = np.array([xx.ravel(),yy.ravel()]).T Z = perceptron.predict(kernel_function([roi[:,0], roi[:,1]])) plt.contourf(xx, yy, Z.reshape(xx.shape), levels=1) plt.scatter(X[:,0],X[:,1]) plt.xlim([-0.5,1.5]) plt.ylim([-0.5,1.5]) plt.colorbar(); perceptron.predict(kernel_function(np.array([X[:,0], X[:,1]]))) perceptron.train(kernel_function(np.array([X[:,0], X[:,1]])),Y, epochs=20) x=np.linspace(-0.5, 1.5, 200) xx, yy = np.meshgrid(x, x) roi = np.array([xx.ravel(),yy.ravel()]).T Z = perceptron.predict(kernel_function([roi[:,0], roi[:,1]])) plt.contourf(xx, yy, Z.reshape(xx.shape), levels=1) plt.scatter(X[:,0],X[:,1]) plt.xlim([-0.5,1.5]) plt.ylim([-0.5,1.5]) plt.colorbar(); ###Output _____no_output_____