markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
We'll learn about what these different blocks do later in the course. For now, it's enough to know that: Convolution layers are for finding patterns in images Dense (fully connected) layers are for combining patterns across an image Now that we've defined the architecture, we can create the model like any python object:
model = VGG_16()
deeplearning1/nbs/lesson1.ipynb
sainathadapa/fastai-courses
apache-2.0
As well as the architecture, we need the weights that the VGG creators trained. The weights are the part of the model that is learnt from the data, whereas the architecture is pre-defined based on the nature of the problem. Downloading pre-trained weights is much preferred to training the model ourselves, since otherwise we would have to download the entire Imagenet archive, and train the model for many days! It's very helpful when researchers release their weights, as they did here.
fpath = get_file('vgg16.h5', FILES_PATH+'vgg16.h5', cache_subdir='models') model.load_weights(fpath)
deeplearning1/nbs/lesson1.ipynb
sainathadapa/fastai-courses
apache-2.0
Getting imagenet predictions The setup of the imagenet model is now complete, so all we have to do is grab a batch of images and call predict() on them.
batch_size = 4
deeplearning1/nbs/lesson1.ipynb
sainathadapa/fastai-courses
apache-2.0
Keras provides functionality to create batches of data from directories containing images; all we have to do is to define the size to resize the images to, what type of labels to create, whether to randomly shuffle the images, and how many images to include in each batch. We use this little wrapper to define some helpful defaults appropriate for imagenet data:
def get_batches(dirname, gen=image.ImageDataGenerator(), shuffle=True, batch_size=batch_size, class_mode='categorical'): return gen.flow_from_directory(path+dirname, target_size=(224,224), class_mode=class_mode, shuffle=shuffle, batch_size=batch_size)
deeplearning1/nbs/lesson1.ipynb
sainathadapa/fastai-courses
apache-2.0
From here we can use exactly the same steps as before to look at predictions from the model.
batches = get_batches('train', batch_size=batch_size) val_batches = get_batches('valid', batch_size=batch_size) imgs,labels = next(batches) # This shows the 'ground truth' plots(imgs, titles=labels)
deeplearning1/nbs/lesson1.ipynb
sainathadapa/fastai-courses
apache-2.0
The VGG model returns 1,000 probabilities for each image, representing the probability that the model assigns to each possible imagenet category for each image. By finding the index with the largest probability (with np.argmax()) we can find the predicted label.
def pred_batch(imgs): preds = model.predict(imgs) idxs = np.argmax(preds, axis=1) print('Shape: {}'.format(preds.shape)) print('First 5 classes: {}'.format(classes[:5])) print('First 5 probabilities: {}\n'.format(preds[0, :5])) print('Predictions prob/class: ') for i in range(len(idxs)): idx = idxs[i] print (' {:.4f}/{}'.format(preds[i, idx], classes[idx])) pred_batch(imgs)
deeplearning1/nbs/lesson1.ipynb
sainathadapa/fastai-courses
apache-2.0
Use the np.random module to generate a normal distribution of 1,000 data points in two dimensions (e.g. x, y) - choose whatever mean and sigma^2 you like. Generate another 1,000 data points with a normal distribution in two dimensions that are well separated from the first set. You now have two "clusters". Concatenate them so you have 2,000 data points in two dimensions. Plot the points. This will be the training set.
X_train_normal = np.concatenate((np.random.randn(1000,2), 2*np.random.randn(1000,2)+8.))
notebooks/anomaly_detection/anomaly_detection_zhu.ipynb
cavestruz/MLPipeline
mit
Plot the points.
plt.scatter(X_train_normal[:,0],X_train_normal[:,1])
notebooks/anomaly_detection/anomaly_detection_zhu.ipynb
cavestruz/MLPipeline
mit
Generate 100 data points with the same distribution as your first random normal 2-d set, and 100 data points with the same distribution as your second random normal 2-d set. This will be the test set labeled X_test_normal.
X_test_normal = np.concatenate((np.random.randn(100,2), 3*np.random.randn(100,2)+10.))
notebooks/anomaly_detection/anomaly_detection_zhu.ipynb
cavestruz/MLPipeline
mit
Generate 100 data points with a random uniform distribution. This will be the test set labeled X_test_uniform.
X_test_uniform = np.random.rand(100,2)
notebooks/anomaly_detection/anomaly_detection_zhu.ipynb
cavestruz/MLPipeline
mit
Define a model classifier with the svm.OneClassSVM
model = svm.OneClassSVM()
notebooks/anomaly_detection/anomaly_detection_zhu.ipynb
cavestruz/MLPipeline
mit
Fit the model to the training data.
model.fit(X_train_normal)
notebooks/anomaly_detection/anomaly_detection_zhu.ipynb
cavestruz/MLPipeline
mit
Use the trained model to predict whether X_test_normal data point are in the same distributions. Calculate the fraction of "false" predictions.
model.predict(X_test_normal)
notebooks/anomaly_detection/anomaly_detection_zhu.ipynb
cavestruz/MLPipeline
mit
Use the trained model to predict whether X_test_uniform is in the same distribution. Calculate the fraction of "false" predictions.
from collections import Counter L1=model.predict(X_test_uniform) a = Counter(L1).values()[0] b = Counter(L1).values()[1] c = float(b)/a print c
notebooks/anomaly_detection/anomaly_detection_zhu.ipynb
cavestruz/MLPipeline
mit
Use the trained model to see how well it recovers the training data. (Predict on the training data, and calculate the fraction of "false" predictions.)
L2=model.predict(X_train_normal) a2 = Counter(L2).values()[0] b2 = Counter(L2).values()[1] c2 = float(b2)/a2 print c2
notebooks/anomaly_detection/anomaly_detection_zhu.ipynb
cavestruz/MLPipeline
mit
Create another instance of the model classifier, but change the kwarg value for nu. Hint: Use help to figure out what the kwargs are.
model2 = svm.OneClassSVM(nu=.2)
notebooks/anomaly_detection/anomaly_detection_zhu.ipynb
cavestruz/MLPipeline
mit
Redo the prediction on the training set, prediction on X_test_random, and prediction on X_test.
model2.fit(X_train_normal) L3=model2.predict(X_train_normal) Counter(L3) model2.predict(X_test_normal) model2.predict(X_test_uniform)
notebooks/anomaly_detection/anomaly_detection_zhu.ipynb
cavestruz/MLPipeline
mit
Plot in scatter points the X_train in blue, X_test_normal in red, and X_test_uniform in black. Overplot the trained model decision function boundary for the first instance of the model classifier.
plt.scatter(X_train_normal[:,0],X_train_normal[:,1],color='b') plt.scatter(X_test_normal[:,0],X_test_normal[:,1],color='r') plt.scatter(X_test_uniform[:,0],X_test_uniform[:,1],color='k') xx1, yy1 = np.meshgrid(np.linspace(-5, 22, 1000), np.linspace(-5, 22,1000)) Z1 =model.decision_function(np.c_[xx1.ravel(), yy1.ravel()]) Z1 = Z1.reshape(xx1.shape) plt.contour(xx1, yy1, Z1, levels=[0], linewidths=2)
notebooks/anomaly_detection/anomaly_detection_zhu.ipynb
cavestruz/MLPipeline
mit
Do the same for the second instance of the model classifier.
plt.scatter(X_train_normal[:,0],X_train_normal[:,1],color='b') plt.scatter(X_test_normal[:,0],X_test_normal[:,1],color='r') plt.scatter(X_test_uniform[:,0],X_test_uniform[:,1],color='k') xx1, yy1 = np.meshgrid(np.linspace(-5, 22, 1000), np.linspace(-5, 22,1000)) Z1 =model2.decision_function(np.c_[xx1.ravel(), yy1.ravel()]) Z1 = Z1.reshape(xx1.shape) plt.contour(xx1, yy1, Z1, levels=[0], linewidths=2) from sklearn.covariance import EllipticEnvelope
notebooks/anomaly_detection/anomaly_detection_zhu.ipynb
cavestruz/MLPipeline
mit
Test how well EllipticEnvelope predicts the outliers when you concatenate the training data with the X_test_uniform data.
train_uniform=np.concatenate((X_train_normal,X_test_uniform)) envelope=EllipticEnvelope() envelope.fit(train_uniform) envelope.predict(train_uniform)
notebooks/anomaly_detection/anomaly_detection_zhu.ipynb
cavestruz/MLPipeline
mit
Compute and plot the mahanalobis distances of X_test, X_train_normal, X_train_uniform
plt.scatter(range(100),envelope.mahalanobis(X_test_uniform),color='black') #idk why but on the graph it's red... plt.scatter(range(2000),envelope.mahalanobis(X_train_normal),color='b') plt.scatter(range(200),envelope.mahalanobis(X_test_normal),color='r')
notebooks/anomaly_detection/anomaly_detection_zhu.ipynb
cavestruz/MLPipeline
mit
Let's get some numbers! Nodes Number of all Nodes
graph.data("MATCH (n) RETURN COUNT(n) AS NumberOfAllNodes")
prototypes/Quantifying Graph Data.ipynb
feststelltaste/software-analytics
gpl-3.0
Nodes and their Labels
pd.DataFrame(graph.data("MATCH (n) RETURN labels(n) AS Labels, COUNT(n) AS LabelCount ORDER BY LabelCount DESC"))
prototypes/Quantifying Graph Data.ipynb
feststelltaste/software-analytics
gpl-3.0
Relationships Number of all Relationships
graph.data("MATCH ()-[r]-() RETURN COUNT(r) AS NumberOfAllRelationships")
prototypes/Quantifying Graph Data.ipynb
feststelltaste/software-analytics
gpl-3.0
Relationships and their Types
pd.DataFrame(graph.data("MATCH ()-[r]-() RETURN type(r) AS Type, COUNT(r) AS TypeCount ORDER BY TypeCount DESC"))
prototypes/Quantifying Graph Data.ipynb
feststelltaste/software-analytics
gpl-3.0
Properties Number of all properties
graph.data("MATCH (n) RETURN SUM(SIZE(KEYS(n))) as NumberOfAllProperties")
prototypes/Quantifying Graph Data.ipynb
feststelltaste/software-analytics
gpl-3.0
Amount of specific Properties
pd.DataFrame(graph.data(""" MATCH (n) WITH KEYS(n) as keys UNWIND keys as properties RETURN properties as Property, COUNT(properties) as PropertyCount ORDER BY PropertyCount DESC"""))
prototypes/Quantifying Graph Data.ipynb
feststelltaste/software-analytics
gpl-3.0
You may hear text enclosed in triple quotes (""" Insert Text Here """) referred to as multi-line comments, but this is not entirely accurate. This is a special type of string (a data type we will cover), called a docstring, used to explain the purpose of a function.
""" This is a special string """
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
Make sure you read the comments within each code cell (if they are there). They will provide more real-time explanations of what is going on as you look at each line of code. Variables Variables provide names for values in programming. If you want to save a value for later or repeated use, you give the value a name, storing the contents in a variable. Variables in programming work in a fundamentally similar way to variables in algebra, but in Python they can take on various different data types. The basic variable types that we will cover in this section are integers, floating point numbers, booleans, and strings. An integer in programming is the same as in mathematics, a round number with no values after the decimal point. We use the built-in print function here to display the values of our variables as well as their types!
my_integer = 50 print my_integer, type(my_integer)
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
Variables, regardless of type, are assigned by using a single equals sign (=). Variables are case-sensitive so any changes in variation in the capitals of a variable name will reference a different variable entirely.
one = 1 print One
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
A floating point number, or a float is a fancy name for a real number (again as in mathematics). To define a float, we need to either include a decimal point or specify that the value is a float.
my_float = 1.0 print my_float, type(my_float) my_float = float(1) print my_float, type(my_float)
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
A variable of type float will not round the number that you store in it, while a variable of type integer will. This makes floats more suitable for mathematical calculations where you want more than just integers. Note that as we used the float() function to force an number to be considered a float, we can use the int() function to force a number to be considered an int.
my_int = int(3.14159) print my_int, type(my_int)
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
The int() function will also truncate any digits that a number may have after the decimal point! Strings allow you to include text as a variable to operate on. They are defined using either single quotes ('') or double quotes ("").
my_string = 'This is a string with single quotes' print my_string my_string = "This is a string with double quotes" print my_string
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
Both are allowed so that we can include apostrophes or quotation marks in a string if we so choose.
my_string = '"Jabberwocky", by Lewis Carroll' print my_string my_string = "'Twas brillig, and the slithy toves / Did gyre and gimble in the wabe;" print my_string
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
Booleans, or bools are binary variable types. A bool can only take on one of two values, these being True or False. There is much more to this idea of truth values when it comes to programming, which we cover later in the Logical Operators of this notebook.
my_bool = True print my_bool, type(my_bool)
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
There are many more data types that you can assign as variables in Python, but these are the basic ones! We will cover a few more later as we move through this tutorial. Basic Math Python has a number of built-in math functions. These can be extended even further by importing the math package or by including any number of other calculation-based packages. All of the basic arithmetic operations are supported: +, -, /, and *. You can create exponents by using ** and modular arithmetic is introduced with the mod operator, %.
print 'Addition: ', 2 + 2 print 'Subtraction: ', 7 - 4 print 'Multiplication: ', 2 * 5 print 'Division: ', 10 / 2 print 'Exponentiation: ', 3**2
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
If you are not familiar with the the mod operator, it operates like a remainder function. If we type $15 \ \% \ 4$, it will return the remainder after dividing $15$ by $4$.
print 'Modulo: ', 15 % 4
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
Mathematical functions also work on variables!
first_integer = 4 second_integer = 5 print first_integer * second_integer
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
Make sure that your variables are floats if you want to have decimal points in your answer. If you perform math exclusively with integers, you get an integer. Including any float in the calculation will make the result a float.
first_integer = 11 second_integer = 3 print first_integer / second_integer first_number = 11.0 second_number = 3.0 print first_number / second_number
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
Python has a few built-in math functions. The most notable of these are: abs() round() max() min() sum() These functions all act as you would expect, given their names. Calling abs() on a number will return its absolute value. The round() function will round a number to a specified number of the decimal points (the default is $0$). Calling max() or min() on a collection of numbers will return, respectively, the maximum or minimum value in the collection. Calling sum() on a collection of numbers will add them all up. If you're not familiar with how collections of values in Python work, don't worry! We will cover collections in-depth in the next section. Additional math functionality can be added in with the math package.
import math
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
The math library adds a long list of new mathematical functions to Python. Feel free to check out the documentation for the full list and details. It concludes some mathematical constants
print 'Pi: ', math.pi print "Euler's Constant: ", math.e
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
As well as some commonly used math functions
print 'Cosine of pi: ', math.cos(math.pi)
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
Collections Lists A list in Python is an ordered collection of objects that can contain any data type. We define a list using brackets ([]).
my_list = [1, 2, 3] print my_list
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
We can access and index the list by using brackets as well. In order to select an individual element, simply type the list name followed by the index of the item you are looking for in braces.
print my_list[0] print my_list[2]
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
Indexing in Python starts from $0$. If you have a list of length $n$, the first element of the list is at index $0$, the second element is at index $1$, and so on and so forth. The final element of the list will be at index $n-1$. Be careful! Trying to access a non-existent index will cause an error.
print 'The first, second, and third list elements: ', my_list[0], my_list[1], my_list[2] print 'Accessing outside the list bounds causes an error: ', my_list[3]
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
We can see the number of elements in a list by calling the len() function.
print len(my_list)
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
We can update and change a list by accessing an index and assigning new value.
print my_list my_list[0] = 42 print my_list
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
This is fundamentally different from how strings are handled. A list is mutable, meaning that you can change a list's elements without changing the list itself. Some data types, like strings, are immutable, meaning you cannot change them at all. Once a string or other immutable data type has been created, it cannot be directly modified without creating an entirely new object.
my_string = "Strings never change" my_string[0] = 'Z'
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
As we stated before, a list can contain any data type. Thus, lists can also contain strings.
my_list_2 = ['one', 'two', 'three'] print my_list_2
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
Lists can also contain multiple different data types at once!
my_list_3 = [True, 'False', 42]
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
If you want to put two lists together, they can be combined with a + symbol.
my_list_4 = my_list + my_list_2 + my_list_3 print my_list_4
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
In addition to accessing individual elements of a list, we can access groups of elements through slicing.
my_list = ['friends', 'romans', 'countrymen', 'lend', 'me', 'your', 'ears']
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
Slicing We use the colon (:) to slice lists.
print my_list[2:4]
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
Using : we can select a group of elements in the list starting from the first element indicated and going up to (but not including) the last element indicated. We can also select everything after a certain point
print my_list[1:]
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
And everything before a certain point
print my_list[:4]
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
Using negative numbers will count from the end of the indices instead of from the beginning. For example, an index of -1 indicates the last element of the list.
print my_list[-1]
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
You can also add a third component to slicing. Instead of simply indicating the first and final parts of your slice, you can specify the step size that you want to take. So instead of taking every single element, you can take every other element.
print my_list[0:7:2]
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
Here we have selected the entire list (because 0:7 will yield elements 0 through 6) and we have selected a step size of 2. So this will spit out element 0 , element 2, element 4, and so on through the list element selected. We can skip indicated the beginning and end of our slice, only indicating the step, if we like.
print my_list[::2]
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
Lists implictly select the beginning and end of the list when not otherwise specified.
print my_list[:]
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
With a negative step size we can even reverse the list!
print my_list[::-1]
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
Python does not have native matrices, but with lists we can produce a working fascimile. Other packages, such as numpy, add matrices as a separate data type, but in base Python the best way to create a matrix is to use a list of lists. We can also use built-in functions to generate lists. In particular we will look at range() (because we will be using it later!). Range can take several different inputs and will return a list.
b = 10 my_list = range(b) print my_list
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
Similar to our list-slicing methods from before, we can define both a start and an end for our range. This will return a list that is includes the start and excludes the end, just like a slice.
a = 0 b = 10 my_list = range(a, b) print my_list
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
We can also specify a step size. This again has the same behavior as a slice.
a = 0 b = 10 step = 2 my_list = range(a, b, step) print my_list
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
Tuples A tuple is a data type similar to a list in that it can hold different kinds of data types. The key difference here is that a tuple is immutable. We define a tuple by separating the elements we want to include by commas. It is conventional to surround a tuple with parentheses.
my_tuple = 'I', 'have', 30, 'cats' print my_tuple my_tuple = ('I', 'have', 30, 'cats') print my_tuple
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
As mentioned before, tuples are immutable. You can't change any part of them without defining a new tuple.
my_tuple[3] = 'dogs' # Attempts to change the 'cats' value stored in the the tuple to 'dogs'
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
You can slice tuples the same way that you slice lists!
print my_tuple[1:3]
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
And concatenate them the way that you would with strings!
my_other_tuple = ('make', 'that', 50) print my_tuple + my_other_tuple
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
We can 'pack' values together, creating a tuple (as above), or we can 'unpack' values from a tuple, taking them out.
str_1, str_2, int_1 = my_other_tuple print str_1, str_2, int_1
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
Unpacking assigns each value of the tuple in order to each variable on the left hand side of the equals sign. Some functions, including user-defined functions, may return tuples, so we can use this to directly unpack them and access the values that we want. Sets A set is a collection of unordered, unique elements. It works almost exactly as you would expect a normal set of things in mathematics to work and is defined using braces ({}).
things_i_like = {'dogs', 7, 'the number 4', 4, 4, 4, 42, 'lizards', 'man I just LOVE the number 4'} print things_i_like, type(things_i_like)
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
Note how any extra instances of the same item are removed in the final set. We can also create a set from a list, using the set() function.
animal_list = ['cats', 'dogs', 'dogs', 'dogs', 'lizards', 'sponges', 'cows', 'bats', 'sponges'] animal_set = set(animal_list) print animal_set # Removes all extra instances from the list
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
Calling len() on a set will tell you how many elements are in it.
print len(animal_set)
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
Because a set is unordered, we can't access individual elements using an index. We can, however, easily check for membership (to see if something is contained in a set) and take the unions and intersections of sets by using the built-in set functions.
'cats' in animal_set # Here we check for membership using the `in` keyword.
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
Here we checked to see whether the string 'cats' was contained within our animal_set and it returned True, telling us that it is indeed in our set. We can connect sets by using typical mathematical set operators, namely |, for union, and &, for intersection. Using | or & will return exactly what you would expect if you are familiar with sets in mathematics.
print animal_set | things_i_like # You can also write things_i_like | animal_set with no difference
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
Pairing two sets together with | combines the sets, removing any repetitions to make every set element unique.
print animal_set & things_i_like # You can also write things_i_like & animal_set with no difference
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
Pairing two sets together with & will calculate the intersection of both sets, returning a set that only contains what they have in common. If you are interested in learning more about the built-in functions for sets, feel free to check out the documentation. Dictionaries Another essential data structure in Python is the dictionary. Dictionaries are defined with a combination of curly braces ({}) and colons (:). The braces define the beginning and end of a dictionary and the colons indicate key-value pairs. A dictionary is essentially a set of key-value pairs. The key of any entry must be an immutable data type. This makes both strings and tuples candidates. Keys can be both added and deleted. In the following example, we have a dictionary composed of key-value pairs where the key is a genre of fiction (string) and the value is a list of books (list) within that genre. Since a collection is still considered a single entity, we can use one to collect multiple variables or values into one key-value pair.
my_dict = {"High Fantasy": ["Wheel of Time", "Lord of the Rings"], "Sci-fi": ["Book of the New Sun", "Neuromancer", "Snow Crash"], "Weird Fiction": ["At the Mountains of Madness", "The House on the Borderland"]}
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
After defining a dictionary, we can access any individual value by indicating its key in brackets.
print my_dict["Sci-fi"]
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
We can also change the value associated with a given key
my_dict["Sci-fi"] = "I can't read" print my_dict["Sci-fi"]
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
Adding a new key-value pair is as simple as defining it.
my_dict["Historical Fiction"] = ["Pillars of the Earth"] print my_dict["Historical Fiction"] print my_dict
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
String Shenanigans We already know that strings are generally used for text. We can used built-in operations to combine, split, and format strings easily, depending on our needs. The + symbol indicates concatenation in string language. It will combine two strings into a longer string.
first_string = '"Beware the Jabberwock, my son! /The jaws that bite, the claws that catch! /' second_string = 'Beware the Jubjub bird, and shun /The frumious Bandersnatch!"/' third_string = first_string + second_string print third_string
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
Strings are also indexed much in the same way that lists are.
my_string = 'Supercalifragilisticexpialidocious' print 'The first letter is: ', my_string[0] # Uppercase S print 'The last letter is: ', my_string[-1] # lowercase s print 'The second to last letter is: ', my_string[-2] # lowercase u print 'The first five characters are: ', my_string[0:5] # Remember: slicing doesn't include the final element! print 'Reverse it!: ', my_string[::-1]
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
Built-in objects and classes often have special functions associated with them that are called methods. We access these methods by using a period ('.'). We will cover objects and their associated methods more in another lecture! Using string methods we can count instances of a character or group of characters.
print 'Count of the letter i in Supercalifragilisticexpialidocious: ', my_string.count('i') print 'Count of "li" in the same word: ', my_string.count('li')
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
We can also find the first instance of a character or group of characters in a string.
print 'The first time i appears is at index: ', my_string.find('i')
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
As well as replace characters in a string.
print "All i's are now a's: ", my_string.replace('i', 'a') print "It's raining cats and dogs".replace('dogs', 'more cats')
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
There are also some methods that are unique to strings. The function upper() will convert all characters in a string to uppercase, while lower() will convert all characters in a string to lowercase!
my_string = "I can't hear you" print my_string.upper() my_string = "I said HELLO" print my_string.lower()
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
String Formatting Using the format() method we can add in variable values and generally format our strings.
my_string = "{0} {1}".format('Marco', 'Polo') print my_string my_string = "{1} {0}".format('Marco', 'Polo') print my_string
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
We use braces ({}) to indicate parts of the string that will be filled in later and we use the arguments of the format() function to provide the values to substitute. The numbers within the braces indicate the index of the value in the format() arguments. See the format() documentation for additional examples. If you need some quick and dirty formatting, you can instead use the % symbol, called the string formatting operator.
print 'insert %s here' % 'value'
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
The % symbol basically cues Python to create a placeholder. Whatever character follows the % (in the string) indicates what sort of type the value put into the placeholder will have. This character is called a conversion type. Once the string has been closed, we need another % that will be followed by the values to insert. In the case of one value, you can just put it there. If you are inserting more than one value, they must be enclosed in a tuple.
print 'There are %s cats in my %s' % (13, 'apartment')
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
In these examples, the %s indicates that Python should convert the values into strings. There are multiple conversion types that you can use to get more specific with the the formatting. See the string formatting documentation for additional examples and more complete details on use. Logical Operators Basic Logic Logical operators deal with boolean values, as we briefly covered before. If you recall, a bool takes on one of two values, True or False (or $1$ or $0$). The basic logical statements that we can make are defined using the built-in comparators. These are == (equal), != (not equal), < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to).
print 5 == 5 print 5 > 5
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
These comparators also work in conjunction with variables.
m = 2 n = 23 print m < n
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
We can string these comparators together to make more complex logical statements using the logical operators or, and, and not.
statement_1 = 10 > 2 statement_2 = 4 <= 6 print "Statement 1 truth value: {0}".format(statement_1) print "Statement 2 truth value: {0}".format(statement_2) print "Statement 1 and Statement 2: {0}".format(statement_1 and statement_2)
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
The or operator performs a logical or calculation. This is an inclusive or, so if either component paired together by or is True, the whole statement will be True. The and statement only outputs True if all components that are anded together are True. Otherwise it will output False. The not statement simply inverts the truth value of whichever statement follows it. So a True statement will be evaluated as False when a not is placed in front of it. Similarly, a False statement will become True when a not is in front of it. Say that we have two logical statements, or assertions, $P$ and $Q$. The truth table for the basic logical operators is as follows: | P | Q | not P| P and Q | P or Q| |:-----:|:-----:|:---:|:---:|:---:| | True | True | False | True | True | | False | True | True | False | True | | True | False | False | False | True | | False | False | True | False | False | We can string multiple logical statements together using the logical operators.
print ((2 < 3) and (3 > 0)) or ((5 > 6) and not (4 < 2))
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
Logical statements can be as simple or complex as we like, depending on what we need to express. Evaluating the above logical statement step by step we see that we are evaluating (True and True) or (False and not False). This becomes True or (False and True), subsequently becoming True or False, ultimately being evaluated as True. Truthiness Data types in Python have a fun characteristic called truthiness. What this means is that most built-in types will evaluate as either True or False when a boolean value is needed (such as with an if-statement). As a general rule, containers like strings, tuples, dictionaries, lists, and sets, will return True if they contain anything at all and False if they contain nothing.
# Similar to how float() and int() work, bool() forces a value to be considered a boolean! print bool('') print bool('I have character!') print bool([]) print bool([1, 2, 3])
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
And so on, for the other collections and containers. None also evaluates as False. The number 1 is equivalent to True and the number 0 is equivalent to False as well, in a boolean context. If-statements We can create segments of code that only execute if a set of conditions is met. We use if-statements in conjunction with logical statements in order to create branches in our code. An if block gets entered when the condition is considered to be True. If condition is evaluated as False, the if block will simply be skipped unless there is an else block to accompany it. Conditions are made using either logical operators or by using the truthiness of values in Python. An if-statement is defined with a colon and a block of indented text.
# This is the basic format of an if statement. This is a vacuous example. # The string "Condition" will always evaluated as True because it is a # non-empty string. he purpose of this code is to show the formatting of # an if-statement. if "Condition": # This block of code will execute because the string is non-empty # Everything on these indented lines print True else: # So if the condition that we examined with if is in fact False # This block of code will execute INSTEAD of the first block of code # Everything on these indented lines print False # The else block here will never execute because "Condition" is a non-empty string. i = 4 if i == 5: print 'The variable i has a value of 5'
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
Because in this example i = 4 and the if-statement is only looking for whether i is equal to 5, the print statement will never be executed. We can add in an else statement to create a contingency block of code in case the condition in the if-statement is not evaluated as True.
i = 4 if i == 5: print "All lines in this indented block are part of this block" print 'The variable i has a value of 5' else: print "All lines in this indented block are part of this block" print 'The variable i is not equal to 5'
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
We can implement other branches off of the same if-statement by using elif, an abbreviation of "else if". We can include as many elifs as we like until we have exhausted all the logical branches of a condition.
i = 1 if i == 1: print 'The variable i has a value of 1' elif i == 2: print 'The variable i has a value of 2' elif i == 3: print 'The variable i has a value of 3' else: print "I don't care what i is"
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
You can also nest if-statements within if-statements to check for further conditions.
i = 10 if i % 2 == 0: if i % 3 == 0: print 'i is divisible by both 2 and 3! Wow!' elif i % 5 == 0: print 'i is divisible by both 2 and 5! Wow!' else: print 'i is divisible by 2, but not 3 or 5. Meh.' else: print 'I guess that i is an odd number. Boring.'
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
Remember that we can group multiple conditions together by using the logical operators!
i = 5 j = 12 if i < 10 and j > 11: print '{0} is less than 10 and {1} is greater than 11! How novel and interesting!'.format(i, j)
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
You can use the logical comparators to compare strings!
my_string = "Carthago delenda est" if my_string == "Carthago delenda est": print 'And so it was! For the glory of Rome!' else: print 'War elephants are TERRIFYING. I am staying home.'
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
As with other data types, == will check for whether the two things on either side of it have the same value. In this case, we compare whether the value of the strings are the same. Using &gt; or &lt; or any of the other comparators is not quite so intuitive, however, so we will stay from using comparators with strings in this lecture. Comparators will examine the lexicographical order of the strings, which might be a bit more in-depth than you might like. Some built-in functions return a boolean value, so they can be used as conditions in an if-statement. User-defined functions can also be constructed so that they return a boolean value. This will be covered later with function definition! The in keyword is generally used to check membership of a value within another value. We can check memebership in the context of an if-statement and use it to output a truth value.
if 'a' in my_string or 'e' in my_string: print 'Those are my favorite vowels!'
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense
Here we use in to check whether the variable my_string contains any particular letters. We will later use in to iterate through lists! Loop Structures Loop structures are one of the most important parts of programming. The for loop and the while loop provide a way to repeatedly run a block of code repeatedly. A while loop will iterate until a certain condition has been met. If at any point after an iteration that condition is no longer satisfied, the loop terminates. A for loop will iterate over a sequence of values and terminate when the sequence has ended. You can instead include conditions within the for loop to decide whether it should terminate early or you could simply let it run its course.
i = 5 while i > 0: # We can write this as 'while i:' because 0 is False! i -= 1 print 'I am looping! {0} more to go!'.format(i)
Notebooks/quantopian_research_public/notebooks/lectures/Introduction_to_Python/notebook.ipynb
d00d/quantNotebooks
unlicense