markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
There isn't much difference between the channels in terms of the mean and the standard deviation. | N = 20000
fig = plt.figure(figsize=(12,8))
ax = fig.add_subplot(111, projection='3d')
ax.set_xlabel('R')
ax.set_ylabel('G')
ax.set_zlabel('B')
ax.scatter(samples_rgb_subset[:N,0], samples_rgb_subset[:N,1], samples_rgb_subset[:N,2],
marker='+', alpha=0.1, c='black')
ax.plot(np.array([rgb_mean[0]-rgb_std[0], ... | SUPPLEMENTARY - Standardisation.ipynb | Britefury/deep-learning-tutorial-pydata2016 | mit |
A subset of the samples with the mean and standard deviation plotted; the mean as at the centre of the cross and the lines that pass through it extend 1 standard deviation to either side.
PCA whitening
We can use PCA to extract the primary axes of variance and plot them. Note that we retain all axes; we do not use PCA ... | pca = PCA(n_components=3, whiten=True)
pca.fit(samples_rgb)
fig = plt.figure(figsize=(12,8))
ax = fig.add_subplot(111, projection='3d')
ax.set_xlabel('R')
ax.set_ylabel('G')
ax.set_zlabel('B')
ax.scatter(z[:,0], z[:,1], z[:,2],
marker='+', alpha=0.1, c='black')
# Get the mean and principal component axes an... | SUPPLEMENTARY - Standardisation.ipynb | Britefury/deep-learning-tutorial-pydata2016 | mit |
The samples with the principal components extracted by PCA.
Rotate the samples onto the standard basis axes.
Use the PCA instance to rotate the samples onto the standard basis axes. | # Turn whitening off temporarily so that we don't scale the samples yet.
pca.whiten = False
z_basis = pca.transform(z)
fig = plt.figure(figsize=(12,8))
ax = fig.add_subplot(111, projection='3d')
ax.set_xlabel('pc-0')
ax.set_ylabel('pc-1')
ax.set_zlabel('pc-2')
ax.scatter(z_basis[:,0], z_basis[:,1], z_basis[:,2],
... | SUPPLEMENTARY - Standardisation.ipynb | Britefury/deep-learning-tutorial-pydata2016 | mit |
The samples are primarily aligned along the X-axis.
Full PCA whitening
PCA whitening adds one final step; after rotating the samples so that the principal components are aligned with the standard basis axes, the samples are scaled by the reciprocal of the standard deviation so that the distribution has unit variance. | # Turn whitening back on.
pca.whiten = True
z_whitened = pca.transform(z)
fig = plt.figure(figsize=(12,8))
ax = fig.add_subplot(111, projection='3d')
ax.set_xlabel('pcw-0')
ax.set_ylabel('pcw-1')
ax.set_zlabel('pcw-2')
ax.scatter(z_whitened[:,0], z_whitened[:,1], z_whitened[:,2],
marker='+', alpha=0.1, c='b... | SUPPLEMENTARY - Standardisation.ipynb | Britefury/deep-learning-tutorial-pydata2016 | mit |
But first, an aside about joining strings | print("&\n".join(planets))
print("&\n".join(planets[:4]))
kittens = document.find_all('div', {'class': 'kitten'})
for item in kittens:
h2_tag = item.find('h2')
print(h2_tag.string)
a_tags = item.find_all('a') #anchor tag, ancestor
all_shows_str = [] #create a new list
for a_tag_item in a_tags:
... | data and database/.ipynb_checkpoints/june 7 Allison's classnotes-checkpoint.ipynb | sz2472/foundations-homework | mit |
Another Aside: lists and ...lists | Our next goal is to create a data structure that looks like this:
[
{'name': 'Fluffy',
'tv shows': ['Deep Space Nine', 'Mr.Belvedere']},
{}
x = ["a", "b", "c", "d"]
x[0]
x.append("e")
len(x)
x[4]
numbers = [1,2,3,4,5,6]
# end up with: [1,4,9,16,25,36]
squared = [item * item for ite... | data and database/.ipynb_checkpoints/june 7 Allison's classnotes-checkpoint.ipynb | sz2472/foundations-homework | mit |
Scraping the Faculty, how many percentage of the CJ faculty are adjunct faculty
our hypothesis:
find all the <li> tags
inside the <li> tags, find the <h4>
inside the <h4>, the name is the content of an <a>
inside the <li> tags, find the <p> with class description
** the title of the professor is the content of that tag... | from urllib.request import urlopen
faculty_html = urlopen("http://www.journalism.columbia.edu/page/10/10?category_ids%5B%5D=2&category_ids%5B%5D=3&category_ids%5B%5D=37").read()
document = BeautifulSoup(faculty_html, "html.parser")
document.find('h2').string
h2_tag = document.find('h2')
h2_tag.string | data and database/.ipynb_checkpoints/june 7 Allison's classnotes-checkpoint.ipynb | sz2472/foundations-homework | mit |
very first task: print out the names of all the faculty members. | # this doesn't work,
ul_tag = document.find('ul', {'class': 'experts-list'})
li_tags= ul_tag.find_all('li')
for item in li_tags:
h4_tag = item.find('h4')
if h4_tag: #none counts as false in python, only proceed if we actually found a h4-tag under li tags
a_tag = h4_tag.find('a')#name of adjunct
... | data and database/.ipynb_checkpoints/june 7 Allison's classnotes-checkpoint.ipynb | sz2472/foundations-homework | mit |
Now, we want to make a list of dictionaries of faculty members along with their titles
[{'name': 'Bodarky George', 'title': 'Adjunct Assistant Professor '},
{'name':''}] | profs = []
ul_tag = document.find('ul', {'class': 'experts-list'})
li_tags= ul_tag.find_all('li')
for item in li_tags:
h4_tag = item.find('h4')
if h4_tag: #none counts as false in python, only proceed if we actually found a h4-tag under li tags
a_tag = h4_tag.find('a')
p_tag = item.find('p', {'c... | data and database/.ipynb_checkpoints/june 7 Allison's classnotes-checkpoint.ipynb | sz2472/foundations-homework | mit |
String Indexing
print all of the professors whose last name start with M | # print all of the professors whose last name start with 'M'
m_profs = []
mcount = 0
for item in profs:
prof_name = item['name']
if prof_name[0]=='M':
print(item['name'])
mcount += 1 #mcount= mcount+1
print(mcount)
# find all of the professors listed as "Adjunct Faculty"
adjunct_prof... | data and database/.ipynb_checkpoints/june 7 Allison's classnotes-checkpoint.ipynb | sz2472/foundations-homework | mit |
lost count of asides | x=5
x
x = x-1
x
x -= 1
x
x *=2
x | data and database/.ipynb_checkpoints/june 7 Allison's classnotes-checkpoint.ipynb | sz2472/foundations-homework | mit |
Variables names can contain a-z, A-Z, 0-9 and some special character as _ but must always begin by a letter. By convention, variables names are smallcase.
Types
Variables are weakly typed in python which means that their type is deduced from the context: the initialization or the types of the variables used for its co... | print("Integer")
a = 3
print(a,type(a))
print("\nFloat")
b = 3.14
print(b,type(b))
print("\nComplex")
c = 3.14 + 2j
print(c,type(c))
print(c.real,type(c.real))
print(c.imag,type(c.imag)) | 1_Basics.ipynb | iutzeler/Introduction-to-Python-for-Data-Sciences | mit |
This typing can lead to some variable having unwanted types, which can be resolved by casting | d = 1j*1j
print(d,type(d))
d = d.real
print(d,type(d))
d = int(d)
print(d,type(d))
e = 10/3
print(e,type(e))
f = (10/3)/(10/3)
print(f,type(f))
f = int((10/3)/(10/3))
print(f,type(f)) | 1_Basics.ipynb | iutzeler/Introduction-to-Python-for-Data-Sciences | mit |
Operation on numbers
The usual operations are
* Multiplication and Division with respecively * and /
* Exponent with **
* Modulo with % | print(7 * 3., type(7 * 3.)) # int x float -> float
print(3/2, type(3/2)) # Warning: int in Python 2, float in Python 3
print(3/2., type(3/2.)) # To be sure
print(2**10, type(2**10))
print(8%2, type(8%2)) | 1_Basics.ipynb | iutzeler/Introduction-to-Python-for-Data-Sciences | mit |
Booleans
Boolean is the type of a variable True or False and thus are extremely useful when coding.
* They can be obtained by comparisons >, >= (greater, greater or égal), <, <= (smaller, smaller or equal) or membership == , != (equality, different).
* They can be manipulated by the logical operations and... | print('2 > 1\t', 2 > 1)
print('2 > 2\t', 2 > 2)
print('2 >= 2\t',2 >= 2)
print('2 == 2\t',2 == 2)
print('2 == 2.0',2 == 2.0)
print('2 != 1.9',2 != 1.9)
print(True and False)
print(True or True)
print(not False) | 1_Basics.ipynb | iutzeler/Introduction-to-Python-for-Data-Sciences | mit |
Lists
Lists are the base element for sequences of variables in python, they are themselves a variable type.
* The syntax to write them is [ ... , ... ]
* The types of the elements may not be all the same
* The indices begin at $0$ (l[0] is the first element of l)
* Lists can be nested (lists of lists of ...)
Warning: ... | l = [1, 2, 3, [4,8] , True , 2.3]
print(l, type(l))
print(l[0],type(l[0]))
print(l[3],type(l[3]))
print(l[3][1],type(l[3][1]))
print(l)
print(l[4:]) # l[4:] is l from the position 4 (included)
print(l[:5]) # l[:5] is l up to position 5 (excluded)
print(l[4:5]) # l[4:5] is l between 4 (included) and 5 (excluded) so ju... | 1_Basics.ipynb | iutzeler/Introduction-to-Python-for-Data-Sciences | mit |
Operations on lists
One can add, insert, remove, count, or test if a element is in a list easily | l.append(10) # Add an element to l (the list is not copied, it is actually l that is modified)
print(l)
l.insert(1,'u') # Insert an element at position 1 in l (the list is not copied, it is actually l that is modified)
print(l)
l.remove(10) # Remove the first element 10 of l
print(l)
print(len(l)) # length of a... | 1_Basics.ipynb | iutzeler/Introduction-to-Python-for-Data-Sciences | mit |
Handling lists
Lists are pointer-like types. Meaning that if you write l2=l, you do not copy l to l2 but rather copy the pointer so modifying one, will modify the other.
The proper way to copy list is to use the dedicated copy method for list variables. | l2 = l
l.append('Something')
print(l,l2)
l3 = list(l) # l.copy() works in Python 3
l.remove('Something')
print(l,l3) | 1_Basics.ipynb | iutzeler/Introduction-to-Python-for-Data-Sciences | mit |
You can have void lists and concatenate list by simply using the + operator, or even repeat them with * . | l4 = []
l5 =[4,8,10.9865]
print(l+l4+l5)
print(l5*3) | 1_Basics.ipynb | iutzeler/Introduction-to-Python-for-Data-Sciences | mit |
Tuples, Dictionaries [*]
Tuples are similar to list but are created with (...,...) or simply comas. They cannot be changed once created. | t = (1,'b',876876.908)
print(t,type(t))
print(t[0])
a,b = 12,[987,98987]
u = a,b
print(a,b,u)
try:
u[1] = 2
except Exception as error:
print(error) | 1_Basics.ipynb | iutzeler/Introduction-to-Python-for-Data-Sciences | mit |
Dictionaries are aimed at storing values of the form key-value with the syntax {key1 : value1, ...}
This type is often used as a return type in librairies. | d = {"param1" : 1.0, "param2" : True, "param3" : "red"}
print(d,type(d))
print(d["param1"])
d["param1"] = 2.4
print(d) | 1_Basics.ipynb | iutzeler/Introduction-to-Python-for-Data-Sciences | mit |
Strings and text formatting
Strings are delimited with (double) quotes. They can be handled globally the same way as lists (see above).
<tt>print</tt> displays (tuples of) variables (not necessarily strings).
To include variable into string, it is preferable to use the <tt>format</tt> method.
Warning: text formatting... | s = "test"
print(s,type(s))
print(s[0])
print(s + "42")
print(s,42)
print(s+"42")
try:
print(s+42)
except Exception as error:
print(error) | 1_Basics.ipynb | iutzeler/Introduction-to-Python-for-Data-Sciences | mit |
The format method | print( "test {}".format(42) )
print( "test with an int {:d}, a float {} (or {:e} which is roughly {:.1f})".format(4 , 3.141 , 3.141 , 3.141 )) | 1_Basics.ipynb | iutzeler/Introduction-to-Python-for-Data-Sciences | mit |
2- Branching and Loops
If, Elif, Else
In Python, the formulation for branching is the if: condition (mind the :) followed by an indentation of one tab that represents what is executed if the condition is true. The indentation is primordial and at the core of Python. | statement1 = False
statement2 = False
if statement1:
print("statement1 is True")
elif statement2:
print("statement2 is True")
else:
print("statement1 and statement2 are False")
statement1 = statement2 = True
if statement1:
if statement2:
print("both statement1 and statement2 are True")
if st... | 1_Basics.ipynb | iutzeler/Introduction-to-Python-for-Data-Sciences | mit |
For loop
The syntax of for loops is for x in something: followed by an indentation of one tab which represents what will be executed.
The something above can be of different nature: list, dictionary, etc. | for x in [1, 2, 3]:
print(x)
sentence = ""
for word in ["Python", "for", "data", "Science"]:
sentence = sentence + word + " "
print(sentence) | 1_Basics.ipynb | iutzeler/Introduction-to-Python-for-Data-Sciences | mit |
A useful function is <tt>range</tt> which generated sequences of numbers that can be used in loops. | print("Range (from 0) to 4 (excluded) ")
for x in range(4):
print(x)
print("Range from 2 (included) to 6 (excluded) ")
for x in range(2,6):
print(x)
print("Range from 1 (included) to 12 (excluded) by steps of 3 ")
for x in range(1,12,3):
print(x) | 1_Basics.ipynb | iutzeler/Introduction-to-Python-for-Data-Sciences | mit |
If the index is needed along with the value, the function enumerate is useful. | for idx, x in enumerate(range(-3,3)):
print(idx, x) | 1_Basics.ipynb | iutzeler/Introduction-to-Python-for-Data-Sciences | mit |
While loop
Similarly to for loops, the syntax iswhile condition: followed by an indentation of one tab which represents what will be executed. | i = 0
while i<5:
print(i)
i+=1 | 1_Basics.ipynb | iutzeler/Introduction-to-Python-for-Data-Sciences | mit |
Try [*]
When a command may fail, you can try to execute it and optionally catch the Exception (i.e. the error). | a = [1,2,3]
print(a)
try:
a[1] = 3
print("command ok")
except Exception as error:
print(error)
print(a) # The command went through
try:
a[6] = 3
print("command ok")
except Exception as error:
print(error)
print(a) # The command failed | 1_Basics.ipynb | iutzeler/Introduction-to-Python-for-Data-Sciences | mit |
3- Functions
In Python, a function is defined as def function_name(function_arguments): followed by an indentation representing what is inside the function. (No return arguments are provided a priori) | def fun0():
print("\"fun0\" just prints")
fun0() | 1_Basics.ipynb | iutzeler/Introduction-to-Python-for-Data-Sciences | mit |
Docstring can be added to document the function, which will appear when calling help | def fun1(l):
"""
Prints a list and its length
"""
print(l, " is of length ", len(l))
fun1([1,'iuoiu',True])
help(fun1) | 1_Basics.ipynb | iutzeler/Introduction-to-Python-for-Data-Sciences | mit |
Outputs
return outputs a variable, tuple, dictionary, ... | def square(x):
"""
Return x squared.
"""
return(x ** 2)
help(square)
res = square(12)
print(res)
def powers(x):
"""
Return the first powers of x.
"""
return(x ** 2, x ** 3, x ** 4)
help(powers)
res = powers(12)
print(res, type(res))
two,three,four = powers(3)
print(three,type(three)... | 1_Basics.ipynb | iutzeler/Introduction-to-Python-for-Data-Sciences | mit |
Arguments
It is possible to
* Give the arguments in any order provided that you write the corresponding argument variable name
* Set defaults values to variables so that they become optional | def fancy_power(x, p=2, debug=False):
"""
Here is a fancy version of power that computes the square of the argument or other powers if p is set
"""
if debug:
print( "\"fancy_power\" is called with x =", x, " and p =", p)
return(x**p)
print(fancy_power(5))
print(fancy_power(5,p=3))
res = fa... | 1_Basics.ipynb | iutzeler/Introduction-to-Python-for-Data-Sciences | mit |
4- Classes [*]
Classes are at the core of object-oriented programming, they are used to represent an object with related attribues (variables) and methods (functions).
They are defined as functions but with the keyword class class my_class(object): followed by an indentation. The definition of a class usually contains... | class Point(object):
"""
Class of a point in the 2D plane.
"""
def __init__(self, x=0.0, y=0.0):
"""
Creation of a new point at position (x, y).
"""
self.x = x
self.y = y
def translate(self, dx, dy):
"""
Translate the point by (dx , dy... | 1_Basics.ipynb | iutzeler/Introduction-to-Python-for-Data-Sciences | mit |
5- Reading and writing files
open returns a file object, and is most commonly used with two arguments: open(filename, mode).
The first argument is a string containing the filename. The second argument is another string containing a few characters describing the way in which the file will be used (optional, 'r' will be ... | f = open('./data/test.txt', 'w')
print(f) | 1_Basics.ipynb | iutzeler/Introduction-to-Python-for-Data-Sciences | mit |
f.write(string) writes the contents of string to the file. | f.write("This is a test\n")
f.close() | 1_Basics.ipynb | iutzeler/Introduction-to-Python-for-Data-Sciences | mit |
Warning: For the file to be actually written and being able to be opened and modified again without mistakes, it is primordial to close the file handle with f.close()
f.read() will read an entire file and put the pointer at the end. | f = open('./data/text.txt', 'r')
f.read()
f.read() | 1_Basics.ipynb | iutzeler/Introduction-to-Python-for-Data-Sciences | mit |
The end of the file has be reached so the command returns ''.
To get to the top, use f.seek(offset, from_what). The position is computed from adding offset to a reference point; the reference point is selected by the from_what argument. A from_what value of 0 measures from the beginning of the file, 1 uses the curren... | f.seek(0) | 1_Basics.ipynb | iutzeler/Introduction-to-Python-for-Data-Sciences | mit |
f.readline() reads a single line from the file; a newline character (\n) is left at the end of the string | f.readline()
f.readline() | 1_Basics.ipynb | iutzeler/Introduction-to-Python-for-Data-Sciences | mit |
For reading lines from a file, you can loop over the file object. This is memory efficient, fast, and leads to simple code: | f.seek(0)
for line in f:
print(line)
f.close() | 1_Basics.ipynb | iutzeler/Introduction-to-Python-for-Data-Sciences | mit |
6- Exercises
Exercise 1: Odd or Even
The code snippet below enable the user to enter a number. Check if this number is odd or even. Optionnaly, handle bad inputs (character, float, signs, etc) | num = input("Enter a number: ")
print(num) | 1_Basics.ipynb | iutzeler/Introduction-to-Python-for-Data-Sciences | mit |
Exercise 2: Fibonacci
The Fibonacci seqence is a sequence of numbers where the next number in the sequence is the sum of the previous two numbers in the sequence. The sequence looks like this: 1, 1, 2, 3, 5, 8, 13. Write a function that generate a given number of elements of the Fibonacci sequence.
Exercise 3: Imp... | def quicksort(l):
# ...
return None
res = quicksort([-2, 3, 5, 1, 3])
print(res) | 1_Basics.ipynb | iutzeler/Introduction-to-Python-for-Data-Sciences | mit |
Score test set with our text classification model
Using our new model, we can score the set of test comments for toxicity. | TOXICITY_COLUMN = 'toxicity'
TEXT_COLUMN = 'phrase'
predict_fn = tf.contrib.predictor.from_saved_model(
'tfjs_model', signature_def_key='predict')
sp = sentencepiece.SentencePieceProcessor()
sp.Load('tfjs_model/assets/universal_encoder_8k_spm.model')
def progress(value, max=100):
return HTML("""
<progr... | experiments/tf_trainer/tf_hub_tfjs/notebook/BiasEvaluation.ipynb | conversationai/conversationai-models | apache-2.0 |
Evaluate the overall ROC-AUC
This calculates the models performance on the entire test set using the ROC-AUC metric. | SUBGROUP_AUC = 'subgroup_auc'
BACKGROUND_POSITIVE_SUBGROUP_NEGATIVE_AUC = 'background_positive_subgroup_negative_auc'
BACKGROUND_NEGATIVE_SUBGROUP_POSITIVE_AUC = 'background_negative_subgroup_positive_auc'
def compute_auc(y_true, y_pred):
try:
return metrics.roc_auc_score(y_true, y_pred)
except ValueError:
... | experiments/tf_trainer/tf_hub_tfjs/notebook/BiasEvaluation.ipynb | conversationai/conversationai-models | apache-2.0 |
Plot a heatmap of bias metrics
Plot a heatmap of the bias metrics. Higher scores indicate better results.
* Subgroup AUC measures the ability to separate toxic and non-toxic comments for this identity.
* Negative cross AUC measures the ability to separate non-toxic comments for this identity from toxic comments from t... | def plot_auc_heatmap(bias_metrics_results, models):
metrics_list = [SUBGROUP_AUC, BACKGROUND_POSITIVE_SUBGROUP_NEGATIVE_AUC, BACKGROUND_NEGATIVE_SUBGROUP_POSITIVE_AUC]
df = bias_metrics_results.set_index('subgroup')
columns = []
vlines = [i * len(models) for i in range(len(metrics_list))]
for metric in metric... | experiments/tf_trainer/tf_hub_tfjs/notebook/BiasEvaluation.ipynb | conversationai/conversationai-models | apache-2.0 |
Numpy has many built-in functions and capabilities. We won't cover them all but instead we will focus on some of the most important aspects of Numpy: vectors,arrays,matrices, and number generation. Let's start by discussing arrays.
Numpy Arrays
NumPy arrays are the main way we will use Numpy throughout the course. Nump... | my_list = [1,2,3]
my_list
np.array(my_list)
my_matrix = [[1,2,3],[4,5,6],[7,8,9]]
my_matrix
np.array(my_matrix) | udemy_ml_bootcamp/Python-for-Data-Analysis/NumPy/NumPy Arrays.ipynb | AtmaMani/pyChakras | mit |
Built-in Methods
There are lots of built-in ways to generate Arrays
arange
Return evenly spaced values within a given interval. | np.arange(0,10)
np.arange(0,11,2) | udemy_ml_bootcamp/Python-for-Data-Analysis/NumPy/NumPy Arrays.ipynb | AtmaMani/pyChakras | mit |
zeros and ones
Generate arrays of zeros or ones | np.zeros(3)
np.zeros((5,5))
np.ones(3)
np.ones((3,3)) | udemy_ml_bootcamp/Python-for-Data-Analysis/NumPy/NumPy Arrays.ipynb | AtmaMani/pyChakras | mit |
linspace
Return evenly spaced numbers over a specified interval. | np.linspace(0,10,3)
np.linspace(0,10,50) | udemy_ml_bootcamp/Python-for-Data-Analysis/NumPy/NumPy Arrays.ipynb | AtmaMani/pyChakras | mit |
eye
Creates an identity matrix | np.eye(4) | udemy_ml_bootcamp/Python-for-Data-Analysis/NumPy/NumPy Arrays.ipynb | AtmaMani/pyChakras | mit |
Random
Numpy also has lots of ways to create random number arrays:
rand
Create an array of the given shape and populate it with
random samples from a uniform distribution
over [0, 1). | np.random.rand(2)
np.random.rand(5,5) | udemy_ml_bootcamp/Python-for-Data-Analysis/NumPy/NumPy Arrays.ipynb | AtmaMani/pyChakras | mit |
randn
Return a sample (or samples) from the "standard normal" distribution. Unlike rand which is uniform: | np.random.randn(2)
np.random.randn(5,5) | udemy_ml_bootcamp/Python-for-Data-Analysis/NumPy/NumPy Arrays.ipynb | AtmaMani/pyChakras | mit |
randint
Return random integers from low (inclusive) to high (exclusive). | np.random.randint(1,100)
np.random.randint(1,100,10) | udemy_ml_bootcamp/Python-for-Data-Analysis/NumPy/NumPy Arrays.ipynb | AtmaMani/pyChakras | mit |
Array Attributes and Methods
Let's discuss some useful attributes and methods or an array: | arr = np.arange(25)
ranarr = np.random.randint(0,50,10)
arr
ranarr | udemy_ml_bootcamp/Python-for-Data-Analysis/NumPy/NumPy Arrays.ipynb | AtmaMani/pyChakras | mit |
Reshape
Returns an array containing the same data with a new shape. | arr.reshape(5,5) | udemy_ml_bootcamp/Python-for-Data-Analysis/NumPy/NumPy Arrays.ipynb | AtmaMani/pyChakras | mit |
max,min,argmax,argmin
These are useful methods for finding max or min values. Or to find their index locations using argmin or argmax | ranarr
ranarr.max()
ranarr.argmax()
ranarr.min()
ranarr.argmin() | udemy_ml_bootcamp/Python-for-Data-Analysis/NumPy/NumPy Arrays.ipynb | AtmaMani/pyChakras | mit |
Shape
Shape is an attribute that arrays have (not a method): | # Vector
arr.shape
# Notice the two sets of brackets
arr.reshape(1,25)
arr.reshape(1,25).shape
arr.reshape(25,1)
arr.reshape(25,1).shape | udemy_ml_bootcamp/Python-for-Data-Analysis/NumPy/NumPy Arrays.ipynb | AtmaMani/pyChakras | mit |
dtype
You can also grab the data type of the object in the array: | arr.dtype | udemy_ml_bootcamp/Python-for-Data-Analysis/NumPy/NumPy Arrays.ipynb | AtmaMani/pyChakras | mit |
Vector plotting | plt.quiver(0,0,3,4)
plt.show()
plt.quiver(0,0,3,4, scale_units='xy', angles='xy', scale=1)
plt.show()
plt.quiver(0,0,3,4, scale_units='xy', angles='xy', scale=1)
plt.xlim(-10,10)
plt.ylim(-10,10)
plt.show()
plt.quiver(0,0,3,4, scale_units='xy', angles='xy', scale=1, color='r')
plt.quiver(0,0,-3,4, scale_units='xy', ... | 0207_Vectors-1549598493596.ipynb | bekbote/project_repository | apache-2.0 |
Vector addition and subtraction | vecs = [np.asarray([0,0,3,4]), np.asarray([0,0,-3,4]), np.asarray([0,0,-3,-2]), np.asarray([0,0,4,-1])]
plot_vectors([vecs[0], vecs[3]])
vecs[0] + vecs[3]
plot_vectors([vecs[0], vecs[3], vecs[0] + vecs[3]])
plot_vectors([vecs[0], vecs[0], vecs[0] + vecs[0]])
plot_vectors([vecs[0], vecs[3], vecs[0] - vecs[3]])
plo... | 0207_Vectors-1549598493596.ipynb | bekbote/project_repository | apache-2.0 |
Vector dot product | vecs = [np.asarray([0,0,5,4]), np.asarray([0,0,-3,4]), np.asarray([0,0,-3,-2]), np.asarray([0,0,4,-1])]
plot_vectors(vecs)
a = np.asarray([5, 4])
b = np.asarray([-3, -2]) | 0207_Vectors-1549598493596.ipynb | bekbote/project_repository | apache-2.0 |
$\vec{a}\cdot\vec{b} = |\vec{a}| |\vec{b}| \cos(\theta) = a_x b_x + a_y b_y$ | a_dot_b = np.dot(a, b)
print(a_dot_b) | 0207_Vectors-1549598493596.ipynb | bekbote/project_repository | apache-2.0 |
$a_b = |\vec{a}| \cos(\theta) = |\vec{a}|\frac{\vec{a}\cdot\vec{b}}{|\vec{a}||\vec{b}|} = \frac{\vec{a}\cdot\vec{b}}{|\vec{b}|}$ | a_b = np.dot(a, b)/np.linalg.norm(b)
print(a_b) | 0207_Vectors-1549598493596.ipynb | bekbote/project_repository | apache-2.0 |
$\vec{a_b} = a_b \hat{b} = a_b \frac{\vec{b}}{|\vec{b}|}$ | vec_a_b = (a_b/np.linalg.norm(b))*b
print(vec_a_b)
plot_vectors([np.asarray([0,0,3,4]), np.asarray([0,0,4,-1]), np.asarray([0, 0, 1.88235294, -0.47058824])]) | 0207_Vectors-1549598493596.ipynb | bekbote/project_repository | apache-2.0 |
Linear combination
$\vec{c} = w_1 \vec{a} + w_2 \vec{b}$ | def plot_linear_combination(a, b, w1, w2):
plt.quiver(0,0,a[0],a[1], scale_units='xy', angles='xy', scale=1, color='r')
plt.quiver(0,0,b[0],b[1], scale_units='xy', angles='xy', scale=1, color='b')
c = w1 * a + w2 * b
plt.quiver(0,0,c[0],c[1], scale_units='xy', angles='xy', scale=1, color='g')
plt.xl... | 0207_Vectors-1549598493596.ipynb | bekbote/project_repository | apache-2.0 |
Explore the Data
Play around with view_sentence_range to view different parts of the data. | view_sentence_range = (10, 20)
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
import numpy as np
print('Dataset Stats')
print('Roughly the number of unique words: {}'.format(len({word: None for word in text.split()})))
scenes = text.split('\n\n')
print('Number of scenes: {}'.format(len(scenes)))
sentence_count_scene = [s... | tv-script-generation/.ipynb_checkpoints/dlnd_tv_script_generation-Copy1-checkpoint.ipynb | herruzojm/udacity-deep-learning | mit |
Implement Preprocessing Functions
The first thing to do to any dataset is preprocessing. Implement the following preprocessing functions below:
- Lookup Table
- Tokenize Punctuation
Lookup Table
To create a word embedding, you first need to transform the words to ids. In this function, create two dictionaries:
- Dict... | import numpy as np
import problem_unittests as tests
from collections import Counter
def create_lookup_tables(text):
"""
Create lookup tables for vocabulary
:param text: The text of tv scripts split into words
:return: A tuple of dicts (vocab_to_int, int_to_vocab)
"""
word_counts = Counter(text... | tv-script-generation/.ipynb_checkpoints/dlnd_tv_script_generation-Copy1-checkpoint.ipynb | herruzojm/udacity-deep-learning | mit |
Tokenize Punctuation
We'll be splitting the script into a word array using spaces as delimiters. However, punctuations like periods and exclamation marks make it hard for the neural network to distinguish between the word "bye" and "bye!".
Implement the function token_lookup to return a dict that will be used to token... | def token_lookup():
"""
Generate a dict to turn punctuation into a token.
:return: Tokenize dictionary where the key is the punctuation and the value is the token
"""
punctuation = {}
punctuation['.'] = '<PERIOD>'
punctuation[','] = '<COMMA>'
punctuation['"'] = '<QUOTATION_MARK>'
pun... | tv-script-generation/.ipynb_checkpoints/dlnd_tv_script_generation-Copy1-checkpoint.ipynb | herruzojm/udacity-deep-learning | mit |
Input
Implement the get_inputs() function to create TF Placeholders for the Neural Network. It should create the following placeholders:
- Input text placeholder named "input" using the TF Placeholder name parameter.
- Targets placeholder
- Learning Rate placeholder
Return the placeholders in the following the tuple (... | def get_inputs():
"""
Create TF Placeholders for input, targets, and learning rate.
:return: Tuple (input, targets, learning rate)
"""
inputs = tf.placeholder(tf.int32, [None, None], name='input')
targets = tf.placeholder(tf.int32, [None, None])
learning_rate = tf.placeholder(tf.int32)
r... | tv-script-generation/.ipynb_checkpoints/dlnd_tv_script_generation-Copy1-checkpoint.ipynb | herruzojm/udacity-deep-learning | mit |
Build RNN Cell and Initialize
Stack one or more BasicLSTMCells in a MultiRNNCell.
- The Rnn size should be set using rnn_size
- Initalize Cell State using the MultiRNNCell's zero_state() function
- Apply the name "initial_state" to the initial state using tf.identity()
Return the cell and initial state in the follo... | lstm_layers = 1
def get_init_cell(batch_size, rnn_size):
"""
Create an RNN Cell and initialize it.
:param batch_size: Size of batches
:param rnn_size: Size of RNNs
:return: Tuple (cell, initialize state)
"""
lstm = tf.contrib.rnn.BasicLSTMCell(rnn_size)
cell = tf.contrib.rnn.MultiRNNCel... | tv-script-generation/.ipynb_checkpoints/dlnd_tv_script_generation-Copy1-checkpoint.ipynb | herruzojm/udacity-deep-learning | mit |
Word Embedding
Apply embedding to input_data using TensorFlow. Return the embedded sequence. | def get_embed(input_data, vocab_size, embed_dim):
"""
Create embedding for <input_data>.
:param input_data: TF placeholder for text input.
:param vocab_size: Number of words in vocabulary.
:param embed_dim: Number of embedding dimensions
:return: Embedded input.
"""
return embe... | tv-script-generation/.ipynb_checkpoints/dlnd_tv_script_generation-Copy1-checkpoint.ipynb | herruzojm/udacity-deep-learning | mit |
Build the Neural Network
Apply the functions you implemented above to:
- Apply embedding to input_data using your get_embed(input_data, vocab_size, embed_dim) function.
- Build RNN using cell and your build_rnn(cell, inputs) function.
- Apply a fully connected layer with a linear activation and vocab_size as the number... | def build_nn(cell, rnn_size, input_data, vocab_size):
"""
Build part of the neural network
:param cell: RNN cell
:param rnn_size: Size of rnns
:param input_data: Input data
:param vocab_size: Vocabulary size
:return: Tuple (Logits, FinalState)
"""
# TODO: Implement Function
retur... | tv-script-generation/.ipynb_checkpoints/dlnd_tv_script_generation-Copy1-checkpoint.ipynb | herruzojm/udacity-deep-learning | mit |
Batches
Implement get_batches to create batches of input and targets using int_text. The batches should be a Numpy array with the shape (number of batches, 2, batch size, sequence length). Each batch contains two elements:
- The first element is a single batch of input with the shape [batch size, sequence length]
- Th... | def get_batches(int_text, batch_size, seq_length):
"""
Return batches of input and target
:param int_text: Text with the words replaced by their ids
:param batch_size: The size of batch
:param seq_length: The length of sequence
:return: Batches as a Numpy array
"""
# TODO: Implement Func... | tv-script-generation/.ipynb_checkpoints/dlnd_tv_script_generation-Copy1-checkpoint.ipynb | herruzojm/udacity-deep-learning | mit |
Neural Network Training
Hyperparameters
Tune the following parameters:
Set num_epochs to the number of epochs.
Set batch_size to the batch size.
Set rnn_size to the size of the RNNs.
Set seq_length to the length of sequence.
Set learning_rate to the learning rate.
Set show_every_n_batches to the number of batches the ... | # Number of Epochs
num_epochs = None
# Batch Size
batch_size = None
# RNN Size
rnn_size = None
# Sequence Length
seq_length = None
# Learning Rate
learning_rate = None
# Show stats for every n number of batches
show_every_n_batches = None
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
save_dir = '.... | tv-script-generation/.ipynb_checkpoints/dlnd_tv_script_generation-Copy1-checkpoint.ipynb | herruzojm/udacity-deep-learning | mit |
(OPTIONAL) Building plotting hooks for jupyter notebooks
You can skip this part, if this is not relevant for you. The next code block is only relevant important for logging in notebooks. However, it might be an interesting example for how to create custom tf.SessionRunHooks. We define a hook for Tensorflow and call it ... | from matplotlib import pyplot as plt
from IPython import display
%matplotlib inline
class NotebookLoggingHook(tf.train.SessionRunHook):
def __init__(self, fetches):
self.fetches = fetches
self.loss = []
def before_run(self, run_context):
# Add the tensors to fetch to the sess... | examples/tutorials/03_building_a_model_fn.ipynb | DLTK/DLTK | apache-2.0 |
Building a model_fn
Here, we define a model function that requires to have the arguments features, labels, mode, and params. The function has to return a tf.estimator.EstimatorSpec that is used by a tf.estimator.Estimator to perform training, predtion, etc. The EstimatorSpec holds additional information, such as the op... | # Create a `NotebookLoggingHook`
nl_hook = NotebookLoggingHook(None)
hooks = [nl_hook]
# Create the model function with its required arguments `features`, `labels`,
# `mode`, and `params`:
def model_fn(features, labels, mode, params):
# 1. Define a model to train and its outputs. It can be any model you
... | examples/tutorials/03_building_a_model_fn.ipynb | DLTK/DLTK | apache-2.0 |
Putting it all together to train a model
Let's create a dltk reader as in dltk/examples/tutorials/01_Reading_data.ipynb and pass the file_references as None (see the test image creator above): | from dltk.io.abstract_reader import Reader
# Set up a data reader to handle the file i/o.
reader_example_shapes = {'features': {'x': [1, im_width, im_height, 1]},
'labels': {'y': [1, im_width, im_height]}}
reader = Reader(read_fn, {'features': {'x': tf.float32},
'la... | examples/tutorials/03_building_a_model_fn.ipynb | DLTK/DLTK | apache-2.0 |
Now, we use our custom model_fn to build a tf.estimator.Estimator. It does automatic checkpointing if you set a model_dir and the params argument is passed directly to the model_fn: | nn = tf.estimator.Estimator(model_fn=model_fn,
model_dir=None,
params={"learning_rate": 0.001}) | examples/tutorials/03_building_a_model_fn.ipynb | DLTK/DLTK | apache-2.0 |
Finally, we train using the estimator by simply calling the estimator.train function, passing the input_fn created and the custom NotebookLoggingHook for logging. Here, we train the model for 200 steps: | _ = nn.train(input_fn=input_fn, hooks=hooks + [qinit_hook], steps=200) | examples/tutorials/03_building_a_model_fn.ipynb | DLTK/DLTK | apache-2.0 |
Similarly, we can evaluate the model: | nl_hook.loss = []
eval_input_fn, eval_qinit_hook = reader.get_inputs(file_references=None,
mode=tf.estimator.ModeKeys.EVAL,
example_shapes=reader_example_shapes)
_ = nn.evaluate(input_fn=eval_input_fn, hooks=hooks + ... | examples/tutorials/03_building_a_model_fn.ipynb | DLTK/DLTK | apache-2.0 |
Graphical excellence and integrity
Find a data-focused visualization on one of the following websites that is a positive example of the principles that Tufte describes in The Visual Display of Quantitative Information.
Vox
Upshot
538
BuzzFeed
Upload the image for the visualization to this directory and display the im... | # Add your filename and uncomment the following line:
Image(filename='drugs_and_poverty_Chicago.0.png') | assignments/assignment04/TheoryAndPracticeEx01.ipynb | ozorich/phys202-2015-work | mit |
math | # So, let's use some functions from math library
import math
#Square Root
n = input('Enter a value: ')
print 'The square root of {} is {}'.format(n,math.sqrt(n))
# Trigonometry
n = input('Enter a value: ')
print 'The sine of {} is {}'.format(n,math.sin(n))
print 'The cossine of {} is {}'.format(n,math.cos(n))
print ... | felis_python1/lectures/03_Libraries and Conditions.ipynb | mmaelicke/felis_python1 | mit |
That are other calculations that can be performed. However, it is necessary to have some data structure. We will see that again in further sections.
os | # Let's import the library first
import os
# getcwd and chdir
# this function sets your home directory
path = r"C:\Users\Pereira\Desktop"
print 'Former working environment:',os.getcwd()# get the path ot the current working directory
os.chdir(path)
print 'Current working environment:',os.getcwd()
# mkdir
# this funct... | felis_python1/lectures/03_Libraries and Conditions.ipynb | mmaelicke/felis_python1 | mit |
<body>
<b>The os.open function has different modes in order to do different things.</b>
<p>‘r’ – Read mode which is used when the file is only being read </p>
<p></p>
<p>‘w’ – Write mode which is used to edit and write new information to the file (any existing files with the same name will be erased when this mode is a... | # listdir
# provide a list of files in a determined path given
path = r'F:\Joao\Dropbox\Python_I\02_SS_2017\material\exercises'
os.listdir(path) | felis_python1/lectures/03_Libraries and Conditions.ipynb | mmaelicke/felis_python1 | mit |
glob | from glob import glob
paths = glob(r'F:\Joao\Dropbox\Python_I\02_SS_2017\material\exercises\*1.docx')
# Don't worry if you don't get that. We will talk about it next section.
for path in paths:
print path | felis_python1/lectures/03_Libraries and Conditions.ipynb | mmaelicke/felis_python1 | mit |
time | import time
print 'GMT time\n',time.gmtime()
print '\nLocal time\n',time.localtime()
time.asctime()
time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime())
# https://docs.python.org/2/library/time.html#time.strftime
time.gmtime() | felis_python1/lectures/03_Libraries and Conditions.ipynb | mmaelicke/felis_python1 | mit |
datetime | from datetime import datetime
startTime = datetime.now()
len(str(2**10000000))
print datetime.now() - startTime | felis_python1/lectures/03_Libraries and Conditions.ipynb | mmaelicke/felis_python1 | mit |
random | import random
random.randint(0,100) | felis_python1/lectures/03_Libraries and Conditions.ipynb | mmaelicke/felis_python1 | mit |
Conditions
Conditions are already pretty well known, having the common sysntax 'if' and 'else'. In Python that is not different, but with the addition of another one called 'elif'. Now let's see how to use it in Python. But before we talk about conditions, we have to adress operators and boolean variables.
In Python we... | print 4 > 2
print 2 < 3.7
print 2 > 5
print 2 == 7 # Be careful here
print 5 == 5 # Be careful here | felis_python1/lectures/03_Libraries and Conditions.ipynb | mmaelicke/felis_python1 | mit |
When working with 'if' and 'else' statements, conditions are assessed generating boolean variables as result. Let's see. | a = 4
b = 'Python'
if a == b: # watch the obligatory element ':'
print 'Variable a is equal variable b.'
else: # watch the obligatory element ':'
print 'Variable a is different than variable b.'
if a != b: # watch the obligatory element ':'
print 'Variable a is different than variable b.'
else: # watch the... | felis_python1/lectures/03_Libraries and Conditions.ipynb | mmaelicke/felis_python1 | mit |
Now, let's take a look how to use the 'elif'. Working with intervals is a good way to understand it. | # The 'elif' functions allows us to add extra conditions to our if statement.
a = 5
b = 2
if a > b:
print 'The variable a is bigger than the variable b.'
elif a < b:
print 'The variable a is smaller than the variable b.'
else:
print 'The variable a is equal to the variable b.'
# Let's make the example bef... | felis_python1/lectures/03_Libraries and Conditions.ipynb | mmaelicke/felis_python1 | mit |
Python still have other operators called 'not', 'and' and 'or' (NAO). An easy way to understand is to use boolean variables. Let's try. | # Let's compare True and False using the operators.
print 'True and True is',True and True
print '0 and True is',False and True
print 'False and False is',False and False
print 'True or True is',True or True
print '1 or 0 is',False or True
print '0 or False is',False or False
print 'not True is',not True
print 'not 0 i... | felis_python1/lectures/03_Libraries and Conditions.ipynb | mmaelicke/felis_python1 | mit |
2 - Dataset
First, let's get the dataset you will work on. The following code will load a "flower" 2-class dataset into variables X and Y. | X, Y = load_planar_dataset()
# Y = Y[0,:] | coursera/deep-neural-network/quiz and assignments/Week 3/week3-Planar+data+classification+with+one+hidden+layer.ipynb | jinntrance/MOOC | cc0-1.0 |
Visualize the dataset using matplotlib. The data looks like a "flower" with some red (label y=0) and some blue (y=1) points. Your goal is to build a model to fit this data. | print(X.shape)
# Visualize the data:
plt.scatter(X[0, :], X[1, :], c=Y[0,], s=40, cmap=plt.cm.Spectral); | coursera/deep-neural-network/quiz and assignments/Week 3/week3-Planar+data+classification+with+one+hidden+layer.ipynb | jinntrance/MOOC | cc0-1.0 |
You have:
- a numpy-array (matrix) X that contains your features (x1, x2)
- a numpy-array (vector) Y that contains your labels (red:0, blue:1).
Lets first get a better sense of what our data is like.
Exercise: How many training examples do you have? In addition, what is the shape of the variables X and Y?
Hin... | ### START CODE HERE ### (≈ 3 lines of code)
shape_X = X.shape
shape_Y = Y.shape
m = shape_Y[1] # training set size
### END CODE HERE ###
print ('The shape of X is: ' + str(shape_X))
print ('The shape of Y is: ' + str(shape_Y))
print ('I have m = %d training examples!' % (m)) | coursera/deep-neural-network/quiz and assignments/Week 3/week3-Planar+data+classification+with+one+hidden+layer.ipynb | jinntrance/MOOC | cc0-1.0 |
Expected Output:
<table style="width:20%">
<tr>
<td>**shape of X**</td>
<td> (2, 400) </td>
</tr>
<tr>
<td>**shape of Y**</td>
<td>(1, 400) </td>
</tr>
<tr>
<td>**m**</td>
<td> 400 </td>
</tr>
</table>
3 - Simple Logistic Regression
Before building a full neural network, le... | # Train the logistic regression classifier
clf = sklearn.linear_model.LogisticRegressionCV();
clf.fit(X.T, Y[0,:].T); | coursera/deep-neural-network/quiz and assignments/Week 3/week3-Planar+data+classification+with+one+hidden+layer.ipynb | jinntrance/MOOC | cc0-1.0 |
You can now plot the decision boundary of these models. Run the code below. | # Plot the decision boundary for logistic regression
plot_decision_boundary(lambda x: clf.predict(x), X, Y[0,:])
plt.title("Logistic Regression")
# Print accuracy
LR_predictions = clf.predict(X.T)
print ('Accuracy of logistic regression: %d ' % float((np.dot(Y,LR_predictions) + np.dot(1-Y,1-LR_predictions))/float(Y.si... | coursera/deep-neural-network/quiz and assignments/Week 3/week3-Planar+data+classification+with+one+hidden+layer.ipynb | jinntrance/MOOC | cc0-1.0 |
Expected Output (these are not the sizes you will use for your network, they are just used to assess the function you've just coded).
<table style="width:20%">
<tr>
<td>**n_x**</td>
<td> 5 </td>
</tr>
<tr>
<td>**n_h**</td>
<td> 4 </td>
</tr>
<tr>
<td>**n_y**</td>
<td> 2 </td>
... | # GRADED FUNCTION: initialize_parameters
def initialize_parameters(n_x, n_h, n_y):
"""
Argument:
n_x -- size of the input layer
n_h -- size of the hidden layer
n_y -- size of the output layer
Returns:
params -- python dictionary containing your parameters:
W1 -- wei... | coursera/deep-neural-network/quiz and assignments/Week 3/week3-Planar+data+classification+with+one+hidden+layer.ipynb | jinntrance/MOOC | cc0-1.0 |
Expected Output:
<table style="width:90%">
<tr>
<td>**W1**</td>
<td> [[-0.00416758 -0.00056267]
[-0.02136196 0.01640271]
[-0.01793436 -0.00841747]
[ 0.00502881 -0.01245288]] </td>
</tr>
<tr>
<td>**b1**</td>
<td> [[ 0.]
[ 0.]
[ 0.]
[ 0.]] </td>
</tr>
<tr>
<td>**W2**</td>
<td>... | # GRADED FUNCTION: forward_propagation
def forward_propagation(X, parameters):
"""
Argument:
X -- input data of size (n_x, m)
parameters -- python dictionary containing your parameters (output of initialization function)
Returns:
A2 -- The sigmoid output of the second activation
cache ... | coursera/deep-neural-network/quiz and assignments/Week 3/week3-Planar+data+classification+with+one+hidden+layer.ipynb | jinntrance/MOOC | cc0-1.0 |
Expected Output:
<table style="width:55%">
<tr>
<td> -0.000499755777742 -0.000496963353232 0.000438187450959 0.500109546852 </td>
</tr>
</table>
Now that you have computed $A^{[2]}$ (in the Python variable "A2"), which contains $a^{2}$ for every example, you can compute the cost function as follows:
$$J = - \... | # GRADED FUNCTION: compute_cost
def compute_cost(A2, Y, parameters):
"""
Computes the cross-entropy cost given in equation (13)
Arguments:
A2 -- The sigmoid output of the second activation, of shape (1, number of examples)
Y -- "true" labels vector of shape (1, number of examples)
paramete... | coursera/deep-neural-network/quiz and assignments/Week 3/week3-Planar+data+classification+with+one+hidden+layer.ipynb | jinntrance/MOOC | cc0-1.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.