markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Exercise 1: Which industry sees the most Ramnit infections? Least? Count the number of infected days for "Ramnit" in each industry industry. How: 1. First filter the data to remove all the infections we don't care about 2. Aggregate the data on the column of interest. HINT: You might want to use the groupby() func...
grouped_df = data[data.botfam == "Ramnit"].groupby(['industry']) grouped_df.sum()
Notebooks/EDA/EDA Worksheet - Python Version - Answers.ipynb
cgivre/oreilly-sec-ds-fundamentals
apache-2.0
Exercise 2: Calculate the min, max, median and mean infected orgs for each bot family, sort by median In this exercise, you are asked to calculate the min, max, median and mean of infected orgs for each bot family sorted by median. HINT: 1. Using the groupby() function, create a grouped data frame 2. You can do this...
group2 = data[['botfam','orgs']].groupby( ['botfam']) summary = group2.agg([np.min, np.max, np.mean, np.median, np.std]) summary.sort_values( [('orgs', 'median')], ascending=False)
Notebooks/EDA/EDA Worksheet - Python Version - Answers.ipynb
cgivre/oreilly-sec-ds-fundamentals
apache-2.0
Exercise 3: Which date had the total most bot infections and how many infections on that day? In this exercise you are asked to aggregate and sum the number of infections (hosts) by date. Once you've done that, the next step is to sort in descending order.
df3 = data[['date','hosts']].groupby('date').sum() df3.sort_values(by='hosts', ascending=False).head(10)
Notebooks/EDA/EDA Worksheet - Python Version - Answers.ipynb
cgivre/oreilly-sec-ds-fundamentals
apache-2.0
Exercise 4: Plot the daily infected hosts for Necurs, Ramnit and PushDo In this exercise you're going to plot the daily infected hosts for three infection types. In order to do this, you'll need to do the following steps: 1. Filter the data to remove the botfamilies we don't care about. 2. Use groupby() to aggregat...
filteredData = data[ data['botfam'].isin(['Necurs', 'Ramnit', 'PushDo']) ][['date', 'botfam', 'hosts']] groupedFilteredData = filteredData.groupby( ['date', 'botfam']).sum() groupedFilteredData.unstack(level=1).plot(kind='line', subplots=False)
Notebooks/EDA/EDA Worksheet - Python Version - Answers.ipynb
cgivre/oreilly-sec-ds-fundamentals
apache-2.0
Exercise 5: What are the distribution of infected hosts for each day-of-week across all bot families? Hint: try a box plot and/or violin plot. In order to do this, there are two steps: 1. First create a day column where the day of the week is represented as an integer. You'll need to convert the date column to an ac...
data.date = pd.to_datetime( data.date ) data['day'] = data.date.dt.weekday data[['hosts', 'day']].boxplot( by='day') grouped = data[['hosts', 'day']].groupby('day') print( grouped.sum() ) grouped.box
Notebooks/EDA/EDA Worksheet - Python Version - Answers.ipynb
cgivre/oreilly-sec-ds-fundamentals
apache-2.0
CS228 Python Tutorial Adapted by Volodymyr Kuleshov and Isaac Caswell from the CS231n Python tutorial by Justin Johnson <a href="http://cs231n.github.io/python-numpy-tutorial/">Python Numpy Tutorial</a>. Introduction Python is a great general-purpose programming language on its own, but with the help of a few popular l...
def quicksort(arr): if len(arr) <= 1: return arr pivot = arr[len(arr) // 2] left = [x for x in arr if x < pivot] middle = [x for x in arr if x == pivot] right = [x for x in arr if x > pivot] return quicksort(left) + middle + quicksort(right) quicksort([3,6,8,10,1,2,1])
Python/Python-Tutorial.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
Python versions This version of the notebook has been adapted to work with Python 3.6. You can check your Python version at the command line by running python --version.
!python --version
Python/Python-Tutorial.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
Basic data types Numbers Integers and floats work as you would expect from other languages:
x = 3 x, type(x) print(x + 1) # Addition; print(x - 1) # Subtraction; print(x * 2) # Multiplication; print(x ** 2) # Exponentiation; x += 1 print(x) # Prints "4" x *= 2 print(x) # Prints "8" y = 2.5 print(type(y)) print(y, y + 1, y * 2, y ** 2)
Python/Python-Tutorial.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
Note that unlike certain other languages like <tt>C</tt>, <tt>C++</tt>, <em>Java</em>, or <tt>C#</tt>, Python does not have unary increment (x++) or decrement (x--) operators. Python also has built-in types for long integers and complex numbers; you can find all of the details in the documentation. Booleans Python impl...
t, f = True, False type(t) print(type(t))
Python/Python-Tutorial.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
Now we let's look at the operations:
print(t and f) # Logical AND print(t or f) # Logical OR print( not t) # Logical NOT print(t != f) # Logical XOR
Python/Python-Tutorial.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
Strings
hello = 'hello' # String literals can use single quotes world = "world" # or double quotes; it does not matter. print(hello, len(hello)) hw = hello + ' ' + world # String concatenation hw hw12 = '%s, %s! %d' % (hello, world, 12) # sprintf style string formatting hw12
Python/Python-Tutorial.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
String objects have a bunch of useful methods; for example:
s = "hello" print(s.capitalize()) # Capitalize a string print(s.upper()) # Convert a string to uppercase print(s.rjust(7)) # Right-justify a string, padding with spaces print(s.center(7)) # Center a string, padding with spaces print(s.replace('l', '\N{greek small letter lamda}')) # Replace all instance...
Python/Python-Tutorial.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
You can find a list of all string methods in the documentation. Containers Python includes several built-in container types: lists, dictionaries, sets, and tuples. Lists A list is the Python equivalent of an array, but is resizeable and can contain elements of different types:
xs = [3, 1, 2] # Create a list print(xs, xs[2]) # Indexing starts at 0 print(xs[-1]) # Negative indices count from the end of the list; prints "2" xs[2] = 'foo' # Lists can contain elements of different types xs xs.append('bar') # Add a new element to the end of the list xs x = xs.pop() # Remove and...
Python/Python-Tutorial.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
As usual, you can find all the gory details about lists in the documentation. Slicing In addition to accessing list elements one at a time, Python provides concise syntax to access sublists; this is known as slicing:
nums = list(range(5)) print(nums) print(nums[2:4]) # Get a slice from index 2 to 4 (exclusive) print(nums[2:]) # Get a slice from index 2 to the end print(nums[:2]) # Get a slice from the start to index 2 (exclusive) print(nums[:]) # Get a slice of the whole list, creates a sha...
Python/Python-Tutorial.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
If you want access to the index of each element within the body of a loop, use the built-in enumerate function:
animals = ['cat', 'dog', 'monkey'] for idx, animal in enumerate(animals): print('#%d: %s' % (idx + 1, animal))
Python/Python-Tutorial.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
List comprehensions: When programming, frequently we want to transform one type of data into another. As a simple example, consider the following code that computes square numbers:
nums = [0, 1, 2, 3, 4] squares = [] for x in nums: squares.append(x ** 2) squares
Python/Python-Tutorial.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
You can make this code simpler using a list comprehension:
nums = [0, 1, 2, 3, 4] squares = [x ** 2 for x in nums] squares
Python/Python-Tutorial.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
List comprehensions can also contain conditions:
nums = [0, 1, 2, 3, 4] even_squares = [x ** 2 for x in nums if x % 2 == 0] even_squares
Python/Python-Tutorial.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
Dictionaries A dictionary stores (key, value) pairs, similar to a Map in Java or an object in Javascript. You can use it like this:
d = {'cat': 'cute', 'dog': 'furry'} # Create a new dictionary with some data print(d['cat']) # Get an entry from a dictionary print('cat' in d) # Check if a dictionary has a given key d['fish'] = 'wet' # Set an entry in a dictionary d['fish'] d['monkey'] # KeyError: 'monkey' not a key of d print(...
Python/Python-Tutorial.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
You can find all you need to know about dictionaries in the documentation. It is easy to iterate over the keys in a dictionary:
d = {'person': 2, 'cat': 4, 'spider': 8} for animal in d: legs = d[animal] print('A %s has %d legs.' % (animal.ljust(6), legs))
Python/Python-Tutorial.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
If you want access to keys and their corresponding values, use the <tt>items</tt> method:
d = {'person': 2, 'cat': 4, 'spider': 8} for animal, legs in d.items(): print('A %s has %d legs.' % (animal.ljust(6), legs))
Python/Python-Tutorial.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
Dictionary comprehensions: These are similar to list comprehensions, but allow you to easily construct dictionaries. For example:
nums = [0, 1, 2, 3, 4, 5, 6] even_num_to_square = {x: x ** 2 for x in nums if x % 2 == 0} even_num_to_square
Python/Python-Tutorial.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
Sets A set is an unordered collection of distinct elements. As a simple example, consider the following:
animals = {'cat', 'dog'} print('cat' in animals) # Check if an element is in a set print('fish' in animals) animals.add('fish') # Add an element to a set print('fish' in animals) print(len(animals)) # Number of elements in a set animals.add('cat') # Adding an element that is already in the set does...
Python/Python-Tutorial.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
Loops: Iterating over a set has the same syntax as iterating over a list; however since sets are unordered, you cannot make assumptions about the order in which you visit the elements of the set:
animals = {'cat', 'dog', 'fish'} for idx, animal in enumerate(animals): print('#%d: %s' % (idx + 1, animal))
Python/Python-Tutorial.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
Set comprehensions: Like lists and dictionaries, we can easily construct sets using set comprehensions:
from math import sqrt { int(sqrt(x)) for x in range(30) }
Python/Python-Tutorial.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
Tuples A tuple is an (immutable) ordered list of values. A tuple is in many ways similar to a list; one of the most important differences is that tuples can be used as keys in dictionaries and as elements of sets, while lists cannot. Here is a trivial example:
d = { (x, x + 1): x for x in range(10) } # Create a dictionary with tuple keys t = (5, 6) # Create a tuple print(type(t)) print(d[t]) print(d[(1, 2)]) d t[0] = 1
Python/Python-Tutorial.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
We will often define functions to take optional keyword arguments, like this:
def hello(name, loud=False): if loud: print('HELLO, %s' % name.upper()) else: print('Hello, %s!' % name) hello('Bob') hello('Fred', loud=True)
Python/Python-Tutorial.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
Classes The syntax for defining classes in Python is straightforward:
class Greeter: # Constructor def __init__(self, name): self.name = name # Create an instance variable # Instance method def greet(self, loud=False): if loud: print('HELLO, %s!' % self.name.upper()) else: print('Hello, %s' % self.name) g = Greeter('Fred...
Python/Python-Tutorial.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
Numpy Numpy is the core library for scientific computing in Python. It provides a high-performance multidimensional array object, and tools for working with these arrays. To use Numpy, we first need to import the numpy package:
import numpy as np
Python/Python-Tutorial.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
Arrays A numpy array is a grid of values, all of the same type, and is indexed by a tuple of nonnegative integers. The number of dimensions is called the rank of the array; the shape of an array is a tuple of integers giving the size of the array along each dimension. We can initialize numpy arrays from nested Python l...
a = np.array([1, 2, 3]) # Create a rank 1 array print(type(a), a.shape, a[0], a[1], a[2]) a[0] = 5 # Change an element of the array a b = np.array([[1,2,3],[4,5,6]]) # Create a rank 2 array b print(b.shape) print(b[0, 0], b[0, 1], b[1, 0])
Python/Python-Tutorial.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
Numpy also provides many functions to create arrays:
np.zeros((2,2)) # Create an array of all zeros np.ones((1,2)) # Create an array of all ones np.full((2,2), 7) # Create a constant array np.eye(2) # Create a 2x2 identity matrix np.random.random((2,2)) # Create an array filled with random values
Python/Python-Tutorial.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
Array indexing Numpy offers several ways to index into arrays. Slicing: Similar to Python lists, numpy arrays can be sliced. Since arrays may be multidimensional, you must specify a slice for each dimension of the array:
import numpy as np # Create the following rank 2 array with shape (3, 4) # [[ 1 2 3 4] # [ 5 6 7 8] # [ 9 10 11 12]] a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]]) print(a) # Use slicing to pull out the subarray consisting of the first 2 rows # and columns 1 and 2; b is the following array of shape (2, 2):...
Python/Python-Tutorial.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
You can also mix integer indexing with slice indexing. However, doing so will yield an array of lower rank than the original array.
# Create the following rank 2 array with shape (3, 4) a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]]) a
Python/Python-Tutorial.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
Integer array indexing: When you index into numpy arrays using slicing, the resulting array view will always be a subarray of the original array. In contrast, integer array indexing allows you to construct arbitrary arrays using the data from another array. Here is an example:
a np.array([a[0, 0], a[1, 1], a[2, 0]])
Python/Python-Tutorial.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
The following expression will return an array containing the elements a[0,1]and a[2,3].
# When using integer array indexing, you can reuse the same # element from the source array: a[[0, 2], [1, 3]] a[0,1], a[2,3] # Equivalent to the previous integer array indexing example np.array([a[0, 1], a[2, 3]])
Python/Python-Tutorial.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
One useful trick with integer array indexing is selecting or mutating one element from each row of a matrix:
# Create a new array from which we will select elements a = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]]) a # Create an array of indices b = np.array([0, 2, 0, 1]) b # Select one element from each row of a using the indices in b a[[0, 1, 2, 3], b]
Python/Python-Tutorial.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
same as a[0,0], a[1,2], a[2,0], a[3,1],
a[0,0], a[1,2], a[2,0], a[3,1] # Mutate one element from each row of a using the indices in b a[[0, 1, 2, 3], b] += 100 a
Python/Python-Tutorial.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
Boolean array indexing: Boolean array indexing lets you pick out arbitrary elements of an array. Frequently this type of indexing is used to select the elements of an array that satisfy some condition. Here is an example:
import numpy as np a = np.array([[1,2], [3, 4], [5, 6]]) print('a = \n', a, sep='') bool_idx = (a > 2) # Find the elements of a that are bigger than 2; # this returns a numpy array of Booleans of the same # shape as a, where each slot of bool_idx tells # whe...
Python/Python-Tutorial.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
For brevity we have left out a lot of details about numpy array indexing; if you want to know more you should read the documentation. Datatypes Every numpy array is a grid of elements of the same type. Numpy provides a large set of numeric datatypes that you can use to construct arrays. Numpy tries to guess a datatype ...
x = np.array([1, 2]) # Let numpy choose the datatype y = np.array([1.0, 2.0]) # Let numpy choose the datatype z = np.array([1, 2], dtype=np.int64) # Force a particular datatype x.dtype, y.dtype, z.dtype
Python/Python-Tutorial.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
You can read all about numpy datatypes in the documentation. Array math Basic mathematical functions operate elementwise on arrays, and are available both as operator overloads and as functions in the numpy module:
x = np.array([[1,2],[3,4]], dtype=np.float64) y = np.array([[5,6],[7,8]], dtype=np.float64) # Elementwise sum x + y np.add(x, y) # Elementwise difference x - y np.subtract(x, y) # Elementwise product x * y np.multiply(x, y) # Elementwise division x / y np.divide(x, y) # Elementwise square root np.sqrt(x)
Python/Python-Tutorial.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
Note that unlike MATLAB, * is elementwise multiplication, not matrix multiplication. We instead use the dot function to compute inner products of vectors, to multiply a vector by a matrix, and to multiply matrices. dot is available both as a function in the numpy module and as an instance method of array objects:
x = np.array([[1,2],[3,4]]) x y = np.array([[5,6],[7,8]]) y v = np.array([9,10]) v w = np.array([11, 12]) w # Inner product of vectors print(v.dot(w)) print(np.dot(v, w)) # Matrix / vector product print(x.dot(v)) print(np.dot(x, v)) # Matrix / matrix product; both produce the rank 2 array print(x.dot(y)) print(np...
Python/Python-Tutorial.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
Numpy provides many useful functions for performing computations on arrays; one of the most useful is sum:
x np.sum(x) # Compute sum of all elements np.sum(x, axis=0) # Compute sum of each column np.sum(x, axis=1) # Compute sum of each row
Python/Python-Tutorial.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
You can find the full list of mathematical functions provided by numpy in the documentation. Apart from computing mathematical functions using arrays, we frequently need to reshape or otherwise manipulate data in arrays. The simplest example of this type of operation is transposing a matrix; to transpose a matrix, simp...
x x.T v = np.array([[1,2,3]]) print(v) print(v.T)
Python/Python-Tutorial.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
Broadcasting Broadcasting is a powerful mechanism that allows numpy to work with arrays of different shapes when performing arithmetic operations. Frequently we have a smaller array and a larger array, and we want to use the smaller array multiple times to perform some operation on the larger array. For example, suppos...
# We will add the vector v to each row of the matrix x, # storing the result in the matrix y x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]]) x v = np.array([1, 0, 1]) v
Python/Python-Tutorial.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
Create an empty matrix with the same shape as x. The elements of this matrix are initialized arbitrarily.
y = np.empty_like(x) y # Add the vector v to each row of the matrix x with an explicit loop for i in range(4): y[i, :] = x[i, :] + v y
Python/Python-Tutorial.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
This works; however when the matrix x is very large, computing an explicit loop in Python could be slow. Note that adding the vector v to each row of the matrix x is equivalent to forming a matrix vv by stacking multiple copies of v vertically, then performing elementwise summation of x and vv. We could implement this ...
vv = np.tile(v, (4, 1)) # Stack 4 copies of v on top of each other vv y = x + vv # Add x and vv elementwise y
Python/Python-Tutorial.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
Numpy broadcasting allows us to perform this computation without actually creating multiple copies of v. Consider this version, using broadcasting:
# We will add the vector v to each row of the matrix x, # storing the result in the matrix y y = x + v # Add v to each row of x using broadcasting y
Python/Python-Tutorial.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
The line y = x + v works even though x has shape (4, 3) and v has shape (3,) due to broadcasting; this line works as if v actually had shape (4, 3), where each row was a copy of v, and the sum was performed elementwise. Broadcasting two arrays together follows these rules: If the arrays do not have the same rank, prep...
# Compute outer product of vectors v = np.array([1,2,3]) # v has shape (3,) w = np.array([4,5]) # w has shape (2,) # To compute an outer product, we first reshape v to be a column # vector of shape (3, 1); we can then broadcast it against w to yield # an output of shape (3, 2), which is the outer product of v and w...
Python/Python-Tutorial.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
Add a vector to each column of a matrix x has shape (2, 3) and w has shape (2,). If we transpose x then it has shape (3, 2) and can be broadcast against w to yield a result of shape (3, 2); transposing this result yields the final result of shape (2, 3) which is the matrix x with the vector w added to each column. Give...
(x.T + w).T
Python/Python-Tutorial.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
Another solution is to reshape w to be a row vector of shape (2, 1); we can then broadcast it directly against x to produce the same output.
x + np.reshape(w, (2, 1))
Python/Python-Tutorial.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
Multiply a matrix by a constant: x has shape (2, 3). Numpy treats scalars as arrays of shape (); these can be broadcast together to shape (2, 3), producing the following array:
x * 2
Python/Python-Tutorial.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
Getting help in the Jupyter notebook is easy, just put a "?" after a class or function. Don't forget to use tab to help with syntax completion
exatomic.Universe?
docs/source/notebooks/01_basics.ipynb
alexvmarch/atomic
apache-2.0
The Universe object contains all of the information about a simulation, nuclear coordinates, orbitals, etc. Data is stored in pandas DataFrames (see pandas for more information)
uni = exatomic.Universe() uni
docs/source/notebooks/01_basics.ipynb
alexvmarch/atomic
apache-2.0
Empty universes can be useful...but it is more interesting with data Note that exatomic uses Hartree atomic units
atom = exatomic.Atom.from_dict({'x': [0.0, 0.0], 'y': [0.0, 0.0], 'z': [-0.34, 0.34], 'symbol': ["H", "H"], 'frame': [0, 0]}) uni = exatomic.Universe(atom=atom) uni.atom
docs/source/notebooks/01_basics.ipynb
alexvmarch/atomic
apache-2.0
The frame column is how we track state (e.g. time, theory, etc.) The simplest dataframe is the frame object which by default only contains the number of atoms
uni.frame # This was computed on-the-fly as we didn't instantiate it above
docs/source/notebooks/01_basics.ipynb
alexvmarch/atomic
apache-2.0
Visualization of this simple universe can be accomplished directly in the notebook
exatomic.UniverseWidget(uni)
docs/source/notebooks/01_basics.ipynb
alexvmarch/atomic
apache-2.0
In building the visualization, bonds were automatically computed For small systems this is the default behavior, but for large systems it is not
uni.atom_two
docs/source/notebooks/01_basics.ipynb
alexvmarch/atomic
apache-2.0
Note again that distances are in atomic units
uni.molecule
docs/source/notebooks/01_basics.ipynb
alexvmarch/atomic
apache-2.0
Center of masses can also be computed
uni.compute_molecule_com() uni.molecule
docs/source/notebooks/01_basics.ipynb
alexvmarch/atomic
apache-2.0
Here's an example of loading some document vectors. Calculating 44,500 document vectors takes about 20 minutes, so we'll get only the first 100. To save time, we'll load pre-saved document vectors for the hands-on coding exercises.
reviews = review_data[:100] # We just want the vectors so we can turn off other models in the pipeline with nlp.disable_pipes(): vectors = np.array([nlp(review.text).vector for idx, review in reviews.iterrows()]) vectors.shape
notebooks/nlp/raw/ex3.ipynb
Kaggle/learntools
apache-2.0
The result is a matrix of 100 rows and 300 columns. Why 100 rows? Because we have 1 row for each column. Why 300 columns? This is the same length as word vectors. See if you can figure out why document vectors have the same length as word vectors (some knowledge of linear algebra or vector math would be needed to figu...
# Loading all document vectors from file vectors = np.load('../input/nlp-course/review_vectors.npy')
notebooks/nlp/raw/ex3.ipynb
Kaggle/learntools
apache-2.0
1) Training a Model on Document Vectors Next you'll train a LinearSVC model using the document vectors. It runs pretty quick and works well in high dimensional settings like you have here. After running the LinearSVC model, you might try experimenting with other types of models to see whether it improves your results.
from sklearn.svm import LinearSVC from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(vectors, review_data.sentiment, test_size=0.1, random_state=1) # Create the LinearSVC model model = LinearSVC(random_state=1, ...
notebooks/nlp/raw/ex3.ipynb
Kaggle/learntools
apache-2.0
Document Similarity For the same tea house review, find the most similar review in the dataset using cosine similarity. 2) Centering the Vectors Sometimes people center document vectors when calculating similarities. That is, they calculate the mean vector from all documents, and they subtract this from each individual...
# Check your answer (Run this code cell to receive credit!) q_2.solution()
notebooks/nlp/raw/ex3.ipynb
Kaggle/learntools
apache-2.0
3) Find the most similar review Given an example review below, find the most similar document within the Yelp dataset using the cosine similarity.
review = """I absolutely love this place. The 360 degree glass windows with the Yerba buena garden view, tea pots all around and the smell of fresh tea everywhere transports you to what feels like a different zen zone within the city. I know the price is slightly more compared to the normal American size, however th...
notebooks/nlp/raw/ex3.ipynb
Kaggle/learntools
apache-2.0
Even though there are many different sorts of businesses in our Yelp dataset, you should have found another tea shop. 4) Looking at similar reviews If you look at other similar reviews, you'll see many coffee shops. Why do you think reviews for coffee are similar to the example review which mentions only tea?
# Check your answer (Run this code cell to receive credit!) q_4.solution()
notebooks/nlp/raw/ex3.ipynb
Kaggle/learntools
apache-2.0
2. Test Cytoscape REST API Check the status of server First, send a simple request and check the server status. Roundtrip between JSON and Python Object Object returned from the requests contains return value of API as JSON. Let's convert it into Python object. JSON library in Python converts JSON string into simple ...
# Get server status res = requests.get(BASE) status_object = res.json() print(json.dumps(status_object, indent=4)) print(status_object['apiVersion']) print(status_object['memoryStatus']['usedMemory'])
tutorials/answers/Lesson_1_Introduction_to_cyREST_answer.ipynb
idekerlab/sdcsb-advanced-tutorial
mit
If you are comfortable with this data type conversion, you are ready to go! 3. Import Networks from various data sources There are many ways to load networks into Cytoscape from REST API: Load from files Load from web services Send Cytoscape.js style JSON directly to Cytoscape Send edgelist 3.1 Create networks from ...
# Small utility function to create networks from list of URLs def create_from_list(network_list, collection_name='Yeast Collection'): payload = {'source': 'url', 'collection': collection_name} server_res = requests.post(BASE + 'networks', data=json.dumps(network_list), headers=HEADERS, params=payload) retur...
tutorials/answers/Lesson_1_Introduction_to_cyREST_answer.ipynb
idekerlab/sdcsb-advanced-tutorial
mit
What is SUID? SUID is a unique identifiers for all graph objects in Cytoscape. You can access any objects in current session as long as you have its SUID. Where is my local data file? This is a bit trickey part. When you specify local file, you need to absolute path On Docker container, your data file is mounted on:...
# Utility function to display JSON (Pretty-printer) def pp(json_data): print(json.dumps(json_data, indent=4)) # You need KEGGScape App to load this file! queries = [ 'http://rest.kegg.jp/get/hsa00020/kgml' ] pp(create_from_list(queries, 'KEGG Metabolic Pathways'))
tutorials/answers/Lesson_1_Introduction_to_cyREST_answer.ipynb
idekerlab/sdcsb-advanced-tutorial
mit
And of course, you can mix local files, URLs, and list of web service queries in a same list:
mixed = [ 'http://chianti.ucsd.edu/cytoscape-data/galFiltered.sif', 'http://www.ebi.ac.uk/Tools/webservices/psicquic/intact/webservices/current/search/query/brca1?format=xml25' ] result = create_from_list(mixed, 'Mixed Collection') pp(result) mixed1 = result[0]['networkSUID'][0] mixed1
tutorials/answers/Lesson_1_Introduction_to_cyREST_answer.ipynb
idekerlab/sdcsb-advanced-tutorial
mit
Understand REST Principles We used modern best practices to design cyREST API. All HTTP verbs are mapped to Cytoscape resources: | HTTP Verb | Description | |:----------:|:------------| | GET | Retrieving resources (in most cases, it is Cytoscape data objects, such as networks or tables) | | POST | Creating resources...
# Get a list of network IDs get_all_networks_url = BASE + 'networks' print(get_all_networks_url) res = requests.get(get_all_networks_url) pp(res.json()) # Pick the first network from the list above: network_suid = res.json()[0] get_network_url = BASE + 'networks/' + str(network_suid) print(get_network_url) # Get numb...
tutorials/answers/Lesson_1_Introduction_to_cyREST_answer.ipynb
idekerlab/sdcsb-advanced-tutorial
mit
Exercise 1: Guess URLs If a system's RESTful API is well-designed based on ROA best practices, it should be easy to guess similar functions as URLs. Display a clickable URLs for the following functions: Show number of networks in current session Show all edges in a network Show full information for a node (can be any ...
# Write your answers here... # 1 print(BASE + 'networks/count') #2 print(BASE + 'networks/' + str(network_suid) + '/edges') #3 # First, get available node SUID. Let's use the URL in the last section: res = requests.get(get_nodes_url) first_node_id = res.json()[0] print(BASE + 'networks/' + str(network_suid) + '/nod...
tutorials/answers/Lesson_1_Introduction_to_cyREST_answer.ipynb
idekerlab/sdcsb-advanced-tutorial
mit
POST (Create a new resource) To create new resource (objects), you should use POST methods. URLs follow ROA standards, but you need to read API documents to understand data format for each object.
# Add a new nodes to existing network (with time stamps) import datetime new_nodes =[ 'Node created at ' + str(datetime.datetime.now()), 'Node created at ' + str(datetime.datetime.now()) ] res = requests.post(get_nodes_url, data=json.dumps(new_nodes), headers=HEADERS) new_node_ids = res.json() pp(new_node_ids...
tutorials/answers/Lesson_1_Introduction_to_cyREST_answer.ipynb
idekerlab/sdcsb-advanced-tutorial
mit
DELETE (Delete a resource)
# Delete all nodes requests.delete(BASE + 'networks/' + str(mixed1) + '/nodes') # Delete a network requests.delete(BASE + 'networks/' + str(mixed1))
tutorials/answers/Lesson_1_Introduction_to_cyREST_answer.ipynb
idekerlab/sdcsb-advanced-tutorial
mit
PUT (Update a resource) PUT method is used to update information for existing resources. Just like POST methods, you need to know the data format to be posted.
# Update a node name new_values = [ { 'SUID': new_node_ids[0]['SUID'], 'value' : 'updated 1' }, { 'SUID': new_node_ids[1]['SUID'], 'value' : 'updated 2' } ] requests.put(BASE + 'networks/' + str(network_suid) + '/tables/defaultnode/columns/name', data=json.dumps(new_value...
tutorials/answers/Lesson_1_Introduction_to_cyREST_answer.ipynb
idekerlab/sdcsb-advanced-tutorial
mit
3.3 Create networks from Python objects And this is the most powerful feature in Cytoscape REST API. You can easily convert Python objects into Cytoscape networks, tables, or Visual Styles How does this work? Cytoscape REST API sends and receives data as JSON. For networks, it uses Cytoscape.js style JSON (support fo...
# Start from a clean slate: remove all networks from current session # requests.delete(BASE + 'networks') # Manually generates JSON as a Python dictionary def create_network(): network = { 'data': { 'name': 'I\'m empty!' }, 'elements': { 'nodes':...
tutorials/answers/Lesson_1_Introduction_to_cyREST_answer.ipynb
idekerlab/sdcsb-advanced-tutorial
mit
Modify network dara programmatically Since it's a simple Python dictionary, it is easy to add data to the network. Let's add some nodes and edges:
# Create sequence of letters (A-Z) seq_letters = list(map(chr, range(ord('A'), ord('Z')+1))) print(seq_letters) # Option 1: Add nods and edges with for loops def add_nodes_edges(network): nodes = [] edges = [] for lt in seq_letters: node = { 'data': { 'id': lt ...
tutorials/answers/Lesson_1_Introduction_to_cyREST_answer.ipynb
idekerlab/sdcsb-advanced-tutorial
mit
Now, your Cytoscpae window should look like this: Embed images in IPython Notebook cyRest has function to generate PNG image directly from current network view. Let's try to see the result in this notebook.
from IPython.display import Image Image(url=BASE+'networks/' + str(net1['data']['SUID'])+ '/views/first.png', embed=True)
tutorials/answers/Lesson_1_Introduction_to_cyREST_answer.ipynb
idekerlab/sdcsb-advanced-tutorial
mit
Introduction to Cytoscape Data Model Essentially, writing your workflow as a notebook is a programming. To control Cytoscape efficiently from Notebooks, you need to understand basic data model of Cytoscape. Let me explain it as a notebook... First, let's create a data file to visualize Cytoscape data model
%%writefile ../data/model.sif Model parent_of ViewModel_1 Model parent_of ViewModel_2 Model parent_of ViewModel_3 ViewModel_1 parent_of Presentation_A ViewModel_1 parent_of Presentation_B ViewModel_2 parent_of Presentation_C ViewModel_3 parent_of Presentation_D ViewModel_3 parent_of Presentation_E ViewModel_3 parent_of...
tutorials/answers/Lesson_1_Introduction_to_cyREST_answer.ipynb
idekerlab/sdcsb-advanced-tutorial
mit
Mode, View Model, and Presentation Model Essentially, Model in Cytoscape means networks and tables. Internally, Model can have multiple View Models. View Model State of the view. This is why you need to use views instead of view in the API: /v1/networks/SUID/views However, Cytoscape 3.2.x has only one rendering engine...
view_url = BASE + 'networks/' + str(model_suid) + '/views/first' print('You can access (default) network view from this URL: ' + view_url)
tutorials/answers/Lesson_1_Introduction_to_cyREST_answer.ipynb
idekerlab/sdcsb-advanced-tutorial
mit
Presentation Presentation is a stateless, actual graphics you see in the window. A View Model can have multiple Presentations. For now, you can assume there is always one presentation per View Model. What do you need to know as a cyREST user? CyREST API is fairly low level, and you can access all levels of Cytoscpae...
data_str = '' n = 0 while n <100: data_str = data_str + str(n) + '\t' + str(n+1) + '\n' n = n + 1 # Join the first and last nodes data_str = data_str + '100\t0\n' # print(data_str) res = requests.post(BASE + 'networks?format=edgelist&collection=Ring', data=data_str, headers=HEADERS) circle_suid = res.json()[...
tutorials/answers/Lesson_1_Introduction_to_cyREST_answer.ipynb
idekerlab/sdcsb-advanced-tutorial
mit
Exercise 2: Create a network from a simple edge list file Edge list is a human-editable text file to represent a graph structure. Using the sample data abobe (edge list example in 3.3.2), create a new network in Cytoscape from the edge list and visualize it just like the ring network above. Hint: Use Magic!
%%writefile ../data/small1.txt a b b c a c c d d f b f f g f h # Write your code here... f = open('../data/small1.txt', 'r') data = f.read() res = requests.post(BASE + 'networks?format=edgelist&collection=Edge List Sample', data=data, headers=HEADERS) small_network_suid = res.json()['networkSUID'] requests.get(BASE ...
tutorials/answers/Lesson_1_Introduction_to_cyREST_answer.ipynb
idekerlab/sdcsb-advanced-tutorial
mit
Face recognition The goal of this seminar is to build two simple (anv very similar) face recognition pipelines using scikit-learn package. Overall, we'd like to explore different representations and see which one works better. Prepare dataset
import scipy.io image_h, image_w = 32, 32 data = scipy.io.loadmat('faces_data.mat') X_train = data['train_faces'].reshape((image_w, image_h, -1)).transpose((2, 1, 0)).reshape((-1, image_h * image_w)) y_train = (data['train_labels'] - 1).reshape((-1,)) X_test = data['test_faces'].reshape((image_w, image_h, -1)).trans...
Seminar1/Homework 1 (Face Recognition).ipynb
Gezort/YSDA_deeplearning17
mit
Now we are going to plot some samples from the dataset using the provided helper function.
def plot_gallery(images, titles, h, w, n_row=3, n_col=6): """Helper function to plot a gallery of portraits""" plt.figure(figsize=(1.5 * n_col, 1.7 * n_row)) plt.subplots_adjust(bottom=0, left=.01, right=.99, top=.90, hspace=.35) for i in range(n_row * n_col): plt.subplot(n_row, n_col, i + 1) ...
Seminar1/Homework 1 (Face Recognition).ipynb
Gezort/YSDA_deeplearning17
mit
Nearest Neighbour baseline The simplest way to do face recognition is to treat raw pixels as features and perform Nearest Neighbor Search in the Euclidean space. Let's use KNeighborsClassifier class.
from sklearn.neighbors import KNeighborsClassifier y_train = y_train.ravel() y_test = y_test.ravel() # Use KNeighborsClassifier to calculate test score for the Nearest Neighbour classifier. clf = KNeighborsClassifier(n_neighbors=1, n_jobs=-1) clf.fit(X_train, y_train) test_score = clf.score(X_test, y_test) print('Te...
Seminar1/Homework 1 (Face Recognition).ipynb
Gezort/YSDA_deeplearning17
mit
Not very imperssive, is it? Eigenfaces All the dirty work will be done by the scikit-learn package. First we need to learn a dictionary of codewords. For that we preprocess the training set by making each face normalized (zero mean and unit variance)..
X_train.shape X_train.mean(axis=0).shape # Populate variable 'X_train_processed' with samples each of which has zero mean and unit variance. X_train_processed = X_train * 1. mean = X_train_processed.mean(axis=0) X_train_processed -= mean std = X_train_processed.std(axis=0) X_train_processed /= std X_test_processed = ...
Seminar1/Homework 1 (Face Recognition).ipynb
Gezort/YSDA_deeplearning17
mit
Now we are going to apply PCA to obtain a dictionary of codewords. PCA class is what we need (use svd_solver='randomized' for randomized PCA).
from sklearn.decomposition import RandomizedPCA n_components = 64 # Populate 'pca' with a trained instance of RamdomizedPCA. pca = RandomizedPCA(copy=True, n_components=n_components, random_state=123) X_train_pca = pca.fit_transform(X_train_processed) X_test_pca = pca.transform(X_test_processed)
Seminar1/Homework 1 (Face Recognition).ipynb
Gezort/YSDA_deeplearning17
mit
We plot a bunch of principal components.
plt.figure(figsize=(20,10)) for i in range(5): plt.subplot(1, 5, i + 1) plt.imshow(pca.components_[i].reshape(32,32), cmap=plt.cm.gray, interpolation='nearest')
Seminar1/Homework 1 (Face Recognition).ipynb
Gezort/YSDA_deeplearning17
mit
Transform training data, train an SVM and apply it to the encoded test data.
from sklearn.svm import SVC svc = SVC(kernel='linear', random_state=123) # Populate 'test_score' with test accuracy of an SVM classifier. svc.fit(X_train_pca, y_train) test_score = svc.score(X_test_pca, y_test) print('Test score: {}'.format(test_score))
Seminar1/Homework 1 (Face Recognition).ipynb
Gezort/YSDA_deeplearning17
mit
How many components are sufficient to reach the same accuracy level?
n_components = [1, 2, 4, 8, 16, 32, 64] accuracy = [] # Try different numbers of components and populate 'accuracy' list. for n_comp in n_components: pca = RandomizedPCA(n_components=n_comp, copy=True, random_state=123) X_train_pca = pca.fit_transform(X_train_processed) X_test_pca = pca.transform(X_test_pr...
Seminar1/Homework 1 (Face Recognition).ipynb
Gezort/YSDA_deeplearning17
mit
In this code, I combined what I worked on last week (creating a gene expression bar chart) with the task for this week (creating a gene expression bar chart for multiple genes). The three tissues I chose were the cerebellum, the coronary artery, and the aorta. I originally decided to do a bar chart with two tissues: th...
import numpy as np import matplotlib.pyplot as plt import csv aortaData = [] aortaDataNumbers = [] cerebellumData = [] cerebellumDataNumbers= [] arteryData = [] arteryDataNumbers = [] with open ("genomicdata.csv") as csvfile: readCSV = csv.reader(csvfile, delimiter= '\t') #gives access to the CSV file for col...
Bar Graph for Multiple Genes.ipynb
alexandratutino/rna-analysis-notebooks
apache-2.0
In this graph, along with upcoming graphs, I chose a gene that the cerebellum had a significantly high expression for. This gene, number 75 in the array, proved my previous prediction wrong since the cerebellum, the coronary artery, and the aorta all showed significantly higher gene expressions for this gene.
import numpy as np import matplotlib.pyplot as plt import csv aortaData = [] aortaDataNumbers = [] cerebellumData = [] cerebellumDataNumbers= [] arteryData = [] arteryDataNumbers = [] with open ("genomicdata.csv") as csvfile: readCSV = csv.reader(csvfile, delimiter= '\t') #gives access to the CSV file for col...
Bar Graph for Multiple Genes.ipynb
alexandratutino/rna-analysis-notebooks
apache-2.0
Simulate raw data using subject anatomy This example illustrates how to generate source estimates and simulate raw data using subject anatomy with the :class:mne.simulation.SourceSimulator class. Once the raw data is simulated, generated source estimates are reconstructed using dynamic statistical parametric mapping (d...
# Author: Ivana Kojcic <ivana.kojcic@gmail.com> # Eric Larson <larson.eric.d@gmail.com> # Kostiantyn Maksymenko <kostiantyn.maksymenko@gmail.com> # Samuel Deslauriers-Gauthier <sam.deslauriers@gmail.com> # License: BSD (3-clause) import os.path as op import numpy as np import mne from mne.da...
0.18/_downloads/925ca2811e0c01ab2f8d558f074c31a3/plot_simulated_raw_data_using_subject_anatomy.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
In order to simulate source time courses, labels of desired active regions need to be specified for each of the 4 simulation conditions. Make a dictionary that maps conditions to activation strengths within aparc.a2009s [1]_ labels. In the aparc.a2009s parcellation: 'G_temp_sup-G_T_transv' is the label for primary aud...
activations = { 'auditory/left': [('G_temp_sup-G_T_transv-lh', 100), # label, activation (nAm) ('G_temp_sup-G_T_transv-rh', 200)], 'auditory/right': [('G_temp_sup-G_T_transv-lh', 200), ('G_temp_sup-G_T_transv-rh', 100)], 'visual/left': [('S_calcarine-lh', 1...
0.18/_downloads/925ca2811e0c01ab2f8d558f074c31a3/plot_simulated_raw_data_using_subject_anatomy.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Create simulated source activity Here, :class:~mne.simulation.SourceSimulator is used, which allows to specify where (label), what (source_time_series), and when (events) event type will occur. We will add data for 4 areas, each of which contains 2 labels. Since add_data method accepts 1 label per call, it will be call...
source_simulator = mne.simulation.SourceSimulator(src, tstep=tstep) for region_id, region_name in enumerate(region_names, 1): events_tmp = events[np.where(events[:, 2] == region_id)[0], :] for i in range(2): label_name = activations[region_name][i][0] label_tmp = mne.read_labels_from_annot(subje...
0.18/_downloads/925ca2811e0c01ab2f8d558f074c31a3/plot_simulated_raw_data_using_subject_anatomy.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Simulate raw data Project the source time series to sensor space. Three types of noise will be added to the simulated raw data: multivariate Gaussian noise obtained from the noise covariance from the sample data blink (EOG) noise ECG noise The :class:~mne.simulation.SourceSimulator can be given directly to the :fun...
raw_sim = mne.simulation.simulate_raw(info, source_simulator, forward=fwd, cov=None) raw_sim.set_eeg_reference(projection=True).crop(0, 60) # for speed mne.simulation.add_noise(raw_sim, cov=noise_cov, random_state=0) mne.simulation.add_eog(raw_sim, random_state=0) mne.simulation....
0.18/_downloads/925ca2811e0c01ab2f8d558f074c31a3/plot_simulated_raw_data_using_subject_anatomy.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Reconstruct simulated source time courses using dSPM inverse operator Here, source time courses for auditory and visual areas are reconstructed separately and their difference is shown. This was done merely for better visual representation of source reconstruction. As expected, when high activations appear in primary a...
method, lambda2 = 'dSPM', 1. / 9. epochs = mne.Epochs(raw_sim, events, event_id) inv = mne.minimum_norm.make_inverse_operator(epochs.info, fwd, noise_cov) stc_aud = mne.minimum_norm.apply_inverse( epochs['auditory/left'].average(), inv, lambda2, method) stc_vis = mne.minimum_norm.apply_inverse( epochs['visual/r...
0.18/_downloads/925ca2811e0c01ab2f8d558f074c31a3/plot_simulated_raw_data_using_subject_anatomy.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Create a LagoInitFile, normally this file should be saved to the disk. Here we will use a temporary file instead. Our environment includes one CentOS 7.3 VM with one network.
with tempfile.NamedTemporaryFile(delete=False) as init_file: init_file.write(dedent(""" domains: vm-01: memory: 1024 nics: - net: net-01 disks: - template_name: el7.3-base type: template name: root dev: sda format:...
docs/examples/lago_sdk_one_vm_one_net.ipynb
lago-project/lago
gpl-2.0
Now we will initialize the environment by using the init file. Our workdir will be created automatically if it does not exists. If this is the first time you are running Lago, it might take a while as it will download the CentOS 7.3 template. You can monitor its progress by watching the log file we configured in /tmp/l...
env = sdk.init(config=init_file.name, workdir='/tmp/lago_sdk_simple_example', loglevel=logging.DEBUG, log_fname='/tmp/lago.log')
docs/examples/lago_sdk_one_vm_one_net.ipynb
lago-project/lago
gpl-2.0
When the method returns, the environment can be started:
env.start()
docs/examples/lago_sdk_one_vm_one_net.ipynb
lago-project/lago
gpl-2.0
Check which VMs are available and get some meta data:
vms = env.get_vms() print vms vm = vms['vm-01'] vm.distro() vm.ip()
docs/examples/lago_sdk_one_vm_one_net.ipynb
lago-project/lago
gpl-2.0