markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Batch normalization: Forward In the file cs231n/layers.py, implement the batch normalization forward pass in the function batchnorm_forward. Once you have done so, run the following to test your implementation.
# Check the training-time forward pass by checking means and variances # of features both before and after batch normalization # Simulate the forward pass for a two-layer network np.random.seed(231) N, D1, D2, D3 = 200, 50, 60, 3 X = np.random.randn(N, D1) W1 = np.random.randn(D1, D2) W2 = np.random.randn(D2, D3) a = np.maximum(0, X.dot(W1)).dot(W2) print('Before batch normalization:') print(' means: ', a.mean(axis=0)) print(' stds: ', a.std(axis=0)) # Means should be close to zero and stds close to one print('After batch normalization (gamma=1, beta=0)') a_norm, _ = batchnorm_forward(a, np.ones(D3), np.zeros(D3), {'mode': 'train'}) print(' mean: ', a_norm.mean(axis=0)) print(' std: ', a_norm.std(axis=0)) # Now means should be close to beta and stds close to gamma gamma = np.asarray([1.0, 2.0, 3.0]) beta = np.asarray([11.0, 12.0, 13.0]) a_norm, _ = batchnorm_forward(a, gamma, beta, {'mode': 'train'}) print('After batch normalization (nontrivial gamma, beta)') print(' means: ', a_norm.mean(axis=0)) print(' stds: ', a_norm.std(axis=0)) # Check the test-time forward pass by running the training-time # forward pass many times to warm up the running averages, and then # checking the means and variances of activations after a test-time # forward pass. np.random.seed(231) N, D1, D2, D3 = 200, 50, 60, 3 W1 = np.random.randn(D1, D2) W2 = np.random.randn(D2, D3) bn_param = {'mode': 'train'} gamma = np.ones(D3) beta = np.zeros(D3) for t in range(50): X = np.random.randn(N, D1) a = np.maximum(0, X.dot(W1)).dot(W2) batchnorm_forward(a, gamma, beta, bn_param) bn_param['mode'] = 'test' X = np.random.randn(N, D1) a = np.maximum(0, X.dot(W1)).dot(W2) a_norm, _ = batchnorm_forward(a, gamma, beta, bn_param) # Means should be close to zero and stds close to one, but will be # noisier than training-time forward passes. print('After batch normalization (test-time):') print(' means: ', a_norm.mean(axis=0)) print(' stds: ', a_norm.std(axis=0))
assignment2/BatchNormalization.ipynb
billzhao1990/CS231n-Spring-2017
mit
Batch Normalization: backward Now implement the backward pass for batch normalization in the function batchnorm_backward. To derive the backward pass you should write out the computation graph for batch normalization and backprop through each of the intermediate nodes. Some intermediates may have multiple outgoing branches; make sure to sum gradients across these branches in the backward pass. Once you have finished, run the following to numerically check your backward pass.
# Gradient check batchnorm backward pass np.random.seed(231) N, D = 4, 5 x = 5 * np.random.randn(N, D) + 12 gamma = np.random.randn(D) beta = np.random.randn(D) dout = np.random.randn(N, D) bn_param = {'mode': 'train'} fx = lambda x: batchnorm_forward(x, gamma, beta, bn_param)[0] fg = lambda a: batchnorm_forward(x, a, beta, bn_param)[0] fb = lambda b: batchnorm_forward(x, gamma, b, bn_param)[0] dx_num = eval_numerical_gradient_array(fx, x, dout) da_num = eval_numerical_gradient_array(fg, gamma.copy(), dout) db_num = eval_numerical_gradient_array(fb, beta.copy(), dout) _, cache = batchnorm_forward(x, gamma, beta, bn_param) dx, dgamma, dbeta = batchnorm_backward(dout, cache) print('dx error: ', rel_error(dx_num, dx)) print('dgamma error: ', rel_error(da_num, dgamma)) print('dbeta error: ', rel_error(db_num, dbeta))
assignment2/BatchNormalization.ipynb
billzhao1990/CS231n-Spring-2017
mit
Batch Normalization: alternative backward (OPTIONAL, +3 points extra credit) In class we talked about two different implementations for the sigmoid backward pass. One strategy is to write out a computation graph composed of simple operations and backprop through all intermediate values. Another strategy is to work out the derivatives on paper. For the sigmoid function, it turns out that you can derive a very simple formula for the backward pass by simplifying gradients on paper. Surprisingly, it turns out that you can also derive a simple expression for the batch normalization backward pass if you work out derivatives on paper and simplify. After doing so, implement the simplified batch normalization backward pass in the function batchnorm_backward_alt and compare the two implementations by running the following. Your two implementations should compute nearly identical results, but the alternative implementation should be a bit faster. NOTE: This part of the assignment is entirely optional, but we will reward 3 points of extra credit if you can complete it.
np.random.seed(231) N, D = 100, 500 x = 5 * np.random.randn(N, D) + 12 gamma = np.random.randn(D) beta = np.random.randn(D) dout = np.random.randn(N, D) bn_param = {'mode': 'train'} out, cache = batchnorm_forward(x, gamma, beta, bn_param) t1 = time.time() dx1, dgamma1, dbeta1 = batchnorm_backward(dout, cache) t2 = time.time() dx2, dgamma2, dbeta2 = batchnorm_backward_alt(dout, cache) t3 = time.time() print('dx difference: ', rel_error(dx1, dx2)) print('dgamma difference: ', rel_error(dgamma1, dgamma2)) print('dbeta difference: ', rel_error(dbeta1, dbeta2)) print('speedup: %.2fx' % ((t2 - t1) / (t3 - t2)))
assignment2/BatchNormalization.ipynb
billzhao1990/CS231n-Spring-2017
mit
Fully Connected Nets with Batch Normalization Now that you have a working implementation for batch normalization, go back to your FullyConnectedNet in the file cs2312n/classifiers/fc_net.py. Modify your implementation to add batch normalization. Concretely, when the flag use_batchnorm is True in the constructor, you should insert a batch normalization layer before each ReLU nonlinearity. The outputs from the last layer of the network should not be normalized. Once you are done, run the following to gradient-check your implementation. HINT: You might find it useful to define an additional helper layer similar to those in the file cs231n/layer_utils.py. If you decide to do so, do it in the file cs231n/classifiers/fc_net.py.
np.random.seed(231) N, D, H1, H2, C = 2, 15, 20, 30, 10 X = np.random.randn(N, D) y = np.random.randint(C, size=(N,)) for reg in [0, 3.14]: print('Running check with reg = ', reg) model = FullyConnectedNet([H1, H2], input_dim=D, num_classes=C, reg=reg, weight_scale=5e-2, dtype=np.float64, use_batchnorm=True) loss, grads = model.loss(X, y) print('Initial loss: ', loss) for name in sorted(grads): f = lambda _: model.loss(X, y)[0] grad_num = eval_numerical_gradient(f, model.params[name], verbose=False, h=1e-5) print('%s relative error: %.2e' % (name, rel_error(grad_num, grads[name]))) if reg == 0: print()
assignment2/BatchNormalization.ipynb
billzhao1990/CS231n-Spring-2017
mit
Batchnorm for deep networks Run the following to train a six-layer network on a subset of 1000 training examples both with and without batch normalization.
np.random.seed(231) # Try training a very deep net with batchnorm hidden_dims = [100, 100, 100, 100, 100] num_train = 1000 small_data = { 'X_train': data['X_train'][:num_train], 'y_train': data['y_train'][:num_train], 'X_val': data['X_val'], 'y_val': data['y_val'], } weight_scale = 2e-2 bn_model = FullyConnectedNet(hidden_dims, weight_scale=weight_scale, use_batchnorm=True) model = FullyConnectedNet(hidden_dims, weight_scale=weight_scale, use_batchnorm=False) bn_solver = Solver(bn_model, small_data, num_epochs=10, batch_size=50, update_rule='adam', optim_config={ 'learning_rate': 1e-3, }, verbose=True, print_every=200) bn_solver.train() solver = Solver(model, small_data, num_epochs=10, batch_size=50, update_rule='adam', optim_config={ 'learning_rate': 1e-3, }, verbose=True, print_every=200) solver.train()
assignment2/BatchNormalization.ipynb
billzhao1990/CS231n-Spring-2017
mit
Run the following to visualize the results from two networks trained above. You should find that using batch normalization helps the network to converge much faster.
plt.subplot(3, 1, 1) plt.title('Training loss') plt.xlabel('Iteration') plt.subplot(3, 1, 2) plt.title('Training accuracy') plt.xlabel('Epoch') plt.subplot(3, 1, 3) plt.title('Validation accuracy') plt.xlabel('Epoch') plt.subplot(3, 1, 1) plt.plot(solver.loss_history, 'o', label='baseline') plt.plot(bn_solver.loss_history, 'o', label='batchnorm') plt.subplot(3, 1, 2) plt.plot(solver.train_acc_history, '-o', label='baseline') plt.plot(bn_solver.train_acc_history, '-o', label='batchnorm') plt.subplot(3, 1, 3) plt.plot(solver.val_acc_history, '-o', label='baseline') plt.plot(bn_solver.val_acc_history, '-o', label='batchnorm') for i in [1, 2, 3]: plt.subplot(3, 1, i) plt.legend(loc='upper center', ncol=4) plt.gcf().set_size_inches(15, 15) plt.show()
assignment2/BatchNormalization.ipynb
billzhao1990/CS231n-Spring-2017
mit
Batch normalization and initialization We will now run a small experiment to study the interaction of batch normalization and weight initialization. The first cell will train 8-layer networks both with and without batch normalization using different scales for weight initialization. The second layer will plot training accuracy, validation set accuracy, and training loss as a function of the weight initialization scale.
np.random.seed(231) # Try training a very deep net with batchnorm hidden_dims = [50, 50, 50, 50, 50, 50, 50] num_train = 1000 small_data = { 'X_train': data['X_train'][:num_train], 'y_train': data['y_train'][:num_train], 'X_val': data['X_val'], 'y_val': data['y_val'], } bn_solvers = {} solvers = {} weight_scales = np.logspace(-4, 0, num=20) for i, weight_scale in enumerate(weight_scales): print('Running weight scale %d / %d' % (i + 1, len(weight_scales))) bn_model = FullyConnectedNet(hidden_dims, weight_scale=weight_scale, use_batchnorm=True) model = FullyConnectedNet(hidden_dims, weight_scale=weight_scale, use_batchnorm=False) bn_solver = Solver(bn_model, small_data, num_epochs=10, batch_size=50, update_rule='adam', optim_config={ 'learning_rate': 1e-3, }, verbose=False, print_every=200) bn_solver.train() bn_solvers[weight_scale] = bn_solver solver = Solver(model, small_data, num_epochs=10, batch_size=50, update_rule='adam', optim_config={ 'learning_rate': 1e-3, }, verbose=False, print_every=200) solver.train() solvers[weight_scale] = solver # Plot results of weight scale experiment best_train_accs, bn_best_train_accs = [], [] best_val_accs, bn_best_val_accs = [], [] final_train_loss, bn_final_train_loss = [], [] for ws in weight_scales: best_train_accs.append(max(solvers[ws].train_acc_history)) bn_best_train_accs.append(max(bn_solvers[ws].train_acc_history)) best_val_accs.append(max(solvers[ws].val_acc_history)) bn_best_val_accs.append(max(bn_solvers[ws].val_acc_history)) final_train_loss.append(np.mean(solvers[ws].loss_history[-100:])) bn_final_train_loss.append(np.mean(bn_solvers[ws].loss_history[-100:])) plt.subplot(3, 1, 1) plt.title('Best val accuracy vs weight initialization scale') plt.xlabel('Weight initialization scale') plt.ylabel('Best val accuracy') plt.semilogx(weight_scales, best_val_accs, '-o', label='baseline') plt.semilogx(weight_scales, bn_best_val_accs, '-o', label='batchnorm') plt.legend(ncol=2, loc='lower right') plt.subplot(3, 1, 2) plt.title('Best train accuracy vs weight initialization scale') plt.xlabel('Weight initialization scale') plt.ylabel('Best training accuracy') plt.semilogx(weight_scales, best_train_accs, '-o', label='baseline') plt.semilogx(weight_scales, bn_best_train_accs, '-o', label='batchnorm') plt.legend() plt.subplot(3, 1, 3) plt.title('Final training loss vs weight initialization scale') plt.xlabel('Weight initialization scale') plt.ylabel('Final training loss') plt.semilogx(weight_scales, final_train_loss, '-o', label='baseline') plt.semilogx(weight_scales, bn_final_train_loss, '-o', label='batchnorm') plt.legend() plt.gca().set_ylim(1.0, 3.5) plt.gcf().set_size_inches(10, 15) plt.show()
assignment2/BatchNormalization.ipynb
billzhao1990/CS231n-Spring-2017
mit
Import required libraries
%matplotlib notebook import matplotlib.pyplot as plt import numpy as np from ipywidgets import widgets from ipywidgets import interact, interactive, fixed from IPython.display import display,HTML,clear_output HTML('''<script>code_show=true;function code_toggle() {if (code_show){$('div.input').hide();} else {$('div.input').show();} code_show = !code_show} $( document ).ready(code_toggle);</script><form action="javascript:code_toggle()"><input type="submit" value="Click here to toggle on/off the raw code."></form>''') from Immune import Add_ons_pMHC import phievo.AnalysisTools as AT from phievo.AnalysisTools.Notebook import Notebook notebook = Notebook() notebook.run_dynamics_pMHC = Add_ons_pMHC.Run_Dynamics_pMHC(notebook) notebook.plot_pMHC = Add_ons_pMHC.Plot_pMHC(notebook) notebook.plot_layout_immune = Add_ons_pMHC.Plot_Layout_Immune(notebook)
Examples/immune/Analyse_pMHC.ipynb
phievo/phievo
lgpl-3.0
Select the Project
notebook.select_project.display()
Examples/immune/Analyse_pMHC.ipynb
phievo/phievo
lgpl-3.0
Select Seed
notebook.select_seed.display()
Examples/immune/Analyse_pMHC.ipynb
phievo/phievo
lgpl-3.0
Plot observable For our immune simulations, the fitness is the mutual information between output concentrations (taken as a probability distribution) and binding time. An ideal fitness is $-1$.
notebook.plot_evolution_observable.display()
Examples/immune/Analyse_pMHC.ipynb
phievo/phievo
lgpl-3.0
Select Generation
notebook.select_generation.display()
Examples/immune/Analyse_pMHC.ipynb
phievo/phievo
lgpl-3.0
PLot Layout The Layout of the network for immune accounts for the new interactions defined. $0$ represents the ligand, $1$ the receptor. They interact to form complex, that can be phosphorylated/dephosphorylated (black arrows, indexed with the corresponding kinase or phosphatase). All other species are either kinases or phosphatastases. Arrows with $1/\tau$ correspond to kinetic proofreading steps.
notebook.plot_layout_immune.display()
Examples/immune/Analyse_pMHC.ipynb
phievo/phievo
lgpl-3.0
Run Dynamics
notebook.run_dynamics_pMHC.display()
Examples/immune/Analyse_pMHC.ipynb
phievo/phievo
lgpl-3.0
Plot Response function The response function for Immune displays the concentration of all species at the end of simulation as a function of the number of ligands presented. The output is the solid line. Left column is for binding time $\tau=3s$, right column for binding time $\tau=10s$. The ideal case such as ``adaptive sorting" corresponds to horizontal lines for the Output, at different levels for different the $\tau$ s
notebook.plot_pMHC.display()
Examples/immune/Analyse_pMHC.ipynb
phievo/phievo
lgpl-3.0
Exam Instructions : Please insert Name and Email address in the first cell of this notebook : Please acknowledge receipt of exam by sending a quick email reply to the instructor : Review the submission form first to scope it out (it will take a 5-10 minutes to input your answers and other information into this form): Exam Submission form : Please keep all your work and responses in ONE (1) notebook only (and submit via the submission form) : Please make sure that the NBViewer link for your Submission notebook works : Please submit your solutions and notebook via the following form: Exam Submission form : For the midterm you will need access to MrJob and Jupyter on your local machines or on AltaScale/AWS to complete some of the questions (like fill in the code to do X). : As for question types: Knowledge test Programmatic/doodle (take photos; embed the photos in your notebook) All programmatic questions can be run locally on your laptop (using MrJob only) or on the cluster : This is an open book exam meaning you can consult webpages and textbooks, class notes, slides etc. but you can not discuss with each other or any other person/group. If any collusion, then this will result in a zero grade and will be grounds for dismissal from the entire program. Please complete this exam by yourself within the time limit. Exam questions begins here ===Map-Reduce=== MT1. Which of the following statememts about map-reduce are true? (I) If you only have 1 computer with 1 computing core, then map-reduce is unlikely to help (II) If we run map-reduce using N single-core computers, then it is likely to get at least an N-Fold speedup compared to using 1 computer (III) Because of network latency and other overhead associated with map-reduce, if we run map-reduce using N computers, then we will get less than N-Fold speedup compared to using 1 computer (IV) When using map-reduce for learning a naive Bayes classifier for SPAM classification, we usually use a single machine that accumulates the partial class and word stats from each of the map machines, in order to compute the final model. Please select one from the following that is most correct: (a) I, II, III, IV (b) I, III, IV (c) I, III (d) I,II, III C ===Order inversion=== MT2. normalized product co-occurrence Suppose you wish to write a MapReduce job that creates normalized product co-occurrence (i.e., pairs of products that have been purchased together) data form a large transaction file of shopping baskets. In addition, we want the relative frequency of coocurring products. Given this scenario, to ensure that all (potentially many) reducers receive appropriate normalization factors (denominators)for a product in the most effcient order in their input streams (so as to minimize memory overhead on the reducer side), the mapper should emit/yield records according to which pattern for the product occurence totals: (a) emit (*,product) count (b) There is no need to use order inversion here (c) emit (product,*) count (d) None of the above A ===Map-Reduce=== MT3. What is the input to the Reduce function in MRJob? Select the most correct choice. (a) An arbitrarily sized list of key/value pairs. (b) One key and a list of some values associated with that key (c) One key and a list of all values associated with that key. (d) None of the above C (Although it is not a list, but a generator) ===Bayesian document classification=== MT4. When building a Bayesian document classifier, Laplace smoothing serves what purpose? (a) It allows you to use your training data as your validation data. (b) It prevents zero-products in the posterior distribution. (c) It accounts for words that were missed by regular expressions. (d) None of the above B MT5. Big Data Big data is defined as the voluminous amount of structured, unstructured or semi-structured data that has huge potential for mining but is so large that it cannot be processed nor stored using traditional (single computer) computing and storage systems. Big data is characterized by its high velocity, volume and variety that requires cost effective and innovative methods for information processing to draw meaningful business insights. More than the volume of the data – it is the nature of the data that defines whether it is considered as Big Data or not. What do the four V’s of Big Data denote? Here is a potential simple explanation for each of the four critical features of big data (some or all of which is correct): Statements * (I) Volume –Scale of data * (II) Velocity – Batch processing of data offline * (III)Variety – Different forms of data * (IV) Veracity –Uncertainty of data Which combination of the above statements is correct. Select a single correct response from the following : (a) I, II, III, IV (b) I, III, IV (c) I, III (d) I,II, III B MT6. Combiners can be integral to the successful utilization of the Hadoop shuffle. Using combiners result in what? (I) minimization of reducer workload (II) minimization of disk storage for mapper results (III) minimization of network traffic (IV) none of the above Select most correct option (i.e., select one option only) from the following: (a) I (b) I, II and III (c) II and III (d) IV B (uncertain) Pairwise similarity using K-L divergence In probability theory and information theory, the Kullback–Leibler divergence (also information divergence, information gain, relative entropy, KLIC, or KL divergence) is a non-symmetric measure of the difference between two probability distributions P and Q. Specifically, the Kullback–Leibler divergence of Q from P, denoted DKL(P\‖Q), is a measure of the information lost when Q is used to approximate P: For discrete probability distributions P and Q, the Kullback–Leibler divergence of Q from P is defined to be + KLDistance(P, Q) = Sum_over_item_i (P(i) log (P(i) / Q(i)) In the extreme cases, the KL Divergence is 1 when P and Q are maximally different and is 0 when the two distributions are exactly the same (follow the same distribution). For more information on K-L Divergence see: + [K-L Divergence](https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence) For the next three question we will use an MRjob class for calculating pairwise similarity using K-L Divergence as the similarity measure: Job 1: create inverted index (assume just two objects) Job 2: calculate/accumulate the similarity of each pair of objects using K-L Divergence Using the following cells then fill in the code for the first reducer to calculate the K-L divergence of objects (letter documents) in line1 and line2, i.e., KLD(Line1||line2). Here we ignore characters which are not alphabetical. And all alphabetical characters are lower-cased in the first mapper. Using the MRJob Class below calculate the KL divergence of the following two string objects.
%%writefile kltext.txt 1.Data Science is an interdisciplinary field about processes and systems to extract knowledge or insights from large volumes of data in various forms (data in various forms, data in various forms, data in various forms), either structured or unstructured,[1][2] which is a continuation of some of the data analysis fields such as statistics, data mining and predictive analytics, as well as Knowledge Discovery in Databases. 2.Machine learning is a subfield of computer science[1] that evolved from the study of pattern recognition and computational learning theory in artificial intelligence.[1] Machine learning explores the study and construction of algorithms that can learn from and make predictions on data.[2] Such algorithms operate by building a model from example inputs in order to make data-driven predictions or decisions,[3]:2 rather than following strictly static program instructions.
exams/MIDS-MidTerm.ipynb
JasonSanchez/w261
mit
MRjob class for calculating pairwise similarity using K-L Divergence as the similarity measure Job 1: create inverted index (assume just two objects) <P> Job 2: calculate the similarity of each pair of objects
import numpy as np np.log(3) !cat kltext.txt %%writefile kldivergence.py # coding: utf-8 from __future__ import division from mrjob.job import MRJob from mrjob.step import MRStep import re import numpy as np class kldivergence(MRJob): # process each string character by character # the relative frequency of each character emitting Pr(character|str) # for input record 1.abcbe # emit "a" [1, 0.2] # emit "b" [1, 0.4] etc... def mapper1(self, _, line): index = int(line.split('.',1)[0]) letter_list = re.sub(r"[^A-Za-z]+", '', line).lower() count = {} for l in letter_list: if count.has_key(l): count[l] += 1 else: count[l] = 1 for key in count: yield key, [index, count[key]*1.0/len(letter_list)] # on a component i calculate (e.g., "b") # Kullback–Leibler divergence of Q from P is defined as (P(i) log (P(i) / Q(i)) def reducer1(self, key, values): p = 0 q = 0 for v in values: if v[0] == 1: #String 1 p = v[1] else: # String 2 q = v[1] if p and q: yield (None, p*np.log(p/q)) #Aggegate components def reducer2(self, key, values): kl_sum = 0 for value in values: kl_sum = kl_sum + value yield "KLDivergence", kl_sum def steps(self): mr_steps = [self.mr(mapper=self.mapper1, reducer=self.reducer1), self.mr(reducer=self.reducer2)] # mr_steps = [MRStep(mapper=self.mapper1, reducer=self.reducer1)] return mr_steps if __name__ == '__main__': kldivergence.run() %reload_ext autoreload %autoreload 2 from mrjob.job import MRJob from kldivergence import kldivergence #dont forget to save kltext.txt (see earlier cell) mr_job = kldivergence(args=['kltext.txt']) with mr_job.make_runner() as runner: runner.run() # stream_output: get access of the output for line in runner.stream_output(): print mr_job.parse_output_line(line)
exams/MIDS-MidTerm.ipynb
JasonSanchez/w261
mit
Questions: MT7. Which number below is the closest to the result you get for KLD(Line1||line2)? (a) 0.7 (b) 0.5 (c) 0.2 (d) 0.1 D MT8. Which of the following letters are missing from these character vectors? (a) p and t (b) k and q (c) j and q (d) j and f
words = """ 1.Data Science is an interdisciplinary field about processes and systems to extract knowledge or insights from large volumes of data in various forms (data in various forms, data in various forms, data in various forms), either structured or unstructured,[1][2] which is a continuation of some of the data analysis fields such as statistics, data mining and predictive analytics, as well as Knowledge Discovery in Databases. 2.Machine learning is a subfield of computer science[1] that evolved from the study of pattern recognition and computational learning theory in artificial intelligence.[1] Machine learning explores the study and construction of algorithms that can learn from and make predictions on data.[2] Such algorithms operate by building a model from example inputs in order to make data-driven predictions or decisions,[3]:2 rather than following strictly static program instructions.""" for char in ['p', 'k', 'f', 'q', 'j']: if char not in words: print char
exams/MIDS-MidTerm.ipynb
JasonSanchez/w261
mit
C
%%writefile kldivergence_smooth.py from __future__ import division from mrjob.job import MRJob import re import numpy as np class kldivergence_smooth(MRJob): # process each string character by character # the relative frequency of each character emitting Pr(character|str) # for input record 1.abcbe # emit "a" [1, (1+1)/(5+24)] # emit "b" [1, (2+1)/(5+24) etc... def mapper1(self, _, line): index = int(line.split('.',1)[0]) letter_list = re.sub(r"[^A-Za-z]+", '', line).lower() count = {} # (ni+1)/(n+24) for l in letter_list: if count.has_key(l): count[l] += 1 else: count[l] = 1 for letter in ['q', 'j']: if letter not in letter_list: count[letter] = 0 for key in count: yield key, [index, (1+count[key]*1.0)/(24+len(letter_list))] def reducer1(self, key, values): p = 0 q = 0 for v in values: if v[0] == 1: p = v[1] else: q = v[1] yield (None, p*np.log(p/q)) # Aggregate components def reducer2(self, key, values): kl_sum = 0 for value in values: kl_sum = kl_sum + value yield "KLDivergence", kl_sum def steps(self): return [self.mr(mapper=self.mapper1, reducer=self.reducer1), self.mr(reducer=self.reducer2) ] if __name__ == '__main__': kldivergence_smooth.run() %reload_ext autoreload %autoreload 2 from kldivergence_smooth import kldivergence_smooth mr_job = kldivergence_smooth(args=['kltext.txt']) with mr_job.make_runner() as runner: runner.run() # stream_output: get access of the output for line in runner.stream_output(): print mr_job.parse_output_line(line)
exams/MIDS-MidTerm.ipynb
JasonSanchez/w261
mit
MT9. The KL divergence on multinomials is defined only when they have nonzero entries. For zero entries, we have to smooth distributions. Suppose we smooth in this way: (ni+1)/(n+24) where ni is the count for letter i and n is the total count of all letters. After smoothing, which number below is the closest to the result you get for KLD(Line1||line2)?? (a) 0.08 (b) 0.71 (c) 0.02 (d) 0.11 A MT10. Block size, and mapper tasks Given ten (10) files in the input directory for a Hadoop Streaming job (MRjob or just Hadoop) with the following filesizes (in megabytes): 1, 2,3,4,5,6,7,8,9,10; and a block size of 5M (NOTE: normally we should set the blocksize to 1 GigB using modern computers). How many map tasks will result from processing the data in the input directory? Select the closest number from the following list. (a) 1 map task (b) 14 (c) 12 (d) None of the above B MT11. Aggregation Given a purchase transaction log file where each purchase transaction contains the customer identifier, item purchased and much more information about the transaction. Which of the following statements are true about a MapReduce job that performs an “aggregation” such as get the number of transaction per customer. Statements * (I) A mapper only job will not suffice, as each map tast only gets to see a subset of the data (e.g., one block). As such a mapper only job will only produce intermediate tallys for each customer. * (II) A reducer only job will suffice and is most efficient computationally * (III) If the developer provides a Mapper and Reducer it can potentially be more efficient than option II * (IV) A reducer only job with a custom partitioner will suffice. Select the most correct option from the following: (a) I, II, III, IV (b) II, IV (c) III, IV (d) III C MT12. Naive Bayes Which of the following statements are true regarding Naive Bayes? Statements * (I) Naive Bayes is a machine learning algorithm that can be used for classifcation problems only * (II) Multinomial Naive Bayes is a flavour of Naive Bayes for discrete input variables and can be combined with Laplace smoothing to avoid zero predictions for class posterior probabilities when attribute value combinations show up during classification but were not present during training. * (III) Naive Bayes can be used for continous valued input variables. In this case, one can use Gaussian distributions to model the class conditional probability distributions Pr(X|Class). * (IV) Naive Bayes can model continous target variables directly. Please select the single most correct combination from the following: (a) I, II, III, IV (b) I, II, III (c) I, III, IV (d) I, II B MT13. Naive Bayes SPAM model Given the following document dataset for a Two-Class problem: ham and spam. Use MRJob (please include your code) to build a muiltnomial Naive Bayes classifier. Please use Laplace Smoothing with a hyperparameter of 1. Please use words only (a-z) as features. Please lowercase all words.
%%writefile spam.txt 0002.2001-05-25.SA_and_HP 0 0 good 0002.2001-05-25.SA_and_HP 0 0 very good 0002.2001-05-25.SA_and_HP 1 0 bad 0002.2001-05-25.SA_and_HP 1 0 very bad 0002.2001-05-25.SA_and_HP 1 0 very bad, very BAD %%writefile spam_test.txt 0002.2001-05-25.SA_and_HP 1 0 good? bad! very Bad! %%writefile NaiveBayes.py import sys import re from mrjob.job import MRJob from mrjob.step import MRStep from mrjob.protocol import TextProtocol, TextValueProtocol # Prevents broken pipe errors from using ... | head from signal import signal, SIGPIPE, SIG_DFL signal(SIGPIPE,SIG_DFL) def sum_hs(counts): h_total, s_total = 0, 0 for h, s in counts: h_total += h s_total += s return (h_total, s_total) class NaiveBayes(MRJob): MRJob.OUTPUT_PROTOCOL = TextValueProtocol def mapper(self, _, lines): _, spam, subject, email = lines.split("\t") words = re.findall(r'[a-z]+', (email.lower()+" "+subject.lower())) if spam == "1": h, s = 0, 1 else: h, s = 1, 0 yield "***Total Emails", (h, s) for word in words: yield word, (h, s) yield "***Total Words", (h, s) def combiner(self, key, count): yield key, sum_hs(count) def reducer_init(self): self.total_ham = 0 self.total_spam = 0 def reducer(self, key, count): ham, spam = sum_hs(count) if key.startswith("***"): if "Words" in key: self.total_ham, self.total_spam = ham, spam elif "Emails" in key: total = ham + spam yield "_", "***Priors\t%.10f\t%.10f" % (ham/total, spam/total) else: pg_ham, pg_spam = ham/self.total_ham, spam/self.total_spam yield "_", "%s\t%.10f\t%.10f" % (key, pg_ham, pg_spam) if __name__ == "__main__": NaiveBayes.run() !cat spam.txt | python NaiveBayes.py --jobconf mapred.reduce.tasks=1 -q | head
exams/MIDS-MidTerm.ipynb
JasonSanchez/w261
mit
QUESTION Having learnt the Naive Bayes text classification model for this problem using the training data and classified the test data (d6) please indicate which of the following is true: Statements * (I) P(very|ham) = 0.33 * (II) P(good|ham) = 0.50 * (I) Posterior Probability P(ham| d6) is approximately 24% * (IV) Class of d6 is ham Please select the single most correct combination of these statements from the following: (a) I, II, III, IV (b) I, II, III (c) I, III, IV (d) I, II C (wild guess) MT14. Is there a map input format (for Hadoop or MRJob)? (a) Yes, but only in Hadoop 0.22+. (b) Yes, in Hadoop there is a default expectation that each record is delimited by an end of line charcacter and that key is the first token delimited by a tab character and that the value-part is everything after the tab character. (c) No, when MRJob INPUT_PROTOCOL = RawValueProtocol. In this case input is processed in format agnostic way thereby avoiding any type of parsing errors. The value is treated as a str, the key is read in as None. (d) Both b and c are correct answers. D MT15. What happens if mapper output does not match reducer input? (a) Hadoop API will convert the data to the type that is needed by the reducer. (b) Data input/output inconsistency cannot occur. A preliminary validation check is executed prior to the full execution of the job to ensure there is consistency. (c) The java compiler will report an error during compilation but the job will complete with exceptions. (d) A real-time exception will be thrown and map-reduce job will fail. D MT16. Why would a developer create a map-reduce without the reduce step? (a) Developers should design Map-Reduce jobs without reducers only if no reduce slots are available on the cluster. (b) Developers should never design Map-Reduce jobs without reducers. An error will occur upon compile. (c) There is a CPU intensive step that occurs between the map and reduce steps. Disabling the reduce step speeds up data processing. (d) It is not possible to create a map-reduce job without at least one reduce step. A developer may decide to limit to one reducer for debugging purposes. C ===Gradient descent=== MT17. Which of the following are true statements with respect to gradient descent for machine learning, where alpha is the learning rate. Select all that apply (I) To make gradient descent converge, we must slowly decrease alpha over time and use a combiner in the context of Hadoop. (II) Gradient descent is guaranteed to find the global minimum for any unconstrained convex objective function J() regardless of using a combiner or not in the context of Hadoop (III) Gradient descent can converge even if alpha is kept fixed. (But alpha cannot be too large, or else it may fail to converge.) Combiners will help speed up the process. (IV) For the specific choice of cost function J() used in linear regression, there is no local optima (other than the global optimum). Select a single correct response from the following: * (a) I, II, III, IV * (b) I, III, IV * (c) II, III * (d) II,III, IV D ===Weighted K-means=== Write a MapReduce job in MRJob to do the training at scale of a weighted K-means algorithm. You can write your own code or you can use most of the code from the following notebook: http://nbviewer.jupyter.org/urls/dl.dropbox.com/s/oppgyfqxphlh69g/MrJobKmeans_Corrected.ipynb Weight each example as follows using the inverse vector length (Euclidean norm): weight(X)= 1/||X||, where ||X|| = SQRT(X.X)= SQRT(X1^2 + X2^2) Here X is vector made up of two component X1 and X2. Using the following data to answer the following TWO questions: https://www.dropbox.com/s/ai1uc3q2ucverly/Kmeandata.csv?dl=0
def inverse_vector_length(x1, x2): norm = (x1**2 + x2**2)**.5 return 1.0/norm inverse_vector_length(1, 5) 0 --> .2 %matplotlib inline import numpy as np import pylab import pandas as pd data = pd.read_csv("Kmeandata.csv", header=None) pylab.plot(data[0], data[1], 'o', linewidth=0, alpha=.5); %%writefile Kmeans.py from numpy import argmin, array, random from mrjob.job import MRJob from mrjob.step import MRStep from itertools import chain import os #Calculate find the nearest centroid for data point def MinDist(datapoint, centroid_points): datapoint = array(datapoint) centroid_points = array(centroid_points) diff = datapoint - centroid_points diffsq = diff*diff # Get the nearest centroid for each instance minidx = argmin(list(diffsq.sum(axis = 1))) return minidx #Check whether centroids converge def stop_criterion(centroid_points_old, centroid_points_new,T): oldvalue = list(chain(*centroid_points_old)) newvalue = list(chain(*centroid_points_new)) Diff = [abs(x-y) for x, y in zip(oldvalue, newvalue)] Flag = True for i in Diff: if(i>T): Flag = False break return Flag class MRKmeans(MRJob): centroid_points=[] k=3 def steps(self): return [ MRStep(mapper_init = self.mapper_init, mapper=self.mapper,combiner = self.combiner,reducer=self.reducer) ] #load centroids info from file def mapper_init(self): # print "Current path:", os.path.dirname(os.path.realpath(__file__)) self.centroid_points = [map(float,s.split('\n')[0].split(',')) for s in open("Centroids.txt").readlines()] #open('Centroids.txt', 'w').close() # print "Centroids: ", self.centroid_points #load data and output the nearest centroid index and data point def mapper(self, _, line): D = (map(float,line.split(','))) yield int(MinDist(D, self.centroid_points)), (D[0],D[1],1) #Combine sum of data points locally def combiner(self, idx, inputdata): sumx = sumy = num = 0 for x,y,n in inputdata: num = num + n sumx = sumx + x sumy = sumy + y yield idx,(sumx,sumy,num) #Aggregate sum for each cluster and then calculate the new centroids def reducer(self, idx, inputdata): centroids = [] num = [0]*self.k for i in range(self.k): centroids.append([0,0]) for x, y, n in inputdata: num[idx] = num[idx] + n centroids[idx][0] = centroids[idx][0] + x centroids[idx][1] = centroids[idx][1] + y centroids[idx][0] = centroids[idx][0]/num[idx] centroids[idx][1] = centroids[idx][1]/num[idx] yield idx,(centroids[idx][0],centroids[idx][1]) if __name__ == '__main__': MRKmeans.run() %reload_ext autoreload %autoreload 2 from numpy import random from Kmeans import MRKmeans, stop_criterion mr_job = MRKmeans(args=['Kmeandata.csv', '--file=Centroids.txt']) #Geneate initial centroids centroid_points = [] k = 3 for i in range(k): centroid_points.append([random.uniform(-3,3),random.uniform(-3,3)]) with open('Centroids.txt', 'w+') as f: f.writelines(','.join(str(j) for j in i) + '\n' for i in centroid_points) # Update centroids iteratively i = 0 while(1): # save previous centoids to check convergency centroid_points_old = centroid_points[:] print "iteration"+str(i)+":" with mr_job.make_runner() as runner: runner.run() # stream_output: get access of the output for line in runner.stream_output(): key,value = mr_job.parse_output_line(line) print key, value centroid_points[key] = value # Update the centroids for the next iteration with open('Centroids.txt', 'w') as f: f.writelines(','.join(str(j) for j in i) + '\n' for i in centroid_points) print "\n" i = i + 1 if(stop_criterion(centroid_points_old,centroid_points,0.01)): break print "Centroids\n" print centroid_points pylab.plot(data[0], data[1], 'o', linewidth=0, alpha=.5); for point in centroid_points: pylab.plot(point[0], point[1], '*',color='pink',markersize=20) for point in [(-4.5,0.0), (4.5,0.0), (0.0,4.5)]: pylab.plot(point[0], point[1], '*',color='red',markersize=20) pylab.show()
exams/MIDS-MidTerm.ipynb
JasonSanchez/w261
mit
tokenize using nltk.tokenize.treebank.TreebankWordTokenizer
from nltk.tokenize.treebank import TreebankWordTokenizer tokenizer = TreebankWordTokenizer() tokenizer.tokenize("""that its money would be better spent "in areas such as research" and development.""") import re ENDS_WITH_COMMA = re.compile('(.*),$') ENDS_WITH_PUNCTUATION = re.compile('(.*)(,|.|!|:|;)$') foo = "Cummins Engine Co. , Columbus , Ind.," bar = ENDS_WITH_COMMA.sub(r'\1 ,', foo) BRACKETS = { '(': '-LRB-', # round brackets ')': '-RRB-', '[': '-LSB-', # square brackets ']': '-RSB-', '{': '-LCB-', # curly brackets '}': '-RCB-' } def fix_tokenized_sentence(tokenized_sentence): # If an EDU ends with a comma, we'll have to tokenize it, # e.g. "when it ends," -> "when it ends ," tokenized_sentence[-1] = ENDS_WITH_PUNCTUATION.sub(r'\1 \2', tokenized_sentence[-1]) for i, token in enumerate(tokenized_sentence): if token in BRACKETS: tokenized_sentence[i] = BRACKETS[token] return tokenized_sentence ENDS_WITH_PUNCTUATION = re.compile('(.*)(,|\.|!|:|;)$') ENDS_WITH_PUNCTUATION.match(foo).groups() from nltk.tokenize.treebank import TreebankWordTokenizer from nltk.tokenize import sent_tokenize TOKENIZER = TreebankWordTokenizer() def tokenize_rst_file_with_nltk(rst_input_path, rst_output_path, tokenizer): # edus = {} with open(rst_input_path, 'r') as rstfile, codecs.open(rst_output_path, 'w', encoding='utf-8') as outfile: rstfile_str = rstfile.read() input_file_onset = 0 edu_matches = RST_DIS_TEXT_REGEX.finditer(rstfile_str) for edu in edu_matches: doc_onset = edu.start() doc_offset = edu.end() doc_untokenized_str = edu.groups()[0] untokenized_sents = sent_tokenize(doc_untokenized_str) tokenized_sents = tokenizer.tokenize_sents(untokenized_sents) fixed_tokenized_sents = [fix_tokenized_sentence(sent) for sent in tokenized_sents] tokenized_str = u' '.join(tok for sent in fixed_tokenized_sents for tok in sent) outfile.write(rstfile_str[input_file_onset:doc_onset]) outfile.write(u'"{}"'.format(tokenized_str)) input_file_onset = doc_offset outfile.write(rstfile_str[input_file_onset:]) %%time RSTDT_NLTK_TOKENIZED_ROOT = os.path.expanduser('~/repos/rst_discourse_treebank/data/RSTtrees-WSJ-main-1.0-nltk-tokenized') for folder in ('TEST', 'TRAINING'): for rst_fpath in glob.glob(os.path.join(RSTDT_MAIN_ROOT, folder, '*.dis')): out_fpath = os.path.join(RSTDT_NLTK_TOKENIZED_ROOT, folder, os.path.basename(rst_fpath)) out_dir, _fname = os.path.split(out_fpath) dg.util.create_dir(out_dir) tokenize_rst_file_with_nltk(rst_fpath, out_fpath, TOKENIZER) TOKENIZER.tokenize("on Monday the small ( investors ) are going to panic and sell")
python/rstdt-batch-tokenization.ipynb
arne-cl/alt-mulig
gpl-3.0
The Treebank tokenizer uses regular expressions to tokenize text as in Penn Treebank. This is the method that is invoked by word_tokenize(). It assumes that the text has already been segmented into sentences, e.g. using sent_tokenize().
from nltk.tokenize import sent_tokenize sents = sent_tokenize("a tree. You are a ball.") tokenized_sents = TOKENIZER.tokenize_sents(sents) u' '.join(tok for sent in tokenized_sents for tok in sent)
python/rstdt-batch-tokenization.ipynb
arne-cl/alt-mulig
gpl-3.0
Edge ML with TensorFlow Lite In this notebook, we convert the saved model into a TensorFlow Lite model so that we can run it on Edge devices. In order to do edge inference, we need to handle raw image data from the camera and process a single image (not a batch of images).
import tensorflow as tf import os, shutil MODEL_LOCATION='export/flowers_model3' # will be created # load from checkpoint and export a model that has desired signature CHECK_POINT_DIR='gs://practical-ml-vision-book/flowers_5_trained/chkpts' model = tf.keras.models.load_model(CHECK_POINT_DIR) IMG_HEIGHT = 345 IMG_WIDTH = 345 IMG_CHANNELS = 3 CLASS_NAMES = 'daisy dandelion roses sunflowers tulips'.split() # a single image of any size @tf.function(input_signature=[tf.TensorSpec([None, None, 3], dtype=tf.float32)]) def predict_flower_type(img): img = tf.image.resize_with_pad(img, IMG_HEIGHT, IMG_WIDTH) batch_pred = model(tf.expand_dims(img, axis=0)) top_prob = tf.math.reduce_max(batch_pred, axis=[1]) pred_label_index = tf.math.argmax(batch_pred, axis=1) pred_label = tf.gather(tf.convert_to_tensor(CLASS_NAMES), pred_label_index) return { 'probability': tf.squeeze(top_prob, axis=0), 'flower_type': tf.squeeze(pred_label, axis=0) } shutil.rmtree('export', ignore_errors=True) os.mkdir('export') model.save(MODEL_LOCATION, signatures={ 'serving_default': predict_flower_type })
09_deploying/09e_tflite.ipynb
GoogleCloudPlatform/practical-ml-vision-book
apache-2.0
Convert to TFLite This will take a while to do the conversion
import tensorflow as tf converter = tf.lite.TFLiteConverter.from_saved_model(MODEL_LOCATION) tflite_model = converter.convert() with open('export/model.tflite', 'wb') as ofp: ofp.write(tflite_model) !ls -lh export/model.tflite
09_deploying/09e_tflite.ipynb
GoogleCloudPlatform/practical-ml-vision-book
apache-2.0
The Space Shuttle problem Here's a problem from Bayesian Methods for Hackers On January 28, 1986, the twenty-fifth flight of the U.S. space shuttle program ended in disaster when one of the rocket boosters of the Shuttle Challenger exploded shortly after lift-off, killing all seven crew members. The presidential commission on the accident concluded that it was caused by the failure of an O-ring in a field joint on the rocket booster, and that this failure was due to a faulty design that made the O-ring unacceptably sensitive to a number of factors including outside temperature. Of the previous 24 flights, data were available on failures of O-rings on 23, (one was lost at sea), and these data were discussed on the evening preceding the Challenger launch, but unfortunately only the data corresponding to the 7 flights on which there was a damage incident were considered important and these were thought to show no obvious trend. The data are shown below (see 1):
# !wget https://raw.githubusercontent.com/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/master/Chapter2_MorePyMC/data/challenger_data.csv columns = ['Date', 'Temperature', 'Incident'] df = pd.read_csv('challenger_data.csv', parse_dates=[0]) df.drop(labels=[3, 24], inplace=True) df df['Incident'] = df['Damage Incident'].astype(float) df import matplotlib.pyplot as plt plt.scatter(df.Temperature, df.Incident, s=75, color="k", alpha=0.5) plt.yticks([0, 1]) plt.ylabel("Damage Incident?") plt.xlabel("Outside temperature (Fahrenheit)") plt.title("Defects of the Space Shuttle O-Rings vs temperature");
examples/shuttle_soln.ipynb
AllenDowney/ThinkBayes2
mit
Grid algorithm We can solve the problem first using a grid algorithm, with parameters b0 and b1, and $\mathrm{logit}(p) = b0 + b1 * T$ and each datum being a temperature T and a boolean outcome fail, which is true is there was damage and false otherwise. Hint: the expit function from scipy.special computes the inverse of the logit function.
from scipy.special import expit class Logistic(Suite, Joint): def Likelihood(self, data, hypo): """ data: T, fail hypo: b0, b1 """ return 1 # Solution from scipy.special import expit class Logistic(Suite, Joint): def Likelihood(self, data, hypo): """ data: T, fail hypo: b0, b1 """ temp, fail = data b0, b1 = hypo log_odds = b0 + b1 * temp p_fail = expit(log_odds) if fail == 1: return p_fail elif fail == 0: return 1-p_fail else: # NaN return 1 b0 = np.linspace(0, 50, 101); b1 = np.linspace(-1, 1, 101); from itertools import product hypos = product(b0, b1) suite = Logistic(hypos); for data in zip(df.Temperature, df.Incident): print(data) suite.Update(data) thinkplot.Pdf(suite.Marginal(0)) thinkplot.decorate(xlabel='Intercept', ylabel='PMF', title='Posterior marginal distribution') thinkplot.Pdf(suite.Marginal(1)) thinkplot.decorate(xlabel='Log odds ratio', ylabel='PMF', title='Posterior marginal distribution')
examples/shuttle_soln.ipynb
AllenDowney/ThinkBayes2
mit
According to the posterior distribution, what was the probability of damage when the shuttle launched at 31 degF?
# Solution T = 31 total = 0 for hypo, p in suite.Items(): b0, b1 = hypo log_odds = b0 + b1 * T p_fail = expit(log_odds) total += p * p_fail total # Solution pred = suite.Copy() pred.Update((31, True))
examples/shuttle_soln.ipynb
AllenDowney/ThinkBayes2
mit
MCMC Implement this model using MCMC. As a starting place, you can use this example from the PyMC3 docs. As a challege, try writing the model more explicitly, rather than using the GLM module.
from warnings import simplefilter simplefilter('ignore', FutureWarning) import pymc3 as pm # Solution with pm.Model() as model: pm.glm.GLM.from_formula('Incident ~ Temperature', df, family=pm.glm.families.Binomial()) start = pm.find_MAP() trace = pm.sample(1000, start=start, tune=1000) pm.traceplot(trace); # Solution with pm.Model() as model: pm.glm.GLM.from_formula('Incident ~ Temperature', df, family=pm.glm.families.Binomial()) trace = pm.sample(1000, tune=1000)
examples/shuttle_soln.ipynb
AllenDowney/ThinkBayes2
mit
Step1: build the initial state of the entire user network, as well as the purchae history of the users Input: sample_dataset/batch_log.json
batchlogfile = 'sample_dataset/batch_log.json' df_batch = pd.read_json(batchlogfile, lines=True) index_purchase = ['event_type','id','timestamp','amount'] index_friend = ['event_type','id1','id2','timestamp'] #df_batch.head() #df_batch.describe() # Read D and T df_DT=df_batch[df_batch['D'].notnull()] df_DT=df_DT[['D','T']] D = df_DT.values[0][0] T = df_DT.values[0][1] #print(D) #print(T) #df_DT.head() # check D and T values if D < 1: print('Program terminated because of D < 1') sys.exit() if T < 2: print('Program terminated because of T < 2') sys.exit() #for possible_value in set(df['event_type'].tolist()): # print(possible_value) df_purchase = df_batch[df_batch['event_type']=='purchase'] df_purchase = df_purchase[index_purchase] df_purchase = df_purchase.dropna(how='any') # If sort on the timestamp is needed, commentout the following line # df_purchase = df_purchase.sort_values('timestamp') #df_purchase.shape df_friend=df_batch[(df_batch['event_type']=='befriend') | (df_batch['event_type']=='unfriend')] df_friend=df_friend[index_friend] df_friend=df_friend.dropna(how='any') # If sort on the timestamp is needed, commentout the following line #df_friend=df_friend.sort_values('timestamp') #df_friend.shape G = nx.Graph() idlist = set(df_purchase.id.tolist()) G.add_nodes_from(idlist) #len(list(G.nodes())) def Add_edges(data): for row in data.itertuples(): id10 = row.id1 id20 = row.id2 event_type0 = row.event_type if event_type0 == 'befriend': G.add_edge(id10,id20) if event_type0 == 'unfriend': if G.has_edge(id10,id20): G.remove_edge(id10,id20) Add_edges(df_friend) #len(list(G.edges())) #G[10.0] #G.number_of_nodes() #G.number_of_edges() # define a function to calcualte the mean and sd for userid's network def Get_Mean_SD(userid): Nodes = list(nx.ego_graph(G, userid, D, center=False)) df_Nodes = df_purchase.loc[df_purchase['id'].isin(Nodes)] if len(df_Nodes) >= 2: if len(df_Nodes) > T: df_Nodes = df_Nodes.sort_values('timestamp').iloc[-int(T):] #df_Nodes.shape #the std from pd is different from np; np is correct #mean = df_Nodes.amount.mean() #sd = df_Nodes.amount.std() mean = np.mean(df_Nodes['amount']) sd = np.std(df_Nodes['amount']) mean = float("{0:.2f}".format(mean)) sd = float("{0:.2f}".format(sd)) else: mean=np.nan sd=np.nan return mean, sd #Get_Mean_SD(0.0) #df_purchase.head() #df_purchase.tail() #df_purchase.shape
anomaly_detection.ipynb
xiaodongpang23/anomaly_detection
mit
Step2: Determine whether a purchase is anomalous input file: sample_dataset/stream_log.json
# read in the stream_log.json streamlogfile = 'sample_dataset/stream_log.json' df_stream = pd.read_json(streamlogfile, lines=True) # If sort on the timestamp is needed, commentout the following line #df_stream = df_stream.sort_values('timestamp') # open output file flagged_purchases.json flaggedfile = 'log_output/flagged_purchases.json' f = open(flaggedfile, 'w') # Determine whether a purchase is anomalous; update purchase history; update social network for i in range(0, len(df_stream)): datai = df_stream.iloc[i] event_type = datai['event_type'] if (event_type == 'purchase') & (not datai[index_purchase].isnull().any()): # update purchase history df_purchase = df_purchase.append(datai[index_purchase]) timestamp = datai['timestamp'] timestamp = str(timestamp) userid = datai['id'] if (not G.has_node(userid)): G.add_node(userid) amount = datai['amount'] mean, sd = Get_Mean_SD(userid) if mean != np.nan: mean_3sd = mean + (3*sd) if amount > mean_3sd: f.write('{{"event_type":"{0:s}", "timestamp":"{1:s}", "id": "{2:.0f}", "amount": "{3:.2f}", "mean": "{4:.2f}", "sd": "{5:.2f}"}}\n'.format(event_type, timestamp, userid, amount, mean, sd)) # update social network if (event_type == 'befriend') & (not datai[index_friend].isnull().any()): df_friend=df_friend.append(datai[index_friend]) id1 = datai['id1'] id2 = datai['id2'] G.add_edge(id1,id2) if (event_type == 'unfriend') & (not datai[index_friend].isnull().any()): df_friend=df_friend.append(datai[index_friend]) id1 = datai['id1'] id2 = datai['id2'] if G.has_edge(id1,id2): G.remove_edge(id1,id2) f.close()
anomaly_detection.ipynb
xiaodongpang23/anomaly_detection
mit
We will also load the other packages we will use in this demo. This could be done before the above import.
import numpy as np import matplotlib import matplotlib.pyplot as plt %matplotlib inline
demos/sparse/sparse_lin_inverse.ipynb
GAMPTeam/vampyre
mit
Generating Synthetic Data We begin by generating synthetic data $z$ and measurements $y$ that we will use to test the algorithms. First, we set the dimensions and the shapes of the vectors we will use.
# Parameters nz = 1000 # number of components of z ny = 500 # number of measurements y # Compute the shapes zshape = (nz,) # Shape of z matrix yshape = (ny,) # Shape of y matrix Ashape = (ny,nz) # Shape of A matrix
demos/sparse/sparse_lin_inverse.ipynb
GAMPTeam/vampyre
mit
To generate the synthetic data for this demo, we use the following simple probabilistic model. For the input $z$, we will use Bernouli-Gaussian (BG) distribution, a simple model in sparse signal processing. In the BG model, the components $z_i$ are i.i.d. where each component $z_i=0$ with probability $1-\rho$ and $z_i \sim {\mathcal N}(0,1)$ with probability $\rho$. The parameter $\rho$ is called the sparsity ratio and represents the average number of non-zero components. When $\rho$ is small, the vector $z$ is sparse. The components on which $z_i$ are non-zero are called the active components. We set the parameters below. We also set the SNR for the measurements.
sparse_rat = 0.1 # sparsity ratio zmean1 = 0 # mean for the active components zvar1 = 1 # variance for the active components snr = 30 # SNR in dB
demos/sparse/sparse_lin_inverse.ipynb
GAMPTeam/vampyre
mit
Using these parameters, we can generate random sparse z following this distribution with the following simple code.
# Generate the random input z1 = np.random.normal(zmean1, np.sqrt(zvar1), zshape) u = np.random.uniform(0, 1, zshape) < sparse_rat z = z1*u
demos/sparse/sparse_lin_inverse.ipynb
GAMPTeam/vampyre
mit
To illustrate the sparsity, we plot the vector z. We can see from this plot that the majority of the components of z are zero.
ind = np.array(range(nz)) plt.plot(ind,z)
demos/sparse/sparse_lin_inverse.ipynb
GAMPTeam/vampyre
mit
Now, we create a random transform $A$ and output $y_0 = Az$.
A = np.random.normal(0, 1/np.sqrt(nz), Ashape) y0 = A.dot(z)
demos/sparse/sparse_lin_inverse.ipynb
GAMPTeam/vampyre
mit
Finally, we add noise at the desired SNR
yvar = np.mean(np.abs(y0)**2) wvar = yvar*np.power(10, -0.1*snr) y = y0 + np.random.normal(0,np.sqrt(wvar), yshape)
demos/sparse/sparse_lin_inverse.ipynb
GAMPTeam/vampyre
mit
Creating the Vampyre estimators Now that we have created the sparse data, we will use the vampyre package to recover z from y. In vampyre the methods to perform this estimation are called solvers. For this demo, we will use a simple solver called VAMP described in the paper: Rangan, Sundeep, Philip Schniter, and Alyson Fletcher. "Vector approximate message passing." arXiv preprint arXiv:1610.03082 (2016). Similar to most of the solvers in the vampyre package, the VAMP solver needs precise specifications of the probability distributions of z and y. The simplest way to use VAMP is to specify two densities: * The prior $p(z)$; and * The likelihood $p(y|z)$. Each of the densities are described by estimators. We first describe the estimator for the prior $p(z)$. The vampyre package will eventually have a large number of estimators to describe various densities. In this simple demo, $p(z)$ is what is called a mixture distribution since $z$ is one distribution with probability $1-\rho$ and a second distribution with probability $\rho$. To describe this mixture distribution in the vampyre package, we need to first create estimator classes for each component distribution. The following code creates an estimator, est0, for a discrete distribution with a probability of 1 at a 0 and a second estimator, est1, for the Gaussian distribution with the active components.
est0 = vp.estim.DiscreteEst(0,1,zshape) est1 = vp.estim.GaussEst(zmean1,zvar1,zshape)
demos/sparse/sparse_lin_inverse.ipynb
GAMPTeam/vampyre
mit
We next use the vampyre class, MixEst, to describe a mixture of the two distributions. This is done by creating a list, est_list, of the estimators and an array pz with the probability of each component. The resulting estimator, est_in, is the estimator for the prior $z$, which is also the input to the transform $A$. We give this a name Input since it corresponds to the input. But, any naming is fine. Or, you can let vampyre give it a generic name.
est_list = [est0, est1] pz = np.array([1-sparse_rat, sparse_rat]) est_in = vp.estim.MixEst(est_list, w=pz, name='Input')
demos/sparse/sparse_lin_inverse.ipynb
GAMPTeam/vampyre
mit
Next, we describe the likelihood function, $p(y|z)$. Since $y=Az+w$, we can first use the MatrixLT class to define a linear transform operator Aop corresponding to the matrix A. Then, we use the LinEstim class to describe the likelihood $y=Az+w$.
Aop = vp.trans.MatrixLT(A,zshape) est_out = vp.estim.LinEst(Aop,y,wvar,map_est=False, name='Output')
demos/sparse/sparse_lin_inverse.ipynb
GAMPTeam/vampyre
mit
Finally, the VAMP method needs a message handler to describe how to perform the Gaussian message passing. This is a more advanced feature. For most applications, you can just use the simple message handler as follows.
msg_hdl = vp.estim.MsgHdlSimp(map_est=False, shape=zshape)
demos/sparse/sparse_lin_inverse.ipynb
GAMPTeam/vampyre
mit
Running the VAMP Solver Having described the input and output estimators and the variance handler, we can now construct a VAMP solver. The construtor takes the input and output estimators, the variance handler and other parameters. The paramter nit is the number of iterations. This is fixed for now. Later, we will add auto-termination. The other parameter, hist_list is optional, and will be described momentarily.
nit = 20 # number of iterations solver = vp.solver.Vamp(est_in,est_out,msg_hdl,\ hist_list=['zhat', 'zhatvar'],nit=nit)
demos/sparse/sparse_lin_inverse.ipynb
GAMPTeam/vampyre
mit
We can print a summary of the model which indicates the dimensions and the estimators.
solver.summary()
demos/sparse/sparse_lin_inverse.ipynb
GAMPTeam/vampyre
mit
We now run the solver by calling the solve() method. For a small problem like this, this should be close to instantaneous.
solver.solve()
demos/sparse/sparse_lin_inverse.ipynb
GAMPTeam/vampyre
mit
The VAMP solver estimate is the field zhat. We plot one column of this (icol=0) and compare it to the corresponding column of the true matrix z. You should see a very good match.
zhat = solver.zhat ind = np.array(range(nz)) plt.plot(ind,z) plt.plot(ind,zhat) plt.legend(['True', 'Estimate'])
demos/sparse/sparse_lin_inverse.ipynb
GAMPTeam/vampyre
mit
We can measure the normalized mean squared error as follows. The VAMP solver also produces an estimate of the MSE in the variable zhatvar. We can extract this variable to compute the predicted MSE. We see that the normalized MSE is indeed low and closely matches the predicted value from VAMP.
zerr = np.mean(np.abs(zhat-z)**2) zhatvar = solver.zhatvar zpow = np.mean(np.abs(z)**2) mse_act = 10*np.log10(zerr/zpow) mse_pred = 10*np.log10(zhatvar/zpow) print("Normalized MSE (dB): actual {0:f} pred {1:f}".format(mse_act, mse_pred))
demos/sparse/sparse_lin_inverse.ipynb
GAMPTeam/vampyre
mit
Finally, we can plot the actual and predicted MSE as a function of the iteration number. When solver was contructed, we passed an argument hist_list=['zhat', 'zhatvar']. This indicated to store the value of the estimate zhat and predicted error variance zhatvar with each iteration. We can recover these values from solver.hist_dict, the history dictionary. Using the values we can compute and plot the normalized MSE on each iteartion. We see that VAMP gets a low MSE in very few iterations, about 10.
# Compute the MSE as a function of the iteration zhat_hist = solver.hist_dict['zhat'] zhatvar_hist = solver.hist_dict['zhatvar'] nit = len(zhat_hist) mse_act = np.zeros(nit) mse_pred = np.zeros(nit) for it in range(nit): zerr = np.mean(np.abs(zhat_hist[it]-z)**2) mse_act[it] = 10*np.log10(zerr/zpow) mse_pred[it] = 10*np.log10(zhatvar_hist[it]/zpow) plt.plot(range(nit), mse_act, 'o-', linewidth=2) plt.plot(range(nit), mse_pred, 's', linewidth=1) plt.xlabel('Iteration') plt.ylabel('Normalized MSE (dB)') plt.legend(['Actual', 'Predicted']) plt.grid()
demos/sparse/sparse_lin_inverse.ipynb
GAMPTeam/vampyre
mit
Step 2: Concatenate Barcodes for QIIME2 Pipeline
## Note: QIIME takes a single barcode file. The command 'extract_barcodes.py' concatenates the forward and reverse read barcode and attributes it to a single read. # See http://qiime.org/tutorials/processing_illumina_data.html for dataset in datasets: directory = dataset[1] index1 = directory+indexFile1 index2 = directory+indexFile2 # Run extract_barcodes to merge the two index files !python2 /opt/anaconda2/bin/extract_barcodes.py --input_type barcode_paired_end -f $index1 -r $index2 --bc1_len 8 --bc2_len 8 -o $directory/output # QIIME2 import requires a directory containing files names: forward.fastq.gz, reverse.fastq.gz and barcodes.fastq.gz !ln -s $directory$readFile1 $directory/output/forward.fastq.gz !ln -s $directory$readFile2 $directory/output/reverse.fastq.gz # Gzip the barcodes files (apparently necessary) !pigz -p 5 $directory/output/barcodes.fastq # Removed orphaned reads files (not needed) !rm $directory/output/reads?.fastq
sequence_analysis_walkthrough/QIIME2_Processing_Pipeline.ipynb
buckleylab/Buckley_Lab_SIP_project_protocols
mit
Step 3: Import into QIIME2
for dataset in datasets: name = dataset[0] directory = dataset[1] os.system(' '.join([ "qiime tools import", "--type EMPPairedEndSequences", "--input-path "+directory+"output/", "--output-path "+directory+"output/"+name+".qza" ])) # This more direct command is broken by the fact QIIME uses multiple dashes in their arguments (is my theory) #!qiime tools import --type EMPPairedEndSequences --input-path $directory/output --output-path $directory/output/$name.qza
sequence_analysis_walkthrough/QIIME2_Processing_Pipeline.ipynb
buckleylab/Buckley_Lab_SIP_project_protocols
mit
Step 4: Demultiplex
######## ## Note: The barcode you supply to QIIME is now a concatenation of your forward and reverse barcode. # Your 'forward' barcode is actually the reverse complement of your reverse barcode and the 'reverse' is your forward barcode. The file 'primers.complete.csv' provides this information corresponding to the Buckley Lab 'primer number' # This quirk could be corrected in how different sequencing facilities pre-process the output from the sequencer ## ## SLOW STEP (~ 2 - 4 hrs) ## for dataset in datasets: name = dataset[0] directory = dataset[1] metadata = dataset[2] os.system(' '.join([ "qiime demux emp-paired", "--m-barcodes-file "+directory+metadata, "--m-barcodes-category BarcodeSequence", "--i-seqs "+directory+"output/"+name+".qza", "--o-per-sample-sequences "+directory+"output/"+name+".demux" ])) # This more direct command is broken by the fact QIIME uses multiple dashes in their arguments (is my theory) #!qiime demux emp-paired --m-barcodes-file $directory/$metadata --m-barcodes-category BarcodeSequence --i-seqs $directory/output/$name.qza --o-per-sample-sequences $directory/output/$name.demux
sequence_analysis_walkthrough/QIIME2_Processing_Pipeline.ipynb
buckleylab/Buckley_Lab_SIP_project_protocols
mit
Step 5: Visualize Quality Scores and Determine Trimming Parameters
## Based on the Graph Produced using the Following Command enter the trim and truncate values. Trim refers to the start of a sequence and truncate the total length (i.e. number of bases to remove from end) # The example in the Atacam Desert Tutorial trims 13 bp from the start of each read and does not remove any bases from the end of the 150 bp reads: # --p-trim-left-f 13 \ # --p-trim-left-r 13 \ # --p-trunc-len-f 150 \ # --p-trunc-len-r 150 for dataset in datasets: name = dataset[0] directory = dataset[1] os.system(' '.join([ "qiime demux summarize", "--i-data "+directory+"/output/"+name+".demux.qza", "--o-visualization "+directory+"/output/"+name+".demux.QC.summary.qzv" ])) ## Take the output from this command and drop it into: #https://view.qiime2.org wait_for_user = input("The script will now wait for you to input trimming parameters in the next cell. You will need to take the .qzv files for each library and visualize them at <https://view.qiime2.org>. This is hopefully temporary, while QIIME2 developers improve on q2view.\n\n[ENTER ANYTHING. THIS IS ONLY MEANT TO PAUSE THE PIPELING]") print("\nThe script is now proceeding. Stay tuned to make sure trimming works.")
sequence_analysis_walkthrough/QIIME2_Processing_Pipeline.ipynb
buckleylab/Buckley_Lab_SIP_project_protocols
mit
Step 6: Trimming Parameters | USER INPUT REQUIRED
## User Input Required trim_dict = {} ## Input your trimming parameters into a python dictionary for all libraries #trim_dict["LibraryName1"] = [trim_forward, truncate_forward, trim_reverse, truncate_reverse] #trim_dict["LibraryName2"] = [trim_forward, truncate_forward, trim_reverse, truncate_reverse] ## Example trim_dict["bioblitz"] = [1, 240, 1, 190]
sequence_analysis_walkthrough/QIIME2_Processing_Pipeline.ipynb
buckleylab/Buckley_Lab_SIP_project_protocols
mit
Step 7: Trim, Denoise and Join (aka 'Merge') Reads Using DADA2
## Hack for Multithreading # I hardcoded 'nthreads' in both versions of 'run_dada_paired.R' (find your versions by running 'locate run_dada_paired.R' from your home directory) # I used ~ 20 threads and the processing finished in ~ 7 - 8hrs ## ## SLOW STEP (~ 6 - 8 hrs, IF multithreading is used) ## for dataset in datasets: name = dataset[0] directory = dataset[1] os.system(' '.join([ "qiime dada2 denoise-paired", "--i-demultiplexed-seqs "+directory+"/output/"+name+".demux.qza", "--o-table "+directory+"/output/"+name+".table", "--o-representative-sequences "+directory+"/output/"+name+".rep.seqs.final", "--p-trim-left-f "+str(trim_dict[name][0]), "--p-trim-left-r "+str(trim_dict[name][2]), "--p-trunc-len-f "+str(trim_dict[name][1]), "--p-trunc-len-r "+str(trim_dict[name][3]) ]))
sequence_analysis_walkthrough/QIIME2_Processing_Pipeline.ipynb
buckleylab/Buckley_Lab_SIP_project_protocols
mit
Step 8: Create Summary of OTUs
for dataset in datasets: name = dataset[0] directory = dataset[1] metadata = dataset[2] os.system(' '.join([ "qiime feature-table summarize", "--i-table "+directory+"/output/"+name+".table.qza", "--o-visualization "+directory+"/output/"+name+".table.qzv", "--m-sample-metadata-file "+directory+metadata ])) os.system(' '.join([ "qiime feature-table tabulate-seqs", "--i-data "+directory+"/output/"+name+".rep.seqs.final.qza", "--o-visualization "+directory+"/output/"+name+".rep.seqs.final.qzv" ]))
sequence_analysis_walkthrough/QIIME2_Processing_Pipeline.ipynb
buckleylab/Buckley_Lab_SIP_project_protocols
mit
Step 9: Make Phylogenetic Tree
## Hack for Multithreading # I hardcoded 'n_threads' in '_mafft.py' in the directory ~/anaconda3/envs/qiime2-2017.9/lib/python3.5/site-packages/q2_alignment # I used ~ 20 threads and the processing finished in ~ 15 min for dataset in datasets: name = dataset[0] directory = dataset[1] metadata = dataset[2] domain = dataset[3] if domain != "fungi": # Generate Alignment with MAFFT os.system(' '.join([ "qiime alignment mafft", "--i-sequences "+directory+"/output/"+name+".rep.seqs.final.qza", "--o-alignment "+directory+"/output/"+name+".rep.seqs.aligned.qza" ])) # Mask Hypervariable parts of Alignment os.system(' '.join([ "qiime alignment mask", "--i-alignment "+directory+"/output/"+name+".rep.seqs.aligned.qza", "--o-masked-alignment "+directory+"/output/"+name+".rep.seqs.aligned.masked.qza" ])) # Generate Tree with FastTree os.system(' '.join([ "qiime phylogeny fasttree", "--i-alignment "+directory+"/output/"+name+".rep.seqs.aligned.masked.qza", "--o-tree "+directory+"/output/"+name+".rep.seqs.tree.unrooted.qza" ])) # Root Tree os.system(' '.join([ "qiime phylogeny midpoint-root", "--i-tree "+directory+"/output/"+name+".rep.seqs.tree.unrooted.qza", "--o-rooted-tree "+directory+"/output/"+name+".rep.seqs.tree.final.qza" ]))
sequence_analysis_walkthrough/QIIME2_Processing_Pipeline.ipynb
buckleylab/Buckley_Lab_SIP_project_protocols
mit
Step 10: Classify Seqs
for dataset in datasets: name = dataset[0] directory = dataset[1] metadata = dataset[2] domain = dataset[3] # Classify if domain == 'bacteria': os.system(' '.join([ "qiime feature-classifier classify-sklearn", "--i-classifier /home/db/GreenGenes/qiime2_13.8.99_515.806_nb.classifier.qza", "--i-reads "+directory+"/output/"+name+".rep.seqs.final.qza", "--o-classification "+directory+"/output/"+name+".taxonomy.final.qza" ])) if domain == 'fungi': os.system(' '.join([ "qiime feature-classifier classify-sklearn", "--i-classifier /home/db/UNITE/qiime2_unite_ver7.99_20.11.2016_classifier.qza", "--i-reads "+directory+"/output/"+name+".rep.seqs.final.qza", "--o-classification "+directory+"/output/"+name+".taxonomy.final.qza" ])) # Output Summary os.system(' '.join([ "qiime metadata tabulate", "--m-input-file "+directory+"/output/"+name+".taxonomy.final.qza", "--o-visualization "+directory+"/output/"+name+".taxonomy.final.summary.qzv" ]))
sequence_analysis_walkthrough/QIIME2_Processing_Pipeline.ipynb
buckleylab/Buckley_Lab_SIP_project_protocols
mit
Step 11: Prepare Data for Import to Phyloseq
## Make Function to Re-Format Taxonomy File to Contain Full Column Information # and factor in the certain of the taxonomic assignment def format_taxonomy(tax_file, min_support): output = open(re.sub(".tsv",".fixed.tsv",tax_file), "w") output.write("\t".join(["OTU","Domain","Phylum","Class","Order","Family","Genus","Species"])+"\n") with open(tax_file, "r") as f: next(f) #skip header for line in f: line = line.strip() line = line.split("\t") read_id = line[0] tax_string = line[1] # Annotate those strings which do not meet minimum support if float(line[2]) < float(min_support): tax_string = re.sub("__","__putative ",tax_string) # Remove All Underscore Garbage (gimmie aesthetics) tax_string = re.sub("k__|p__|c__|o__|f__|g__|s__","",tax_string) # Add in columns containing unclassified taxonomic information # Predicated on maximum 7 ranks (Domain -> Species) full_rank = tax_string.split(";") last_classified = full_rank[len(full_rank)-1] count = 1 while last_classified == " ": last_classified = full_rank[len(full_rank)-count] count = count + 1 for n in range(full_rank.index(last_classified)+1, 7, 1): try: full_rank[n] = "unclassifed "+last_classified except: full_rank.append("unclassifed "+last_classified) output.write(read_id+"\t"+'\t'.join(full_rank)+"\n") return() ##################### ## Export from QIIME2 for dataset in datasets: name = dataset[0] directory = dataset[1] metadata = dataset[2] domain = dataset[3] ## Final Output Names fasta_file = directory+"/output/"+name+".rep.seqs.final.fasta" tree_file = directory+"/output/"+name+".tree.final.nwk" tax_file = directory+"/output/"+name+".taxonomy.final.tsv" count_table = directory+"/output/"+name+".counts.final.biom" # Export Classifications os.system(' '.join([ "qiime tools export", directory+"/output/"+name+".taxonomy.final.qza", "--output-dir "+directory+"/output/" ])) # Reformat Classifications to meet phyloseq format format_taxonomy(directory+"/output/taxonomy.tsv", min_support) # Export SV Table os.system(' '.join([ "qiime tools export", directory+"/output/"+name+".table.qza", "--output-dir "+directory+"/output/" ])) # Export SV Sequences os.system(' '.join([ "qiime tools export", directory+"/output/"+name+".rep.seqs.final.qza", "--output-dir "+directory+"/output/" ])) # Export Tree os.system(' '.join([ "qiime tools export", directory+"/output/"+name+".rep.seqs.tree.final.qza", "--output-dir "+directory+"/output/" ])) # Rename Exported Files %mv $directory/output/dna-sequences.fasta $fasta_file %mv $directory/output/feature-table.biom $count_table %mv $directory/output/taxonomy.fixed.tsv $tax_file if domain == "bacteria": %mv $directory/output/tree.nwk $tree_file
sequence_analysis_walkthrough/QIIME2_Processing_Pipeline.ipynb
buckleylab/Buckley_Lab_SIP_project_protocols
mit
Step 13: Get 16S rRNA Gene Copy Number (rrn)
## This step is based on the database contructed for the software 'copyrighter' ## The software itself lacked information about datastructure (and, the import of a biom from QIIME2 failed, likely because there are multiple versions of the biom format) downloaded = "N" for dataset in datasets: name = dataset[0] directory = dataset[1] domain = dataset[3] if domain == 'bacteria': if downloaded == "N": ## Download copyrighter database !git clone https://github.com/fangly/AmpliCopyrighter $directory/temp/ ## There are multiple GreenGenes ID numbers for a given taxonomic string. ## However, the copyrighter database uses the same average rrn copy number. ## We will therefore just use the taxonomic strings, since QIIME2 does not output the ID numbers !sed -e '1,1075178d; 1078115d' $directory/temp/data/201210/ssu_img40_gg201210.txt > $directory/output/copyrighter.tax.strings.tsv ## Create Dictionary of rrnDB rrnDB = {} with open(directory+"/output/copyrighter.tax.strings.tsv", "r") as f: for line in f: line = line.strip() line = line.split("\t") try: rrnDB[line[0]] = line[1] except: pass downloaded = "Y" ## Attribute rrn to readID from taxonomy.tsv output = open(directory+"/output/"+name+".seqID.to.rrn.final.tsv","w") output.write("Feature ID\trrn\n") with open(directory+"/output/taxonomy.tsv", "r") as f: missing = 0 total = 0 next(f) # Skip Header for line in f: line = line.strip() line = line.split("\t") seqID = line[0] try: rrn = rrnDB[line[1]] except: rrn = "NA" missing = missing + 1 total = total + 1 output.write(seqID+"\t"+rrn+"\n") print("\nPercent of OTUs Missing {:.1%}".format(float(missing)/total)) print("Don't Panic! The majority of missing OTUs could be low abundance.")
sequence_analysis_walkthrough/QIIME2_Processing_Pipeline.ipynb
buckleylab/Buckley_Lab_SIP_project_protocols
mit
Step 14: Import into Phyloseq
## Setup R-Magic for Jupyter Notebooks import rpy2 %load_ext rpy2.ipython def fix_biom_conversion(file): with open(file, 'r') as fin: data = fin.read().splitlines(True) with open(file, 'w') as fout: fout.writelines(data[1:]) import pandas as pd %R library(phyloseq) %R library(ape) for dataset in datasets: name = dataset[0] directory = dataset[1] metadata = dataset[2] domain = dataset[3] #### IMPORT DATA to R ## For '.tsv' files, use Pandas to create a dataframe and then pipe that to R ## For '.biom' files, first convert using 'biom convert' on the command-line ## Had problems importing the count table with pandas, opted for using read.table in R # Import Taxonomy File tax_file = pd.read_csv(directory+"/output/"+name+".taxonomy.final.tsv", sep="\t") %R -i tax_file %R rownames(tax_file) = tax_file$OTU %R tax_file$OTU <- NULL %R tax_file <- tax_file[sort(row.names(tax_file)),] #read names must match the count_table # Import Sample Data #sample_file = pd.read_csv(directory+"/"+metadata, sep="\t") sample_file = pd.read_table(directory+metadata, keep_default_na=False) %R -i sample_file %R rownames(sample_file) = sample_file$X.SampleID %R sample_file$X.SampleID <- NULL %R sample_file$LinkerPrimerSequence <- NULL ## Clean-up some other stuff # Import Count Data os.system(' '.join([ "biom convert", "-i", directory+"/output/"+name+".counts.final.biom", "-o", directory+"/output/"+name+".counts.final.tsv", "--to-tsv" ])) # The biom converter adds a stupid line that messes with the table formatting fix_biom_conversion(directory+"/output/"+name+".counts.final.tsv") # Finally import count_table = pd.read_csv(directory+"/output/"+name+".counts.final.tsv", sep="\t") %R -i count_table %R rownames(count_table) = count_table$X.OTU.ID %R count_table$X.OTU.ID <- NULL %R count_table <- count_table[sort(row.names(count_table)),] #read names must match the tax_table # Convert to Phyloseq Objects %R p_counts = otu_table(count_table, taxa_are_rows = TRUE) %R p_samples = sample_data(sample_file) %R p_tax = tax_table(tax_file) %R taxa_names(p_tax) <- rownames(tax_file) # phyloseq throws out rownames %R colnames(p_tax) <- colnames(tax_file) # phyloseq throws out colnames # Merge Phyloseq Objects %R p = phyloseq(p_counts, p_tax) # Import Phylogenetic Tree if domain == "bacteria": tree_file = directory+"/output/"+name+".tree.final.nwk" %R -i tree_file %R p_tree <- read.tree(tree_file) # Combine All Objects into One Phyloseq %R p_final <- merge_phyloseq(p, p_samples, p_tree) else: # Combine All Objects into One Phyloseq %R p_final <- merge_phyloseq(p, p_samples) # Save Phyloseq Object as '.rds' output = directory+"/output/p_"+name+".final.rds" %R -i output %R saveRDS(p_final, file = output) # Confirm Output %R print(p_final)
sequence_analysis_walkthrough/QIIME2_Processing_Pipeline.ipynb
buckleylab/Buckley_Lab_SIP_project_protocols
mit
Step 15: Clean-up Intermediate Files and Final Outputs
for dataset in datasets: directory = dataset[1] metadata = dataset[2] # Remove Files if domain == "bacteria": %rm -r $directory/output/*tree.unrooted.qza %rm -r $directory/output/*aligned.masked.qza %rm $directory/output/*.biom %rm -r $directory/temp/ %rm $directory/output/*barcodes.fastq.gz %rm $directory/output/taxonomy.tsv %rm $directory/output/forward.fastq.gz # Just the symlink %rm $directory/output/reverse.fastq.gz # Just the symlink %rm $directory/output/copyrighter.tax.strings.tsv # Separate Final Files %mkdir $directory/final/ %mv $directory/output/*.final.rds $directory/final/ %mv $directory/output/*.taxonomy.final.tsv $directory/final/ %mv $directory/output/*.counts.final.tsv $directory/final/ %mv $directory/output/*.final.fasta $directory/final/ %cp $directory$metadata $directory/final/ %mv $directory/output/*.seqID.to.rrn.final.tsv $directory/final/ %mv $directory/output/*.nwk $directory/final/ # Gzip and Move Intermediate Files !pigz -p 10 $directory/output/*.qza !pigz -p 10 $directory/output/*.qzv %mv $directory/output/ $directory/intermediate_files print("Your sequences have been successfully saved to 'final' and 'intermediate_files'")
sequence_analysis_walkthrough/QIIME2_Processing_Pipeline.ipynb
buckleylab/Buckley_Lab_SIP_project_protocols
mit
Постановка По 1260 опрошенным имеются следующие данные: заработная плата за час работы, $; опыт работы, лет; образование, лет; внешняя привлекательность, в баллах от 1 до 5; бинарные признаки: пол, семейное положение, состояние здоровья (хорошее/плохое), членство в профсоюзе, цвет кожи (белый/чёрный), занятость в сфере обслуживания (да/нет). Требуется оценить влияние внешней привлекательности на уровень заработка с учётом всех остальных факторов. Hamermesh D.S., Biddle J.E. (1994) Beauty and the Labor Market, American Economic Review, 84, 1174–1194. Данные:
raw = pd.read_csv("beauty.csv", sep=";", index_col=False) raw.head()
4 Stats for data analysis/Lectures notebooks/14 regression/stat.regression.ipynb
maxis42/ML-DA-Coursera-Yandex-MIPT
mit
Посмотрим на матрицу диаграмм рассеяния по количественным признакам:
pd.tools.plotting.scatter_matrix(raw[['wage', 'exper', 'educ', 'looks']], alpha=0.2, figsize=(15, 15), diagonal='hist') pylab.show()
4 Stats for data analysis/Lectures notebooks/14 regression/stat.regression.ipynb
maxis42/ML-DA-Coursera-Yandex-MIPT
mit
Оценим сбалансированность выборки по категориальным признакам:
print raw.union.value_counts() print raw.goodhlth.value_counts() print raw.black.value_counts() print raw.female.value_counts() print raw.married.value_counts() print raw.service.value_counts()
4 Stats for data analysis/Lectures notebooks/14 regression/stat.regression.ipynb
maxis42/ML-DA-Coursera-Yandex-MIPT
mit
У каждого признака все значения встречаются достаточно много раз, так что всё в порядке. Предобработка
data = raw
4 Stats for data analysis/Lectures notebooks/14 regression/stat.regression.ipynb
maxis42/ML-DA-Coursera-Yandex-MIPT
mit
Посмотрим на распределение целевого признака — уровня заработной платы:
plt.figure(figsize(16,7)) plt.subplot(121) data['wage'].plot.hist() plt.xlabel('Wage', fontsize=14) plt.subplot(122) np.log(data['wage']).plot.hist() plt.xlabel('Log wage', fontsize=14) pylab.show()
4 Stats for data analysis/Lectures notebooks/14 regression/stat.regression.ipynb
maxis42/ML-DA-Coursera-Yandex-MIPT
mit
Один человек в выборке получает 77.72\$ в час, остальные — меньше 45\$; удалим этого человека, чтобы регрессия на него не перенастроилась.
data = data[data['wage'] < 77]
4 Stats for data analysis/Lectures notebooks/14 regression/stat.regression.ipynb
maxis42/ML-DA-Coursera-Yandex-MIPT
mit
Посмотрим на распределение оценок привлекательности:
plt.figure(figsize(8,7)) data.groupby('looks')['looks'].agg(lambda x: len(x)).plot(kind='bar', width=0.9) plt.xticks(rotation=0) plt.xlabel('Looks', fontsize=14) pylab.show()
4 Stats for data analysis/Lectures notebooks/14 regression/stat.regression.ipynb
maxis42/ML-DA-Coursera-Yandex-MIPT
mit
В группах looks=1 и looks=5 слишком мало наблюдений. Превратим признак looks в категориальный и закодируем с помощью фиктивных переменных:
data['belowavg'] = data['looks'].apply(lambda x : 1 if x < 3 else 0) data['aboveavg'] = data['looks'].apply(lambda x : 1 if x > 3 else 0) data.drop('looks', axis=1, inplace=True)
4 Stats for data analysis/Lectures notebooks/14 regression/stat.regression.ipynb
maxis42/ML-DA-Coursera-Yandex-MIPT
mit
Данные теперь:
data.head()
4 Stats for data analysis/Lectures notebooks/14 regression/stat.regression.ipynb
maxis42/ML-DA-Coursera-Yandex-MIPT
mit
Построение модели Простейшая модель Построим линейную модель по всем признакам.
m1 = smf.ols('wage ~ exper + union + goodhlth + black + female + married +'\ 'service + educ + belowavg + aboveavg', data=data) fitted = m1.fit() print fitted.summary()
4 Stats for data analysis/Lectures notebooks/14 regression/stat.regression.ipynb
maxis42/ML-DA-Coursera-Yandex-MIPT
mit
Посмотрим на распределение остатков:
plt.figure(figsize(16,7)) plt.subplot(121) sc.stats.probplot(fitted.resid, dist="norm", plot=pylab) plt.subplot(122) np.log(fitted.resid).plot.hist() plt.xlabel('Residuals', fontsize=14) pylab.show()
4 Stats for data analysis/Lectures notebooks/14 regression/stat.regression.ipynb
maxis42/ML-DA-Coursera-Yandex-MIPT
mit
Оно скошенное, как и исходный признак. В таких ситуациях часто помогает перейти от регрессии исходного признака к регрессии его логарифма. Логарифмируем отклик
m2 = smf.ols('np.log(wage) ~ exper + union + goodhlth + black + female + married +'\ 'service + educ + belowavg + aboveavg', data=data) fitted = m2.fit() print fitted.summary() plt.figure(figsize(16,7)) plt.subplot(121) sc.stats.probplot(fitted.resid, dist="norm", plot=pylab) plt.subplot(122) np.log(fitted.resid).plot.hist() plt.xlabel('Residuals', fontsize=14) pylab.show()
4 Stats for data analysis/Lectures notebooks/14 regression/stat.regression.ipynb
maxis42/ML-DA-Coursera-Yandex-MIPT
mit
Теперь стало лучше. Посмотрим теперь на зависимость остатков от непрерывных признаков:
plt.figure(figsize(16,7)) plt.subplot(121) scatter(data['educ'],fitted.resid) plt.xlabel('Education', fontsize=14) plt.ylabel('Residuals', fontsize=14) plt.subplot(122) scatter(data['exper'],fitted.resid) plt.xlabel('Experience', fontsize=14) plt.ylabel('Residuals', fontsize=14) pylab.show()
4 Stats for data analysis/Lectures notebooks/14 regression/stat.regression.ipynb
maxis42/ML-DA-Coursera-Yandex-MIPT
mit
На втором графике видна квадратичная зависимость остатков от опыта работы. Попробуем добавить к признакам квадрат опыта работы, чтобы учесть этот эффект. Добавляем квадрат опыта работы
m3 = smf.ols('np.log(wage) ~ exper + np.power(exper,2) + union + goodhlth + black + female +'\ 'married + service + educ + belowavg + aboveavg', data=data) fitted = m3.fit() print fitted.summary() plt.figure(figsize(16,7)) plt.subplot(121) sc.stats.probplot(fitted.resid, dist="norm", plot=pylab) plt.subplot(122) np.log(fitted.resid).plot.hist() plt.xlabel('Residuals', fontsize=14) plt.figure(figsize(16,5)) plt.subplot(131) scatter(data['educ'],fitted.resid) plt.xlabel('Education', fontsize=14) plt.ylabel('Residuals', fontsize=14) plt.subplot(132) scatter(data['exper'],fitted.resid) plt.xlabel('Experience', fontsize=14) plt.ylabel('Residuals', fontsize=14) plt.subplot(133) scatter(data['exper']**2,fitted.resid) plt.xlabel('Experience^2', fontsize=14) plt.ylabel('Residuals', fontsize=14) pylab.show()
4 Stats for data analysis/Lectures notebooks/14 regression/stat.regression.ipynb
maxis42/ML-DA-Coursera-Yandex-MIPT
mit
Используем критерий Бройша-Пагана для проверки гомоскедастичности ошибок:
print 'Breusch-Pagan test: p=%f' % sms.het_breushpagan(fitted.resid, fitted.model.exog)[1]
4 Stats for data analysis/Lectures notebooks/14 regression/stat.regression.ipynb
maxis42/ML-DA-Coursera-Yandex-MIPT
mit
Ошибки гетероскедастичны, значит, значимость признаков может определяться неверно. Сделаем поправку Уайта:
m4 = smf.ols('np.log(wage) ~ exper + np.power(exper,2) + union + goodhlth + black + female +'\ 'married + service + educ + belowavg + aboveavg', data=data) fitted = m4.fit(cov_type='HC1') print fitted.summary() plt.figure(figsize(16,7)) plt.subplot(121) sc.stats.probplot(fitted.resid, dist="norm", plot=pylab) plt.subplot(122) np.log(fitted.resid).plot.hist() plt.xlabel('Residuals', fontsize=14) pylab.show()
4 Stats for data analysis/Lectures notebooks/14 regression/stat.regression.ipynb
maxis42/ML-DA-Coursera-Yandex-MIPT
mit
Удаляем незначимые признаки В предыдущей модели незначимы: цвет кожи, здоровье, семейное положение. Удалим их. Индикатор привлекательности выше среднего тоже незначим, но удалять его не будем, потому что это одна из переменных, по которым на нужно в конце ответить на вопрос.
m5 = smf.ols('np.log(wage) ~ exper + np.power(exper,2) + union + female + service + educ +'\ 'belowavg + aboveavg', data=data) fitted = m5.fit(cov_type='HC1') print fitted.summary() plt.figure(figsize(16,7)) plt.subplot(121) sc.stats.probplot(fitted.resid, dist="norm", plot=pylab) plt.subplot(122) np.log(fitted.resid).plot.hist() plt.xlabel('Residuals', fontsize=14) pylab.show()
4 Stats for data analysis/Lectures notebooks/14 regression/stat.regression.ipynb
maxis42/ML-DA-Coursera-Yandex-MIPT
mit
Посмотрим, не стала ли модель от удаления трёх признаков значимо хуже, с помощью критерия Фишера:
print "F=%f, p=%f, k1=%f" % m4.fit().compare_f_test(m5.fit())
4 Stats for data analysis/Lectures notebooks/14 regression/stat.regression.ipynb
maxis42/ML-DA-Coursera-Yandex-MIPT
mit
Не стала. Проверим, нет ли наблюдений, которые слишком сильно влияют на регрессионное уравнение:
plt.figure(figsize(8,7)) plot_leverage_resid2(fitted) pylab.show() data.loc[[1122]] data.loc[[269]]
4 Stats for data analysis/Lectures notebooks/14 regression/stat.regression.ipynb
maxis42/ML-DA-Coursera-Yandex-MIPT
mit
Выводы Итоговая модель объясняет 40% вариации логарифма отклика.
plt.figure(figsize(16,7)) plt.subplot(121) scatter(data['wage'],np.exp(fitted.fittedvalues)) plt.xlabel('Wage', fontsize=14) plt.ylabel('Exponentiated predictions', fontsize=14) plt.xlim([0,50]) plt.subplot(122) scatter(np.log(data['wage']),fitted.fittedvalues) plt.xlabel('Log wage', fontsize=14) plt.ylabel('Predictions', fontsize=14) plt.xlim([0,4]) pylab.show()
4 Stats for data analysis/Lectures notebooks/14 regression/stat.regression.ipynb
maxis42/ML-DA-Coursera-Yandex-MIPT
mit
Cross-Validate Model Using Accuracy
# Cross-validate model using accuracy cross_val_score(logit, X, y, scoring="accuracy")
machine-learning/accuracy.ipynb
tpin3694/tpin3694.github.io
mit
2. Program the ZYNQ PL
ol = Overlay('base.bit') ol.download()
Pynq-Z1/notebooks/examples/pmod_dac_adc.ipynb
AEW2015/PYNQ_PR_Overlay
bsd-3-clause
3. Instantiate the Pmod peripherals as Python objects
adc = Pmod_ADC(1) dac = Pmod_DAC(2)
Pynq-Z1/notebooks/examples/pmod_dac_adc.ipynb
AEW2015/PYNQ_PR_Overlay
bsd-3-clause
4. Write to DAC, read from ADC, print result
dac.write(0.35) sample = adc.read() print(sample)
Pynq-Z1/notebooks/examples/pmod_dac_adc.ipynb
AEW2015/PYNQ_PR_Overlay
bsd-3-clause
Contents Tracking the IO Error Report DAC-ADC Pmod Loopback Measurement Error.
from math import ceil from time import sleep import numpy as np import matplotlib.pyplot as plt from pynq import Overlay from pynq.iop import Pmod_ADC, Pmod_DAC ol = Overlay('base.bit') ol.download() adc = Pmod_ADC(1) dac = Pmod_DAC(2) delay = 0.0 values = np.linspace(0, 2, 20) samples = [] for value in values: dac.write(value) sleep(delay) sample = adc.read() samples.append(sample[0]) print('Value written: {:4.2f}\tSample read: {:4.2f}\tError: {:+4.4f}'. format(value, sample[0], sample[0]-value))
Pynq-Z1/notebooks/examples/pmod_dac_adc.ipynb
AEW2015/PYNQ_PR_Overlay
bsd-3-clause
Error plot with Matplotlib This example shows plots in notebook (rather than in separate window).
%matplotlib inline X = np.arange(len(values)) plt.bar(X + 0.0, values, facecolor='blue', edgecolor='white', width=0.5, label="Written_to_DAC") plt.bar(X + 0.25, samples, facecolor='red', edgecolor='white', width=0.5, label="Read_from_ADC") plt.title('DAC-ADC Linearity') plt.xlabel('Sample_number') plt.ylabel('Volts') plt.legend(loc='upper left', frameon=False) plt.show()
Pynq-Z1/notebooks/examples/pmod_dac_adc.ipynb
AEW2015/PYNQ_PR_Overlay
bsd-3-clause
Contents XKCD Plot Same data plotted in XKCD format ... (http://xkcd.com)
%matplotlib inline # xkcd comic book style plots with plt.xkcd(): X = np.arange(len(values)) plt.bar(X + 0.0, values, facecolor='blue', edgecolor='white', width=0.5, label="Written_to_DAC") plt.bar(X + 0.25, samples, facecolor='red', edgecolor='white', width=0.5, label="Read_from_ADC") plt.title('DAC-ADC Linearity') plt.xlabel('Sample_number') plt.ylabel('Volts') plt.legend(loc='upper left', frameon=False) plt.show()
Pynq-Z1/notebooks/examples/pmod_dac_adc.ipynb
AEW2015/PYNQ_PR_Overlay
bsd-3-clause
Contents Widget controlled plot In this example, we extend the IO plot with a slider widget to control the number of samples appearing in the output plot. We use the ipwidgets library and the simple interact() method to launch a slider bar. The interact function (ipywidgets.interact) automatically creates user interface (UI) controls for exploring code and data interactively. It is the easiest way to get started using IPython’s widgets. For more details see Using ipwidgets interact()
from math import ceil from time import sleep import numpy as np import matplotlib.pyplot as plt %matplotlib inline from ipywidgets import interact import ipywidgets as widgets from pynq import Overlay from pynq.iop import Pmod_ADC, Pmod_DAC ol = Overlay('base.bit') ol.download() dac = Pmod_DAC(2) adc = Pmod_ADC(1) def capture_samples(nmbr_of_samples): # Write to DAC, read from ADC, write to OLED delay = 0.0 values = np.linspace(0, 2, nmbr_of_samples) samples = [] for value in values: dac.write(value) sleep(delay) sample = adc.read() samples.append(sample[0]) X = np.arange(nmbr_of_samples) plt.bar(X + 0.0, values[:nmbr_of_samples+1], facecolor='blue', edgecolor='white', width=0.5, label="Written_to_DAC") plt.bar(X + 0.25, samples[:nmbr_of_samples+1], facecolor='red', edgecolor='white', width=0.5, label="Read_from_ADC") plt.title('DAC-ADC Linearity') plt.xlabel('Sample_number') plt.ylabel('Volts') plt.legend(loc='upper left', frameon=False) interact(capture_samples, nmbr_of_samples=widgets.IntSlider( min=5, max=30, step=5, value=10, continuous_update=False)); plt.show()
Pynq-Z1/notebooks/examples/pmod_dac_adc.ipynb
AEW2015/PYNQ_PR_Overlay
bsd-3-clause
Introducing Principal Component Analysis Principal component analysis is a fast and flexible unsupervised method for dimensionality reduction in data, which we saw briefly in Introducing Scikit-Learn. Its behavior is easiest to visualize by looking at a two-dimensional dataset. Consider the following 200 points:
rng = np.random.RandomState(1) X = np.dot(rng.rand(2, 2), rng.randn(2, 200)).T plt.scatter(X[:, 0], X[:, 1]) plt.axis('equal');
present/mcc2/PythonDataScienceHandbook/05.09-Principal-Component-Analysis.ipynb
csaladenes/csaladenes.github.io
mit
By eye, it is clear that there is a nearly linear relationship between the x and y variables. This is reminiscent of the linear regression data we explored in In Depth: Linear Regression, but the problem setting here is slightly different: rather than attempting to predict the y values from the x values, the unsupervised learning problem attempts to learn about the relationship between the x and y values. In principal component analysis, this relationship is quantified by finding a list of the principal axes in the data, and using those axes to describe the dataset. Using Scikit-Learn's PCA estimator, we can compute this as follows:
from sklearn.decomposition import PCA pca = PCA(n_components=2) pca.fit(X)
present/mcc2/PythonDataScienceHandbook/05.09-Principal-Component-Analysis.ipynb
csaladenes/csaladenes.github.io
mit
The fit learns some quantities from the data, most importantly the "components" and "explained variance":
print(pca.components_) print(pca.explained_variance_)
present/mcc2/PythonDataScienceHandbook/05.09-Principal-Component-Analysis.ipynb
csaladenes/csaladenes.github.io
mit
To see what these numbers mean, let's visualize them as vectors over the input data, using the "components" to define the direction of the vector, and the "explained variance" to define the squared-length of the vector:
def draw_vector(v0, v1, ax=None): ax = ax or plt.gca() arrowprops=dict(arrowstyle='->', linewidth=2, shrinkA=0, shrinkB=0) ax.annotate('', v1, v0, arrowprops=arrowprops) # plot data plt.scatter(X[:, 0], X[:, 1], alpha=0.2) for length, vector in zip(pca.explained_variance_, pca.components_): v = vector * 3 * np.sqrt(length) draw_vector(pca.mean_, pca.mean_ + v) plt.axis('equal');
present/mcc2/PythonDataScienceHandbook/05.09-Principal-Component-Analysis.ipynb
csaladenes/csaladenes.github.io
mit
These vectors represent the principal axes of the data, and the length of the vector is an indication of how "important" that axis is in describing the distribution of the data—more precisely, it is a measure of the variance of the data when projected onto that axis. The projection of each data point onto the principal axes are the "principal components" of the data. If we plot these principal components beside the original data, we see the plots shown here: figure source in Appendix This transformation from data axes to principal axes is an affine transformation, which basically means it is composed of a translation, rotation, and uniform scaling. While this algorithm to find principal components may seem like just a mathematical curiosity, it turns out to have very far-reaching applications in the world of machine learning and data exploration. PCA as dimensionality reduction Using PCA for dimensionality reduction involves zeroing out one or more of the smallest principal components, resulting in a lower-dimensional projection of the data that preserves the maximal data variance. Here is an example of using PCA as a dimensionality reduction transform:
pca = PCA(n_components=1) pca.fit(X) X_pca = pca.transform(X) print("original shape: ", X.shape) print("transformed shape:", X_pca.shape)
present/mcc2/PythonDataScienceHandbook/05.09-Principal-Component-Analysis.ipynb
csaladenes/csaladenes.github.io
mit
The transformed data has been reduced to a single dimension. To understand the effect of this dimensionality reduction, we can perform the inverse transform of this reduced data and plot it along with the original data:
X_new = pca.inverse_transform(X_pca) plt.scatter(X[:, 0], X[:, 1], alpha=0.2) plt.scatter(X_new[:, 0], X_new[:, 1], alpha=0.8) plt.axis('equal');
present/mcc2/PythonDataScienceHandbook/05.09-Principal-Component-Analysis.ipynb
csaladenes/csaladenes.github.io
mit
The light points are the original data, while the dark points are the projected version. This makes clear what a PCA dimensionality reduction means: the information along the least important principal axis or axes is removed, leaving only the component(s) of the data with the highest variance. The fraction of variance that is cut out (proportional to the spread of points about the line formed in this figure) is roughly a measure of how much "information" is discarded in this reduction of dimensionality. This reduced-dimension dataset is in some senses "good enough" to encode the most important relationships between the points: despite reducing the dimension of the data by 50%, the overall relationship between the data points are mostly preserved. PCA for visualization: Hand-written digits The usefulness of the dimensionality reduction may not be entirely apparent in only two dimensions, but becomes much more clear when looking at high-dimensional data. To see this, let's take a quick look at the application of PCA to the digits data we saw in In-Depth: Decision Trees and Random Forests. We start by loading the data:
from sklearn.datasets import load_digits digits = load_digits() digits.data.shape
present/mcc2/PythonDataScienceHandbook/05.09-Principal-Component-Analysis.ipynb
csaladenes/csaladenes.github.io
mit
Recall that the data consists of 8×8 pixel images, meaning that they are 64-dimensional. To gain some intuition into the relationships between these points, we can use PCA to project them to a more manageable number of dimensions, say two:
pca = PCA(2) # project from 64 to 2 dimensions projected = pca.fit_transform(digits.data) print(digits.data.shape) print(projected.shape) digits.target i=int(np.random.random()*1797) plt.imshow(digits.data[i].reshape(8,8),cmap='Blues') digits.target[i] digits.data[i].reshape(8,8)
present/mcc2/PythonDataScienceHandbook/05.09-Principal-Component-Analysis.ipynb
csaladenes/csaladenes.github.io
mit
We can now plot the first two principal components of each point to learn about the data:
plt.scatter(projected[:, 0], projected[:, 1], c=digits.target, edgecolor='none', alpha=0.5, cmap=plt.cm.get_cmap('Spectral', 10)) plt.xlabel('component 1') plt.ylabel('component 2') plt.colorbar();
present/mcc2/PythonDataScienceHandbook/05.09-Principal-Component-Analysis.ipynb
csaladenes/csaladenes.github.io
mit
Recall what these components mean: the full data is a 64-dimensional point cloud, and these points are the projection of each data point along the directions with the largest variance. Essentially, we have found the optimal stretch and rotation in 64-dimensional space that allows us to see the layout of the digits in two dimensions, and have done this in an unsupervised manner—that is, without reference to the labels. What do the components mean? We can go a bit further here, and begin to ask what the reduced dimensions mean. This meaning can be understood in terms of combinations of basis vectors. For example, each image in the training set is defined by a collection of 64 pixel values, which we will call the vector $x$: $$ x = [x_1, x_2, x_3 \cdots x_{64}] $$ One way we can think about this is in terms of a pixel basis. That is, to construct the image, we multiply each element of the vector by the pixel it describes, and then add the results together to build the image: $$ {\rm image}(x) = x_1 \cdot{\rm (pixel~1)} + x_2 \cdot{\rm (pixel~2)} + x_3 \cdot{\rm (pixel~3)} \cdots x_{64} \cdot{\rm (pixel~64)} $$ One way we might imagine reducing the dimension of this data is to zero out all but a few of these basis vectors. For example, if we use only the first eight pixels, we get an eight-dimensional projection of the data, but it is not very reflective of the whole image: we've thrown out nearly 90% of the pixels! figure source in Appendix The upper row of panels shows the individual pixels, and the lower row shows the cumulative contribution of these pixels to the construction of the image. Using only eight of the pixel-basis components, we can only construct a small portion of the 64-pixel image. Were we to continue this sequence and use all 64 pixels, we would recover the original image. But the pixel-wise representation is not the only choice of basis. We can also use other basis functions, which each contain some pre-defined contribution from each pixel, and write something like $$ image(x) = {\rm mean} + x_1 \cdot{\rm (basis~1)} + x_2 \cdot{\rm (basis~2)} + x_3 \cdot{\rm (basis~3)} \cdots $$ PCA can be thought of as a process of choosing optimal basis functions, such that adding together just the first few of them is enough to suitably reconstruct the bulk of the elements in the dataset. The principal components, which act as the low-dimensional representation of our data, are simply the coefficients that multiply each of the elements in this series. This figure shows a similar depiction of reconstructing this digit using the mean plus the first eight PCA basis functions: figure source in Appendix Unlike the pixel basis, the PCA basis allows us to recover the salient features of the input image with just a mean plus eight components! The amount of each pixel in each component is the corollary of the orientation of the vector in our two-dimensional example. This is the sense in which PCA provides a low-dimensional representation of the data: it discovers a set of basis functions that are more efficient than the native pixel-basis of the input data. Choosing the number of components A vital part of using PCA in practice is the ability to estimate how many components are needed to describe the data. This can be determined by looking at the cumulative explained variance ratio as a function of the number of components:
pca = PCA().fit(digits.data) plt.plot(np.cumsum(pca.explained_variance_ratio_)) plt.xlabel('number of components') plt.ylabel('cumulative explained variance');
present/mcc2/PythonDataScienceHandbook/05.09-Principal-Component-Analysis.ipynb
csaladenes/csaladenes.github.io
mit
This curve quantifies how much of the total, 64-dimensional variance is contained within the first $N$ components. For example, we see that with the digits the first 10 components contain approximately 75% of the variance, while you need around 50 components to describe close to 100% of the variance. Here we see that our two-dimensional projection loses a lot of information (as measured by the explained variance) and that we'd need about 20 components to retain 90% of the variance. Looking at this plot for a high-dimensional dataset can help you understand the level of redundancy present in multiple observations. PCA as Noise Filtering PCA can also be used as a filtering approach for noisy data. The idea is this: any components with variance much larger than the effect of the noise should be relatively unaffected by the noise. So if you reconstruct the data using just the largest subset of principal components, you should be preferentially keeping the signal and throwing out the noise. Let's see how this looks with the digits data. First we will plot several of the input noise-free data:
def plot_digits(data): fig, axes = plt.subplots(4, 10, figsize=(10, 4), subplot_kw={'xticks':[], 'yticks':[]}, gridspec_kw=dict(hspace=0.1, wspace=0.1)) for i, ax in enumerate(axes.flat): ax.imshow(data[i].reshape(8, 8), cmap='binary', interpolation='nearest', clim=(0, 16)) plot_digits(digits.data)
present/mcc2/PythonDataScienceHandbook/05.09-Principal-Component-Analysis.ipynb
csaladenes/csaladenes.github.io
mit