markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Decomposition of qutrit three-outcome, trace-one POVMS into projective measurements
We implemented the constructive strategy to find a projective decomposition for trace-one qutrit measurements $\mathbf{M}\in\mathcal{P}_1(3,3)$ we described in Appendix D.
First we define a function to generate a random trace-1 POVM. Th... | from qutip import rand_unitary
def get_random_trace_one_povm(dim=3):
U = rand_unitary(dim)
M = [U[:, i]*dag(U[:, i]) for i in range(dim)]
for _ in range(dim-1):
U = rand_unitary(dim)
r = random.random()
for i in range(dim):
M[i] = r*M[i] + (1-r)*U[:, i]*dag(U[:, i])
... | Simulating_POVMs.ipynb | peterwittek/ipython-notebooks | gpl-3.0 |
Then we decompose a random POVM following the cascade of "rank reductions" described in Appendix D, and check the ranks: | M = get_random_trace_one_povm()
print("Rank of POVM: ", check_ranks(M))
coefficients, projective_measurements = decomposePovmToProjective(M) | Simulating_POVMs.ipynb | peterwittek/ipython-notebooks | gpl-3.0 |
As a sanity check, we look at the ranks of the effects of the individual projective measurements. We must point out that the numerical calculations occasionally fail, and we set the tolerance in rank calculations high. | print("Ranks of projective measurements: ")
for measurement in projective_measurements:
print(check_ranks(measurement, tolerance=0.01)) | Simulating_POVMs.ipynb | peterwittek/ipython-notebooks | gpl-3.0 |
We show that the projective measurements indeed return the POVM: | N = coefficients[0]*projective_measurements[0] + \
coefficients[1]*(coefficients[2]*projective_measurements[1] +
coefficients[3]*(coefficients[4]*(coefficients[6]*projective_measurements[2] +
coefficients[7]*projective_measurements[3]) +
coefficients[5]*(coefficients[8]*projective_measurements[4] +
... | Simulating_POVMs.ipynb | peterwittek/ipython-notebooks | gpl-3.0 |
Load the weight matrices from the training | #Weight matrices generated by the neural network after training
#Maps the label vectors to the neuron activity of the ensemble
label_weights = cPickle.load(open("label_weights1000.p", "rb"))
#Maps the activity of the neurons to the visual representation of the image
activity_to_img_weights = cPickle.load(open("activit... | Project/trained_mental_scaling_testing.ipynb | science-of-imagination/nengo-buffer | gpl-3.0 |
Visualize the digit from one hot representation through the activity weight matrix to the image representation
- Image is average digit from mnist dataset | #Change this to imagine different digits
imagine = ZERO
#Can also imagine combitnations of numbers (ZERO + ONE)
#Label to activity
test_activity = np.dot(imagine,label_weights)
#Image decoded
test_output_img = np.dot(test_activity, activity_to_img_weights)
plt.imshow(test_output_img.reshape(28,28),cmap='gray')
plt.s... | Project/trained_mental_scaling_testing.ipynb | science-of-imagination/nengo-buffer | gpl-3.0 |
Visualize the rotation of the image using the weight matrix from activity to activity
- does not use the weight matrix used on the recurrent connection | #Change this to visualize different digits
imagine = ZERO
#How long the animation should go for
frames=5
#Make a list of the activation of rotated images and add first frame
rot_seq = []
rot_seq.append(np.dot(imagine,label_weights)) #Map the label vector to the activity vector
test_output_img = np.dot(rot_seq[0], ac... | Project/trained_mental_scaling_testing.ipynb | science-of-imagination/nengo-buffer | gpl-3.0 |
1.2.3 Write your own documentations | def isprime(n):
"""Determine if a given number is a prime number"""
for x in range(2, n-1):
if n % x == 0: #if n modulo x equals 0
return False #then n is not a prime number
return True
isprime?? | talks/01-pythonbasics-builtins.ipynb | debsankha/network_course_python | gpl-2.0 |
1.2.4 Inline plots & interactive widgets | %matplotlib inline
import pylab as pl
import numpy as np
from IPython.html.widgets import interact
def plot(frequency):
x = np.arange(1000)
pl.plot(x, np.sin(2*np.pi*frequency*x/1000))
interact(plot, frequency=(0,20,1)) | talks/01-pythonbasics-builtins.ipynb | debsankha/network_course_python | gpl-2.0 |
2. Short tutorial on python
2.1 datatypes and operators
2.1.1 integer, float, strings | #name = object
a = 17
b = 3.14
c = "bla"
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c)) | talks/01-pythonbasics-builtins.ipynb | debsankha/network_course_python | gpl-2.0 |
2.1.2 Assignments | a = 17
a = "Used names can always be reassigned to other objects regardles of their data type!"
print(a) | talks/01-pythonbasics-builtins.ipynb | debsankha/network_course_python | gpl-2.0 |
2.1.3 Conversion of datatypes: | print(int(5.5))
print(float('5.23'))
print(str(12))
print(bool('True')) | talks/01-pythonbasics-builtins.ipynb | debsankha/network_course_python | gpl-2.0 |
2.1.4 Arithmetic and operators
+
-
*
/
// (integer division)
% (modulo operator)
** (power) | print(x+y)
print("bla" + "bla")
print(x/y)
print(x*2)
print('bla'*3)
print(x/2)
print(x**3) #the exponentiation operator
print(x%2) #the remainder operator | talks/01-pythonbasics-builtins.ipynb | debsankha/network_course_python | gpl-2.0 |
2.2 Conditions and control statements (if, while)
2.2.1 Comparison operators:
| Operator | True, if |
| ------------- |:-------------:|
| a == b | a equals b |
| a > b | a is larger than b |
| a < b | a is smaller than b |
| a >= b | a is larger than b or equals b |
| a <... | print(x==y)
print(x==5) | talks/01-pythonbasics-builtins.ipynb | debsankha/network_course_python | gpl-2.0 |
2.2.2 is operator | x = 3
y = 3
x is y | talks/01-pythonbasics-builtins.ipynb | debsankha/network_course_python | gpl-2.0 |
'==' compares values while 'is' compares identities | x = [1]
y = [1]
x is y | talks/01-pythonbasics-builtins.ipynb | debsankha/network_course_python | gpl-2.0 |
But: | x==y | talks/01-pythonbasics-builtins.ipynb | debsankha/network_course_python | gpl-2.0 |
Warning: do not check equality of two floats (finite precision!!) | from math import sin, pi
sin(2*pi)==0 | talks/01-pythonbasics-builtins.ipynb | debsankha/network_course_python | gpl-2.0 |
2.2.3 If ... else ... | number_of_people = 6
if number_of_people < 5:
print('Not enough people to play this game.')
elif number_of_people < 10:
print('More would be better, but its sufficient.')
elif number_of_people < 20:
print('Perfect! Enjoy!')
elif number_of_people < 30:
print('Less would be better, but it will work someh... | talks/01-pythonbasics-builtins.ipynb | debsankha/network_course_python | gpl-2.0 |
Conditional expressions: | x = 12
#the long version:
if x%2==0:
message = "Even."
else:
message = "Odd."
print(message)
#the short version:
print( "Even." if x%2==0 else "Odd." ) | talks/01-pythonbasics-builtins.ipynb | debsankha/network_course_python | gpl-2.0 |
2.3 While loops: | value = 17
while value < 21:
print(value)
value = value + 1
value = 17
max_value = 30
while True:
value = value + 1
if value > max_value:
break #stop here and escape the while loop
elif value%2==0:
continue #stop here and continue the while loop
print(va... | talks/01-pythonbasics-builtins.ipynb | debsankha/network_course_python | gpl-2.0 |
2.3.1 Warning: Make sure that the condition gets True after a finite number of steps!
2.4 Sequences & for-loops
2.4.1 Sequences
| Sequence | mutable? | data type |
| ------------- |:-------------:|:--------:|
| list | yes | arbitrary |
| tuple | no | arbitrary |
| s... | a = [1,2,3,4,5] #a list
b = (1,2,3,4,5) #a tuple
c = '12345' #a string | talks/01-pythonbasics-builtins.ipynb | debsankha/network_course_python | gpl-2.0 |
Since lists and tuples can contain arbitrary data types, they can be 'nested': | nested_list = [[1,2,3],[4,5,6],[7,8,9]] | talks/01-pythonbasics-builtins.ipynb | debsankha/network_course_python | gpl-2.0 |
All three sequence types (tuples, strings and lists) share much of their syntax and functionality. | print(len(a),len(b),len(c))
print( a + a )
print( b + b )
print( c + c ) | talks/01-pythonbasics-builtins.ipynb | debsankha/network_course_python | gpl-2.0 |
single items are accessible by their index (starting from 0): | print( a[0], b[1], c[2] ) | talks/01-pythonbasics-builtins.ipynb | debsankha/network_course_python | gpl-2.0 |
Negative indices are counted from the end (starting with -1) | print ( a[-1], b[-3] ) | talks/01-pythonbasics-builtins.ipynb | debsankha/network_course_python | gpl-2.0 |
A subset of items can be accessed by "slices".
Syntax: [I:J:K] means start from index I, stop at index J and take every K'th item. If I is omitted, start from the first item, if J is omitted, stop at the last item, and if K is omitted, take every item. | print( a[1:4] ) #get items from 1 to 4
print( a[3:5] ) #get items from 3 to 5
print( a[:4] ) #get items from 0 to 4
print( a[3:] ) #get items from 3 to the end
print( a[::2] ) #get every second item | talks/01-pythonbasics-builtins.ipynb | debsankha/network_course_python | gpl-2.0 |
The in-operator checks whether an item is in the sequence: | print((2,3) in (1,2,3,4,5))
print('cde' in 'abcdefgh') | talks/01-pythonbasics-builtins.ipynb | debsankha/network_course_python | gpl-2.0 |
2.4.2 Specialities of lists
2.4.2.1 In contrast to tuples and strings, lists are mutable. Items can be replaced, removed or added. | a = [1,2,3,4] #create list
a[2] = 12 #replace item 2 by value 12
a.append(34) #add value 34 to the end
a.extend([0,0,0]) #add several values to the end
a.pop() #remove last item
a.insert(3, 'blub')#insert object before index 3
a.reverse() #reverse list
print(a) | talks/01-pythonbasics-builtins.ipynb | debsankha/network_course_python | gpl-2.0 |
2.4.2.2 Warning: assignment to lists do not create a copy | s = [1,2]
t = s
t.append(99)
print(s, t) | talks/01-pythonbasics-builtins.ipynb | debsankha/network_course_python | gpl-2.0 |
2.4.3 Specialities of strings: | # Strings can be enlosed by both single quote and double quote.
s='My home'
t="My home"
s==t | talks/01-pythonbasics-builtins.ipynb | debsankha/network_course_python | gpl-2.0 |
strings can contain quotation marks themselves. single/double quotes become important then: | newstring="This is Mary's home"
anotherstring='And he said: "Let there be light"'
# And if you **really** need it, both single and double quotes:
huge_string="""This 'string' contains "both" types of quote""" | talks/01-pythonbasics-builtins.ipynb | debsankha/network_course_python | gpl-2.0 |
2.4.3.1 Strings have some nice methods | print(huge_string.upper())
print(huge_string.startswith('a'))
print(huge_string.find('contain'))
print(huge_string.split(' '))
print(huge_string.count('s')) | talks/01-pythonbasics-builtins.ipynb | debsankha/network_course_python | gpl-2.0 |
2.4.4 For-loops
Remember how while loops were prone to infinite loop bugs?
Python gives you a chance to avoid them in most cases: | i = 1
while i < 50:
if i%7 == 0:
print(i)
i += 1
for i in range(1, 50, 1):
if i%7 == 0:
print(i) | talks/01-pythonbasics-builtins.ipynb | debsankha/network_course_python | gpl-2.0 |
2.4.4.1 Works on strings, tuples: | count = 0
st = "home, sweet home"
for char in st:
if char == 'h':
count += 1
print("%c appears %d times in \"%s\""%('h', count, st)) | talks/01-pythonbasics-builtins.ipynb | debsankha/network_course_python | gpl-2.0 |
2.4.4.2 Did I tell you about string formatting? | print("%s is %d years old"%('John', 34))
print("{name} is {age} years old, {name} has 3 children".format(name='John', age=34)) | talks/01-pythonbasics-builtins.ipynb | debsankha/network_course_python | gpl-2.0 |
For-loops can not only iterate through sequences, but also through 'iterable' objects, like range(). | #Example: We want to sum up all numbers betwen 0 and 100.
#Instead of manually typing a list of all numbers, we can use range:
s = 0
for i in range(101):
s = s + i
print(s) | talks/01-pythonbasics-builtins.ipynb | debsankha/network_course_python | gpl-2.0 |
2.4.5 List comprehensions: A short way to create a sequence. | #long version: "for-loop"
li = []
for i in range(100):
li.append(i*2)
#short version:
li = [2*i for i in range(101)]
print(li) | talks/01-pythonbasics-builtins.ipynb | debsankha/network_course_python | gpl-2.0 |
List comprehensions can be used as a filter: | li = [1/i for i in range(101) if i != 0]
print(li) | talks/01-pythonbasics-builtins.ipynb | debsankha/network_course_python | gpl-2.0 |
Also to place a default value | li = [1/i if i!=0 else None for i in range(101) ]
print(li) | talks/01-pythonbasics-builtins.ipynb | debsankha/network_course_python | gpl-2.0 |
And to write insanely obtuse code and mess with your collaborators :D | nested_list = [[1,2], [3], [4,5,6]]
flattened_list = [item for sublist in nested_list for item in sublist]
print(flattened_list) | talks/01-pythonbasics-builtins.ipynb | debsankha/network_course_python | gpl-2.0 |
2.4.6 What are tuples for, you ask?
They are almost like lists, but immutable: | l = [1,2,3,4,5]
t = [1,2,3,4,5]
#or, simply:
t = tuple(l)
print(l[2:5])
print(t[2:5])
print(2 in l)
print(2 in t)
l[2] = 99
print(l)
t[2] = 99
print(t) | talks/01-pythonbasics-builtins.ipynb | debsankha/network_course_python | gpl-2.0 |
What's the use of immutability? glad you asked
2.4.7 dictionaries:
stores key->value pairs: | d={'germany':'berlin', 'france':'paris', 'poland':'warsaw', 'denmark':'copenhagen'}
d['germany'] | talks/01-pythonbasics-builtins.ipynb | debsankha/network_course_python | gpl-2.0 |
You can add keys anytime: | d['belgium']='brussels' | talks/01-pythonbasics-builtins.ipynb | debsankha/network_course_python | gpl-2.0 |
useful things you can do with dictionaries: | d.keys()
d.values() | talks/01-pythonbasics-builtins.ipynb | debsankha/network_course_python | gpl-2.0 |
Any datatype can be used as a key in dictionary, so long as it is hashable
Thumbrule: integer, float, tuple, string are OK; ~~list~~, other ~~dictionaries~~ are NOT OK | mycrazydict = {(1,3,7):'odd!', [2,4,6]: 'even!'} | talks/01-pythonbasics-builtins.ipynb | debsankha/network_course_python | gpl-2.0 |
2.5 functions: | def triple(x):
return x*3
triple(4) | talks/01-pythonbasics-builtins.ipynb | debsankha/network_course_python | gpl-2.0 |
Very important: writing documentation for your code | def triple(x):
"""
This function accepts a number, returns 3 times that number.
"""
return x*3
triple #Shift+tab shows documentation in ipython
help(triple) #this also works | talks/01-pythonbasics-builtins.ipynb | debsankha/network_course_python | gpl-2.0 |
when you pass any object to a function, any change done to the object will affect it globally: | def modify(l):
l.append(23)
return 0
l=[1,2,3]
modify(l)
print(l) | talks/01-pythonbasics-builtins.ipynb | debsankha/network_course_python | gpl-2.0 |
but reassignments inside the function is not reflected globally | def change(l):
l=[1,2,34]
return 0
mylist=[3,6]
change(mylist)
print mylist | talks/01-pythonbasics-builtins.ipynb | debsankha/network_course_python | gpl-2.0 |
2.6 Using modules
One of the most useful things about python is that there are tons of modules available, that do many of the tasks you might need to do: | import math
math.sin(0.1)
help(math) | talks/01-pythonbasics-builtins.ipynb | debsankha/network_course_python | gpl-2.0 |
We must first nagivate to the directory containing the spreadsheets, which for this notebook is the subdirectory 'files'. | # Import OS module to navigate directories
import os
# Change the directory to the excel file location, using relative and absolute paths as previously discussed.
os.chdir('files')
os.listdir() | AutomateTheBoringStuffWithPython/lesson42.ipynb | Vvkmnn/books | gpl-3.0 |
We must now open the workbook file. | workbook = openpyxl.load_workbook('example.xlsx')
type(workbook) | AutomateTheBoringStuffWithPython/lesson42.ipynb | Vvkmnn/books | gpl-3.0 |
Once the workbook is loaded, we can interact with specific sheets by loading them via workbook methods. | sheet = workbook.get_sheet_by_name('Sheet1')
type(sheet) | AutomateTheBoringStuffWithPython/lesson42.ipynb | Vvkmnn/books | gpl-3.0 |
We can also use the .get_sheet_names() method to print all sheet names, in case we aren't sure. | workbook.get_sheet_names() | AutomateTheBoringStuffWithPython/lesson42.ipynb | Vvkmnn/books | gpl-3.0 |
We can now interact with specific cells by creating cell objects, referenced via a sheet method. | # Just references an object exists; requires an additional method to interact with
sheet['A1'] | AutomateTheBoringStuffWithPython/lesson42.ipynb | Vvkmnn/books | gpl-3.0 |
The .value method returns the actual value in the cell. | cell = sheet['A1']
cell.value | AutomateTheBoringStuffWithPython/lesson42.ipynb | Vvkmnn/books | gpl-3.0 |
This particular cell returns a datetime reference from Excel via Python's own datetime module. A string value is available by passing into the str() function: | print(str(cell.value))
print(str(sheet['A1'].value)) | AutomateTheBoringStuffWithPython/lesson42.ipynb | Vvkmnn/books | gpl-3.0 |
All cell values inherit their data types from Excel. | print("The value in cell %s is '%s' and is type %s." %('A1', sheet['A1'].value, type(sheet['A1'].value)))
print("The value in cell %s is '%s' and is type %s." %('B1', sheet['B1'].value, type(sheet['B1'].value)))
print("The value in cell %s is '%s' and is type %s." %('C1', sheet['C1'].value, type(sheet['C1'].value))) | AutomateTheBoringStuffWithPython/lesson42.ipynb | Vvkmnn/books | gpl-3.0 |
You can also reference cells via rows and columns. Excel rows start at 1 and columns at A. | # B1 Cell
sheet.cell(row = 1, column = 2) | AutomateTheBoringStuffWithPython/lesson42.ipynb | Vvkmnn/books | gpl-3.0 |
This can be useful for iterative or looping operations. | for i in range(1,8):
print(i, sheet.cell(row=i, column=2).value) | AutomateTheBoringStuffWithPython/lesson42.ipynb | Vvkmnn/books | gpl-3.0 |
Al-Fe (Heat Capacity and Degree of Ordering)
Here we compute equilibrium thermodynamic properties in the Al-Fe system. We know that only B2 and liquid are stable in the temperature range of interest, but we just as easily could have included all the phases in the calculation using my_phases = list(db.phases.keys()). No... | db = Database('alfe_sei.TDB')
my_phases = ['LIQUID', 'B2_BCC']
eq = equilibrium(db, ['AL', 'FE', 'VA'], my_phases, {v.X('AL'): 0.25, v.T: (300, 2000, 50), v.P: 101325},
output=['heat_capacity', 'degree_of_ordering'])
print(eq) | examples/EquilibriumWithOrdering.ipynb | tkphd/pycalphad | mit |
We also compute degree of ordering at fixed temperature as a function of composition. | eq2 = equilibrium(db, ['AL', 'FE', 'VA'], 'B2_BCC', {v.X('AL'): (0,1,0.01), v.T: 700, v.P: 101325},
output='degree_of_ordering')
print(eq2) | examples/EquilibriumWithOrdering.ipynb | tkphd/pycalphad | mit |
Plots
Next we plot the degree of ordering versus temperature. We can see that the decrease in the degree of ordering is relatively steady and continuous. This is indicative of a second-order transition from partially ordered B2 to disordered bcc (A2). | plt.gca().set_title('Al-Fe: Degree of bcc ordering vs T [X(AL)=0.25]')
plt.gca().set_xlabel('Temperature (K)')
plt.gca().set_ylabel('Degree of ordering')
plt.gca().set_ylim((-0.1,1.1))
# Generate a list of all indices where B2 is stable
phase_indices = np.nonzero(eq.Phase.values == 'B2_BCC')
# phase_indices[2] refers t... | examples/EquilibriumWithOrdering.ipynb | tkphd/pycalphad | mit |
For the heat capacity curve shown below we notice a sharp increase in the heat capacity around 750 K. This is indicative of a magnetic phase transition and, indeed, the temperature at the peak of the curve coincides with 75% of 1043 K, the Curie temperature of pure Fe. (Pure bcc Al is paramagnetic so it has an effectiv... | plt.gca().set_title('Al-Fe: Heat capacity vs T [X(AL)=0.25]')
plt.gca().set_xlabel('Temperature (K)')
plt.gca().set_ylabel('Heat Capacity (J/mol-atom-K)')
# np.squeeze is used to remove all dimensions of size 1
# For a 1-D/"step" calculation, this aligns the temperature and heat capacity arrays
# In 2-D/"map" calculati... | examples/EquilibriumWithOrdering.ipynb | tkphd/pycalphad | mit |
To understand more about what's happening around 700 K, we plot the degree of ordering versus composition. Note that this plot excludes all other phases except B2_BCC. We observe the presence of disordered bcc (A2) until around 13% Al or Fe, when the phase begins to order. | plt.gca().set_title('Al-Fe: Degree of bcc ordering vs X(AL) [T=700 K]')
plt.gca().set_xlabel('X(AL)')
plt.gca().set_ylabel('Degree of ordering')
# Select all points in the datasets where B2_BCC is stable, dropping the others
eq2_b2_bcc = eq2.where(eq2.Phase == 'B2_BCC', drop=True)
plt.plot(eq2_b2_bcc['X_AL'].values, eq... | examples/EquilibriumWithOrdering.ipynb | tkphd/pycalphad | mit |
Al-Ni (Degree of Ordering) | db_alni = Database('NI_AL_DUPIN_2001.TDB')
phases = ['LIQUID', 'FCC_L12']
eq_alni = equilibrium(db_alni, ['AL', 'NI', 'VA'], phases, {v.X('AL'): 0.10, v.T: (300, 2500, 20), v.P: 101325},
output='degree_of_ordering')
print(eq_alni) | examples/EquilibriumWithOrdering.ipynb | tkphd/pycalphad | mit |
Plots
In the plot below we observe two phases designated FCC_L12. This is indicative of a miscibility gap. The ordered gamma-prime phase steadily decreases in amount with increasing temperature until it completely disappears around 750 K, leaving only the disordered gamma phase. | from pycalphad.plot.utils import phase_legend
phase_handles, phasemap = phase_legend(phases)
plt.gca().set_title('Al-Ni: Phase fractions vs T [X(AL)=0.1]')
plt.gca().set_xlabel('Temperature (K)')
plt.gca().set_ylabel('Phase Fraction')
plt.gca().set_ylim((0,1.1))
plt.gca().set_xlim((300, 2000))
for name in phases:
... | examples/EquilibriumWithOrdering.ipynb | tkphd/pycalphad | mit |
In the plot below we see that the degree of ordering does not change at all in each phase. There is a very abrupt disappearance of the completely ordered gamma-prime phase, leaving the completely disordered gamma phase. This is a first-order phase transition. | plt.gca().set_title('Al-Ni: Degree of fcc ordering vs T [X(AL)=0.1]')
plt.gca().set_xlabel('Temperature (K)')
plt.gca().set_ylabel('Degree of ordering')
plt.gca().set_ylim((-0.1,1.1))
# Generate a list of all indices where FCC_L12 is stable and ordered
L12_phase_indices = np.nonzero(np.logical_and((eq_alni.Phase.values... | examples/EquilibriumWithOrdering.ipynb | tkphd/pycalphad | mit |
This is what the labeled dataset looks like (To train on a different set of images, start with a BigQuery table that has these two columns). | import google.datalab.bigquery as bq
sql = "SELECT image_url, label FROM demos.coastline_images"
df = bq.Query(sql).execute().result().to_dataframe()
print 'Have a total of {} labeled images'.format(len(df))
df.head()
import matplotlib.pyplot as plt
import google.datalab.bigquery as bq
df = bq.Query("SELECT image_url... | quests/scientific/coastline.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
<h2> Create a smaller subset </h2>
<p>
Normally, of course, you would train on all your data. However, for learning purposes, we don't want you to wait hours at each stage. Therefore, let's intentionally use only a small subset of the entire dataset. When adapting this sample to work on your own data, skip over this se... | %bash
QUERY='SELECT image_url, label FROM '
TABLE="${PROJECT_ID}.demos.coastline_images"
SUBSAMPLE='WHERE (short_label = "2A" OR short_label = "3A" OR short_label = "9") AND MOD(ABS(FARM_FINGERPRINT(image_url)), 10) = 0'
bq rm -f demos.coastline_train
bq query --use_legacy_sql=false --destination_table=demos.coastline... | quests/scientific/coastline.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
<h2>Create bucket</h2>
<p>
Create a new bucket to hold your model etc. At the end of this lab, you can delete that bucket. | bucket = 'gs://' + datalab_project_id() + '-txf'
preprocessed_dir = bucket + '/preprocessed'
model_dir = bucket + '/model'
import subprocess
print 'Creating bucket named {}'.format(bucket)
subprocess.check_call('gsutil mb {}'.format(bucket).split()); | quests/scientific/coastline.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
<h2> Preprocessing </h2>
<p>
Now that we have the images in Cloud Storage and the labels in BigQuery, we can use Datalab's ML Toolbox to do transfer learning. This consists of three steps: (1) Preprocessing (2) Training, and (3) Deploying.
Preprocessing the images will resize the images, and do some image augmentation... | import mltoolbox.image.classification as model
from google.datalab.ml import *
import os
train_set = BigQueryDataSet("SELECT image_url, label FROM demos.coastline_train")
job = model.preprocess_async(train_set, preprocessed_dir, cloud={'max_num_workers': 4}) | quests/scientific/coastline.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
<b> Wait! </b>
You have two options to proceed:
<ol>
<li> Monitor the above preprocessing job, and proceed with this notebook only after prepocessing is complete. The preprocessing job took about 30 minutes for me. You can explicitly wait for the job completion by running the Option 1 cell. Make sure to uncomment the l... | # option 1 above. Wait for your preprocessing job to complete.
# If you choose this option, uncomment the next line and run this cell.
# job.wait()
%bash
# option 2 above. Copy my preprocessing results and move on.
# If you choose this option, uncomment the last two lines and run this cell.
FROM=gs://cloud-training-de... | quests/scientific/coastline.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
<h2> Training </h2>
<p>
Train the last few layers of the inception model based on our images. | import mltoolbox.image.classification as model
from google.datalab.ml import *
job = model.train_async(preprocessed_dir, 32, 5000, model_dir, # batchsize, numsteps
cloud=CloudTrainingConfig('us-central1', 'BASIC')) | quests/scientific/coastline.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Wait for the above job to complete before proceeding to next step (monitor job progress on the GCP console under ML Engine | Jobs). It should take about 15 minutes to complete.
The training log may contain harmless warnings and errors. Please check the message Task completed successfully at the end of the log to confi... | from google.datalab.ml import *
print model_dir
tb_id = TensorBoard.start(model_dir)
TensorBoard.stop(tb_id) | quests/scientific/coastline.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
When I did it, I got 85% accuracy on the held-out (evaluation dataset). This is not bad considering that we started with just about 200 images!
<p>
<h2> Deploy and predict model </h2>
<p>
Deploy the trained model as a web service. This simply a short cut to the underlying gcloud commands. | Models().create('coastline')
ModelVersions('coastline').deploy('v1', model_dir) | quests/scientific/coastline.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Once the model is deployed, we can send along an image and we will get back the classification probabilities. (these images are not among the 200 or so images used in training or in evaluation) | images = [
'gs://tamucc_coastline/esi_images/IMG_2007_SecDE_Spr12.jpg', # sheltered tidal flats
'gs://tamucc_coastline/esi_images/IMG_0297_SecBC_Spr12.jpg', # scarps and steep slopes in clay
'gs://tamucc_coastline/esi_images/IMG_3264_SecDE_Spr12.jpg', # sand-grained beaches
]
# resize=True because otherwise the i... | quests/scientific/coastline.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Function to calculate the Disk Mass from the Fmm, and the corrispective Error | def Mdisk(F,d,r,k,Td,lam):
#Eq 2 Andrews et al. 2013
#F is *mm* Flux in *Jy*
#d is the distance in *pc*
#r is the dust to mass ratio *adimensional*
#k is the dust opacity in *cm^2/g*
#lam is the wavelenght in *mm*
c=2.99792458e10 # Light velocity *cm/s*
h=6.6260755e-27 # Planck con... | UpperSco_Table.ipynb | martadesimone/Protoplanetarydisks | gpl-2.0 |
Calculate the Disk Mass with the function above | d=145. # distance of Chamaleon in pc
e_d=20. # error on distance d in pc
r=1. #dust to gass mass ratio
k=2.3*(338./225.4)**(0.4) #cm^2/g at 887um
lam=0.88 #wavelenght in mm
Td=20. #Temperature of the disk in K
Md=Mdisk(Fmm*1e-3,d,r,k,Td,lam)/3e-6 #Fmm has to be in *Jy*;... | UpperSco_Table.ipynb | martadesimone/Protoplanetarydisks | gpl-2.0 |
Permutation F-test on sensor data with 1D cluster level
One tests if the evoked response is significantly different
between conditions. Multiple comparison problem is addressed
with cluster level permutation test. | # Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
#
# License: BSD (3-clause)
import matplotlib.pyplot as plt
import mne
from mne import io
from mne.stats import permutation_cluster_test
from mne.datasets import sample
print(__doc__) | 0.17/_downloads/9460321824116e4964fbe6d88d27462e/plot_cluster_stats_evoked.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Set parameters | data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
event_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'
event_id = 1
tmin = -0.2
tmax = 0.5
# Setup for reading the raw data
raw = io.read_raw_fif(raw_fname)
events = mne.read_events(event_fname)
... | 0.17/_downloads/9460321824116e4964fbe6d88d27462e/plot_cluster_stats_evoked.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Read epochs for the channel of interest | picks = mne.pick_types(raw.info, meg=False, eog=True, include=include,
exclude='bads')
event_id = 1
reject = dict(grad=4000e-13, eog=150e-6)
epochs1 = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
baseline=(None, 0), reject=reject)
condition1 = epochs1.get_data()... | 0.17/_downloads/9460321824116e4964fbe6d88d27462e/plot_cluster_stats_evoked.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Compute statistic | threshold = 6.0
T_obs, clusters, cluster_p_values, H0 = \
permutation_cluster_test([condition1, condition2], n_permutations=1000,
threshold=threshold, tail=1, n_jobs=1) | 0.17/_downloads/9460321824116e4964fbe6d88d27462e/plot_cluster_stats_evoked.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Plot | times = epochs1.times
plt.close('all')
plt.subplot(211)
plt.title('Channel : ' + channel)
plt.plot(times, condition1.mean(axis=0) - condition2.mean(axis=0),
label="ERF Contrast (Event 1 - Event 2)")
plt.ylabel("MEG (T / m)")
plt.legend()
plt.subplot(212)
for i_c, c in enumerate(clusters):
c = c[0]
if c... | 0.17/_downloads/9460321824116e4964fbe6d88d27462e/plot_cluster_stats_evoked.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Option language: -l or --lang
Choose the language you want to use for pythontutor.com. Available options are:
python2
python3
py3anaconda (experimental and unsupported)
java
javascript
typescript
ruby
c
c++
If this option is not used the default value is python3.
Example: | %%tutor -l python3
a = 1
b = 2
print(a + b) | examples/Examples.ipynb | kikocorreoso/tutormagic | mit |
Option height: -h or --height
Change the height of the output area display in pixels.
Example: | %%tutor -l python3 -h 100
a = 1
b = 2
print(a + b) | examples/Examples.ipynb | kikocorreoso/tutormagic | mit |
Option tab: -t or --tab
Open pythontutor in a new tab. height option will be ignored if tab option is used.
Example: | %%tutor -l python3 -t
a = 1
b = 2
print(a + b) | examples/Examples.ipynb | kikocorreoso/tutormagic | mit |
Option secure: -s or --secure
Open pythontutor using https in a new tab. height and tab options will be ignored if secure option is used.
Example: | %%tutor -l python3 -s
a = 1
b = 2
print(a + b) | examples/Examples.ipynb | kikocorreoso/tutormagic | mit |
Option link: -k or --link
Just display a link to pythontutor with your defined code.
Example: | %%tutor -k
a = 1
b = 1
print(a + b) | examples/Examples.ipynb | kikocorreoso/tutormagic | mit |
Option run: -r or --run
Use this option if you also want to run the code in the cell in the notebook.
Example: | %%tutor -r
a = 1
b = 1
print("This is run in the notebook as well as in PythonTutor: ", a + b)
print("So, you have access to 'a' and 'b' vars...")
print("the value of a from the previous cell is: ", a) | examples/Examples.ipynb | kikocorreoso/tutormagic | mit |
Option cumulative: --cumulative
PythonTutor config: Set the cumulative option to True.
Example: | %%tutor --cumulative
def func():
return 10
a = func()
print(a) | examples/Examples.ipynb | kikocorreoso/tutormagic | mit |
Option heapPrimitives: --heapPrimitives
Render objects on the heap.
Example: | %%tutor --heapPrimitives
a = 1
b = 1
print(a + b) | examples/Examples.ipynb | kikocorreoso/tutormagic | mit |
Option textReferences: --textReferences
Use text labels for references.
Example: | %%tutor --textReferences --heapPrimitives
a = 1
b = 1
print(a + b) | examples/Examples.ipynb | kikocorreoso/tutormagic | mit |
Option curInstr: --curInstr
PythonTutor config: Start at the defined step.
Example: | %%tutor --curInstr 2
a = 1
b = 1
print(a + b) | examples/Examples.ipynb | kikocorreoso/tutormagic | mit |
Option verticalStack: --verticalStack
PythonTutor config: Set visualization to stack atop one another.
Example: | %%tutor --verticalStack
a = 1
b = 1
print(a + b) | examples/Examples.ipynb | kikocorreoso/tutormagic | mit |
Option lang py3anaconda: --lang py3anaconda
This option allows you to import more modules like numpy. It is experimental and unsupported (check pythontutor web page for more information).
Example: | %%tutor --lang py3anaconda
import numpy as np
arr = np.arange(10)
print(arr * 10) | examples/Examples.ipynb | kikocorreoso/tutormagic | mit |
Error Estimation for Survey Data
the issue we have is the following: we are drawing indendent random numbers from a binary distribution of probability $p$ (think: the probability of a certain person liking the color blue) and we have two groups (think: male and female). Those two groups dont necessarily have the same s... | N_people = 500
ratio_female = 0.30
proba = 0.40 | iPython/Error-Estimation-for-Survey-Data.ipynb | oditorium/blog | agpl-3.0 |
Closed Form Approximation
of course we could have done this analytically using Normal approximation: we have two independent Normal random variables, both with expectation $p$. The variance of the $male$ variable is $p(1-p)/N_{male}$ and the one of the female one accordingly. The overall variance of the difference (or ... | def the_sd(N, p, r):
N = float(N)
p = float(p)
r = float(r)
return sqrt(1.0/N*(p*(1.0-p))/(r*(1.0-r)))
def sd_func_factory(N,r):
def func(p):
return the_sd(N,p,r)
return func
f = sd_func_factory(N_people, ratio_female)
f2 = sd_func_factory(N_people/2, ratio_female) | iPython/Error-Estimation-for-Survey-Data.ipynb | oditorium/blog | agpl-3.0 |
Thats the one-standard deviation range about the estimator. For example: if the underlying probability is $0.25=25\%$ then the difference between the estimators for the male and the female group is $4.2\%$ for the full group (sd), or $5.9\%$ for if only half of the people replied (sd2) | p = linspace(0,0.25,5)
f = sd_func_factory(N_people, ratio_female)
f2 = sd_func_factory(N_people/2, ratio_female)
sd = list(map(f, p))
sd2 = list(map(f2, p))
pd.DataFrame(data= {'p':p, 'sd':sd, 'sd2':sd2}) | iPython/Error-Estimation-for-Survey-Data.ipynb | oditorium/blog | agpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.