markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
All those types are symbolic, meaning they don't have values at all. Theano variables can be defined with simple relations, such as | a = T.scalar('a')
c = a**2
print a.type
print c.type | TheanoLearning/TheanoLearning/theano_demo.ipynb | shengshuyang/PCLCombinedObjectDetection | gpl-2.0 |
note that c is also a symbolic scalar here.
We can also define a function: | f = theano.function([a],a**2)
print f | TheanoLearning/TheanoLearning/theano_demo.ipynb | shengshuyang/PCLCombinedObjectDetection | gpl-2.0 |
Again, Theano functions are symbolic as well. We must evaluate the function with some input to check its output. For example: | print f(2) | TheanoLearning/TheanoLearning/theano_demo.ipynb | shengshuyang/PCLCombinedObjectDetection | gpl-2.0 |
Shared variable is also a Theano type | shared_var = theano.shared(np.array([[1, 2], [3, 4]],
dtype=theano.config.floatX))
print 'variable type:'
print shared_var.type
print '\nvariable value:'
print shared_var.get_value()
shared_var.set_value(np.array([[4, 5], [6, 7]],
dtype=theano.c... | TheanoLearning/TheanoLearning/theano_demo.ipynb | shengshuyang/PCLCombinedObjectDetection | gpl-2.0 |
They have a fixed value, but are still treated as symbolic (can be input to functions etc.).
Shared variables are perfect to use as state variables or parameters. Fore example, in CNN each layer has a parameter matrix 'W', we need to store its value so we can perform testing against thousands of images, yet we also nee... | bias = T.matrix('bias')
shared_squared = shared_var**2 + bias
bias_value = np.array([[1,1],[1,1]],
dtype=theano.config.floatX)
f1 = theano.function([bias],shared_squared)
print f1(bias_value)
print '\n'
print shared_squared.eval({bias:bias_value}) | TheanoLearning/TheanoLearning/theano_demo.ipynb | shengshuyang/PCLCombinedObjectDetection | gpl-2.0 |
The example above defines a function that takes square of a shared_var and add by a bias. When evaluating the function we only provide value for bias because we know that the shared variable is fixed value.
Gradients
To calculate gradient we can use a T.grad() function to return a tensor variable. We first define some ... | def square(a):
return a**2
a = T.scalar('a')
b = square(a)
c = square(b) | TheanoLearning/TheanoLearning/theano_demo.ipynb | shengshuyang/PCLCombinedObjectDetection | gpl-2.0 |
Then we define two ways to evaluate gradient: | grad = T.grad(c,a)
f_grad = theano.function([a],grad) | TheanoLearning/TheanoLearning/theano_demo.ipynb | shengshuyang/PCLCombinedObjectDetection | gpl-2.0 |
The TensorVariable grad calculates gradient of b w.r.t. a.
The function f_grad takes a as input and grad as output, so it should be equivalent. However, evaluating them have different formats: | print grad.eval({a:10})
print f_grad(10) | TheanoLearning/TheanoLearning/theano_demo.ipynb | shengshuyang/PCLCombinedObjectDetection | gpl-2.0 |
MLP Demo with Theano | class layer(object):
def __init__(self, W_init, b_init, activation):
[n_output, n_input] = W_init.shape
assert b_init.shape == (n_output,1) or b_init.shape == (n_output,)
self.W = theano.shared(value = W_init.astype(theano.config.floatX),
name = 'W',
... | TheanoLearning/TheanoLearning/theano_demo.ipynb | shengshuyang/PCLCombinedObjectDetection | gpl-2.0 |
Plotting Flowchart (or Theano Graph)
The code snippet below can plot a flowchart that shows what happens inside our mlp layer. Note that the input out is the output of layer, as defined above. | from IPython.display import SVG
SVG(theano.printing.pydotprint(out, return_image=True,
compact = True,
var_with_name_simple = True,
format='svg')) | TheanoLearning/TheanoLearning/theano_demo.ipynb | shengshuyang/PCLCombinedObjectDetection | gpl-2.0 |
Authenticate to Earth Engine
In order to access Earth Engine, signup at signup.earthengine.google.com.
Once you have signed up and the Earth Engine package is installed, use the earthengine authenticate shell command to create and store authentication credentials on the Colab VM. These credentials are used by the Earth... | import ee
# Check if the server is authenticated. If not, display instructions that
# explain how to complete the process.
try:
ee.Initialize()
except ee.EEException:
!earthengine authenticate | python/examples/ipynb/EarthEngineColabInstall.ipynb | tylere/earthengine-api | apache-2.0 |
Test the installation
Import the Earth Engine library and initialize it with the authorization token stored on the notebook VM. Also import a display widget and display a thumbnail image of an Earth Engine dataset. | import ee
from IPython.display import Image
# Initialize the Earth Engine module.
ee.Initialize()
# Display a thumbnail of a sample image asset.
Image(url=ee.Image('CGIAR/SRTM90_V4').getThumbUrl({'min': 0, 'max': 3000})) | python/examples/ipynb/EarthEngineColabInstall.ipynb | tylere/earthengine-api | apache-2.0 |
Or, run code in parallel mode (command may need to be customized, depending your on MPI installation.) | !mpirun -n 4 swirl | applications/clawpack/advection/2d/disk/swirl.ipynb | ForestClaw/forestclaw | bsd-2-clause |
Create PNG files for web-browser viewing, or animation. | %run make_plots.py | applications/clawpack/advection/2d/disk/swirl.ipynb | ForestClaw/forestclaw | bsd-2-clause |
View PNG files in browser, using URL above, or create an animation of all PNG files, using code below. | %pylab inline
import glob
from matplotlib import image
from clawpack.visclaw.JSAnimation import IPython_display
from matplotlib import animation
figno = 0
fname = '_plots/*fig' + str(figno) + '.png'
filenames=sorted(glob.glob(fname))
fig = plt.figure()
im = plt.imshow(image.imread(filenames[0]))
def init():
im.s... | applications/clawpack/advection/2d/disk/swirl.ipynb | ForestClaw/forestclaw | bsd-2-clause |
Imprima todos los numeros primos positivos menores que n, solicite el n. | n = int(input("Ingrese el n: "))
#ojo... podriamos saltar de a 2, desde el 3.
for i in range(2,n):
cantdiv = 0
for j in range(2,int(i**0.5)+1):
if i%j == 0:
cantdiv += 1
if cantdiv == 0:
print(i, "es primo") | labs/ejercicios_for.ipynb | leoferres/prograUDD | mit |
Solicite n y k y calcule $\binom{n}{k}$ | n = int(input("Ingrese el n: "))
k = int(input("Ingrese el k: "))
if n < 0 or k < 0:
print("No se puede calcular, hay un elemento negativo")
elif n < k:
print("No se puede calcular, n debe ser mayor o igual a k")
else:
menor = k
if (n-k) < menor:
menor = (n-k)
resultado = 1
for i in ra... | labs/ejercicios_for.ipynb | leoferres/prograUDD | mit |
Se define como numero perfecto, aquél natural positivo en que la suma de sus divisores, no incluido si mismo, es el mismo número. | # obviaremos chequeo que sea positivo
n = int(input("Ingrese su n: "))
for i in range(1, n+1):
suma = 0
for j in range(1,i):
if i%j == 0:
suma += j
if suma == i:
print(i, "es perfecto")
for i in range(1, 496):
if 496%i == 0:
print(i) | labs/ejercicios_for.ipynb | leoferres/prograUDD | mit |
Si queremos añadir ramas adicionales al condicional, podemos emplear la instrucción elif (abreviatura de else if). Para la parte final, que debe ejecutarse si ninguna de las condiciones anteriores se ha cumplido, usamos la instrucción else. | x, y = 2, 0
if x > y:
print("x es mayor que y")
else:
print("x es menor que y")
# Uso de ELIF (contracción de else if)
x, y = 2 , 0
if x < y:
print("x es menor que y")
elif x == y:
print("x es igual a y")
else:
print("x es mayor que y") | python/howto/005_Estructuras de control.ipynb | xMyrst/BigData | gpl-3.0 |
<br />
EXPRESIONES TERNARIAS
Las expresiones ternarias en Python tienen la siguiente forma:
e = valorSiTrue if <condicion> else valorSiFalse
Permite definir la instrucción if-else en una sola línea. La expresión anterior es equivalente a:
if <condicion>:
e = valorSiTrue
else:
e = valorSiFal... | # Una expresión ternaria es una contracción de un bucle FOR
# Se define la variable para poder comparar
x = 8
# Se puede escrbir la expresión de esta manera o almacenando el resultado dentro de una variable
# para trabajar posteriormente con ella
"Hola CICE" if x == 8 else "Adios CICE"
a = 'x es igual a 8' if x == 8 e... | python/howto/005_Estructuras de control.ipynb | xMyrst/BigData | gpl-3.0 |
<br />
BUCLES FOR Y WHILE
El bucle FOR
Permite realizar una tarea un número fijo de veces. Se utiliza para recorrer una colección completa de elementos (una tupla, una lista, un diccionario, etc ):
for <element> in <iterable_object>:
<hacer algo...>
Aquí el objeto <iterable_object>... | # itera soble los elementos de la tupla
for elemento in (1, 2, 3, 4, 5):
print(elemento)
# Suma todos los elementos de la tupla
suma = 0
for elemento in (1, 2, 3, 4, 5):
suma = suma + elemento
print(suma)
# Muestra todos los elemntos de una lista
dias = ["Lunes", "Martes", "Miércoles", "Jueves", 'Viernes', 'S... | python/howto/005_Estructuras de control.ipynb | xMyrst/BigData | gpl-3.0 |
<br />
El bucle WHILE
Los bucles while repetirán las instrucciones anidadas en él mientras se cumpla una condición:
while <condition>:
<things to do>
El número de iteraciones es variable, depende de la condición.
+Como en el caso de los condicionales, los bloques se separan por sangrado sin necesi... | i = -2
while i < 5:
print(i)
i = i + 1
print("Estoy fuera del while")
# Para interrumpir un bucle WHILE se utiliza la instrucción BREAK
# Se pueden usar expresiones de tipo condicional (AND, OR, NOT)
i = 0
j = 1
while i < 5 and j == 1:
print(i)
i = i + 1
if i == 3:
break | python/howto/005_Estructuras de control.ipynb | xMyrst/BigData | gpl-3.0 |
<BR />
LA FUNCIÓN ENUMERATE
Cuando trabajamos con secuencias de elementos puede resultar útil conocer el índice de cada elemento. La función enumerate devuelve una secuencia de tuplas de la forma (i, valor).
Mediante un bucle es posible recorrerse dicha secuencia: | # Creamos una lista llamada ciudades
# Recorremos dicha lista mediante la instrucción FOR asignando una secuencia de números (i) a cada valor de la lista
ciudades = ["Madrid", "Sevilla", "Segovia", "Valencia" ]
for (i, valor) in enumerate(ciudades):
print('%d: %s' % (i, valor))
# Uso de la función reversed
# la f... | python/howto/005_Estructuras de control.ipynb | xMyrst/BigData | gpl-3.0 |
1) Boxplot of General Density | # syn_unmasked_T = syn_unmasked.values.T.tolist()
# columns = [syn_unmasked[i] for i in [4]]
plt.boxplot(syn_unmasked[:,3], 0, 'gD')
plt.xticks([1], ['Set'])
plt.ylabel('Density Distribution')
plt.title('Density Distrubution Boxplot')
plt.show() | code/Assignment11_Group.ipynb | Upward-Spiral-Science/team1 | apache-2.0 |
2) Is the spike noise? More evidence.
We saw from Emily's analysis that there is strong evidence against the spike being noise. If we see that the spike is noticeable in the histogram of synapses as well as the histogram of synapse density, we will gain even more evidence that the spike is noise. | figure = plt.figure()
plt.hist(data_thresholded[:,4],5000)
plt.title('Histogram of Synapses in Brain Sample')
plt.xlabel('Synapses')
plt.ylabel('frequency') | code/Assignment11_Group.ipynb | Upward-Spiral-Science/team1 | apache-2.0 |
Since we don't see the spike in the histogram of synapses, the spike may be some artifact of the unmasked value. Let's take a look!
3) What is the spike? We still don't know. | plt.hist(data_thresholded[:,3],5000)
plt.title('Histogram of Unmasked Values')
plt.xlabel('unmasked')
plt.ylabel('frequency') | code/Assignment11_Group.ipynb | Upward-Spiral-Science/team1 | apache-2.0 |
4) Synapses and unmasked: Spike vs Whole Data Set | # Spike
a = np.apply_along_axis(lambda x:x[4]/x[3], 1, data_thresholded)
spike = a[np.logical_and(a <= 0.0015, a >= 0.0012)]
print "Average Density: ", np.mean(spike)
print "Std Deviation: ", np.std(spike)
# Histogram
n, bins, _ = plt.hist(spike, 2000)
plt.title('Histogram of Synaptic Density')
plt.xlabel('Synaptic De... | code/Assignment11_Group.ipynb | Upward-Spiral-Science/team1 | apache-2.0 |
5) Boxplot of different clusters by coordinates and densities
Cluster 4 has relatively high density | import sklearn.mixture as mixture
n_clusters = 4
gmm = mixture.GMM(n_components=n_clusters, n_iter=1000, covariance_type='diag')
labels = gmm.fit_predict(syn_unmasked)
clusters = []
for l in range(n_clusters):
a = np.where(labels == l)
clusters.append(syn_unmasked[a,:])
print len(clusters)
print clusters[0].s... | code/Assignment11_Group.ipynb | Upward-Spiral-Science/team1 | apache-2.0 |
5 OLD ) Boxplot distrubutions of each Z layer |
data_uniques, UIndex, UCounts = np.unique(syn_unmasked[:,2], return_index = True, return_counts = True)
'''
print 'uniques'
print 'index: ' + str(UIndex)
print 'counts: ' + str(UCounts)
print 'values: ' + str(data_uniques)
'''
fig, ax = plt.subplots(3,4,figsize=(10,20))
counter = 0
for i in np.unique(syn_unmasked[:,2... | code/Assignment11_Group.ipynb | Upward-Spiral-Science/team1 | apache-2.0 |
One of the first things you do with a class is to define the _init_() method. The __init__() method sets the values for any parameters that need to be defined when an object is first created. The self part will be explained later; basically, it's a syntax that allows you to access a variable from anywhere else in the c... | class Rocket():
# Rocket simulates a rocket ship for a game,
# or a physics simulation.
def __init__(self):
# Each rocket has an (x,y) position.
self.x = 0
self.y = 0
def move_up(self):
# Increment the y-position of the rocket.
self.y += 1 | 08 Classes and OOP.ipynb | leriomaggio/python-in-a-notebook | mit |
The Rocket class can now store some information, and it can do something. But this code has not actually created a rocket yet. Here is how you actually make a rocket: | class Rocket():
# Rocket simulates a rocket ship for a game,
# or a physics simulation.
def __init__(self):
# Each rocket has an (x,y) position.
self.x = 0
self.y = 0
def move_up(self):
# Increment the y-position of the rocket.
self.y += 1
# Create... | 08 Classes and OOP.ipynb | leriomaggio/python-in-a-notebook | mit |
To actually use a class, you create a variable such as my_rocket. Then you set that equal to the name of the class, with an empty set of parentheses. Python creates an object from the class. An object is a single instance of the Rocket class; it has a copy of each of the class's variables, and it can do any action that... | class Rocket():
# Rocket simulates a rocket ship for a game,
# or a physics simulation.
def __init__(self):
# Each rocket has an (x,y) position.
self.x = 0
self.y = 0
def move_up(self):
# Increment the y-position of the rocket.
self.y += 1
# Create... | 08 Classes and OOP.ipynb | leriomaggio/python-in-a-notebook | mit |
To access an object's variables or methods, you give the name of the object and then use dot notation to access the variables and methods. So to get the y-value of my_rocket, you use my_rocket.y. To use the move_up() method on my_rocket, you write my_rocket.move_up().
Once you have a class defined, you can create as ma... | class Rocket():
# Rocket simulates a rocket ship for a game,
# or a physics simulation.
def __init__(self):
# Each rocket has an (x,y) position.
self.x = 0
self.y = 0
def move_up(self):
# Increment the y-position of the rocket.
self.y += 1
... | 08 Classes and OOP.ipynb | leriomaggio/python-in-a-notebook | mit |
You can see that each rocket is at a separate place in memory. By the way, if you understand list comprehensions, you can make the fleet of rockets in one line: | class Rocket():
# Rocket simulates a rocket ship for a game,
# or a physics simulation.
def __init__(self):
# Each rocket has an (x,y) position.
self.x = 0
self.y = 0
def move_up(self):
# Increment the y-position of the rocket.
self.y += 1
... | 08 Classes and OOP.ipynb | leriomaggio/python-in-a-notebook | mit |
You can prove that each rocket has its own x and y values by moving just one of the rockets: | class Rocket():
# Rocket simulates a rocket ship for a game,
# or a physics simulation.
def __init__(self):
# Each rocket has an (x,y) position.
self.x = 0
self.y = 0
def move_up(self):
# Increment the y-position of the rocket.
self.y += 1
... | 08 Classes and OOP.ipynb | leriomaggio/python-in-a-notebook | mit |
The syntax for classes may not be very clear at this point, but consider for a moment how you might create a rocket without using classes. You might store the x and y values in a dictionary, but you would have to write a lot of ugly, hard-to-maintain code to manage even a small set of rockets. As more features become i... | # Ex 9.0 : Rocket with no Class
# put your code here | 08 Classes and OOP.ipynb | leriomaggio/python-in-a-notebook | mit |
top
<a name='oop_terminology'></a>Object-Oriented terminology
Classes are part of a programming paradigm called object-oriented programming. Object-oriented programming, or OOP for short, focuses on building reusable blocks of code called classes. When you want to use a class in one of your programs, you make an object... | class Rocket():
# Rocket simulates a rocket ship for a game,
# or a physics simulation.
def __init__(self):
# Each rocket has an (x,y) position.
self.x = 0
self.y = 0 | 08 Classes and OOP.ipynb | leriomaggio/python-in-a-notebook | mit |
The first line shows how a class is created in Python. The keyword class tells Python that you are about to define a class. The rules for naming a class are the same rules you learned about naming variables, but there is a strong convention among Python programmers that classes should be named using CamelCase. If you a... | class Rocket():
# Rocket simulates a rocket ship for a game,
# or a physics simulation.
def __init__(self):
# Each rocket has an (x,y) position.
self.x = 0
self.y = 0
def move_up(self):
# Increment the y-position of the rocket.
self.y += 1 | 08 Classes and OOP.ipynb | leriomaggio/python-in-a-notebook | mit |
A method is just a function that is part of a class. Since it is just a function, you can do anything with a method that you learned about with functions. You can accept positional arguments, keyword arguments, an arbitrary list of argument values, an arbitrary dictionary of arguments, or any combination of these. Your... | class Rocket():
# Rocket simulates a rocket ship for a game,
# or a physics simulation.
def __init__(self):
# Each rocket has an (x,y) position.
self.x = 0
self.y = 0
def move_up(self):
# Increment the y-position of the rocket.
self.y += 1
# Create... | 08 Classes and OOP.ipynb | leriomaggio/python-in-a-notebook | mit |
In this example, a Rocket object is created and stored in the variable my_rocket. After this object is created, its y value is printed. The value of the attribute y is accessed using dot notation. The phrase my_rocket.y asks Python to return "the value of the variable y attached to the object my_rocket".
After the obje... | class Rocket():
# Rocket simulates a rocket ship for a game,
# or a physics simulation.
def __init__(self):
# Each rocket has an (x,y) position.
self.x = 0
self.y = 0
def move_up(self):
# Increment the y-position of the rocket.
self.y += 1
... | 08 Classes and OOP.ipynb | leriomaggio/python-in-a-notebook | mit |
If you are comfortable using list comprehensions, go ahead and use those as much as you can. I'd rather not assume at this point that everyone is comfortable with comprehensions, so I will use the slightly longer approach of declaring an empty list, and then using a for loop to fill that list. That can be done slightly... | class Rocket():
# Rocket simulates a rocket ship for a game,
# or a physics simulation.
def __init__(self):
# Each rocket has an (x,y) position.
self.x = 0
self.y = 0
def move_up(self):
# Increment the y-position of the rocket.
self.y += 1
... | 08 Classes and OOP.ipynb | leriomaggio/python-in-a-notebook | mit |
What exactly happens in this for loop? The line my_rockets.append(Rocket()) is executed 5 times. Each time, a new Rocket object is created and then added to the list my_rockets. The __init__() method is executed once for each of these objects, so each object gets its own x and y value. When a method is called on one of... | # Ex 9.1 : Your Own Rocket
# put your code here | 08 Classes and OOP.ipynb | leriomaggio/python-in-a-notebook | mit |
top
<a name='refining_rocket'></a>Refining the Rocket class
The Rocket class so far is very simple. It can be made a little more interesting with some refinements to the __init__() method, and by the addition of some methods.
<a name='init_parameters'></a>Accepting paremeters for the __init__() method
The __init__() me... | class Rocket():
# Rocket simulates a rocket ship for a game,
# or a physics simulation.
def __init__(self):
# Each rocket has an (x,y) position.
self.x = 0
self.y = 0
def move_up(self):
# Increment the y-position of the rocket.
self.y += 1 | 08 Classes and OOP.ipynb | leriomaggio/python-in-a-notebook | mit |
All the __init__() method does so far is set the x and y values for the rocket to 0. We can easily add a couple keyword arguments so that new rockets can be initialized at any position: | class Rocket():
# Rocket simulates a rocket ship for a game,
# or a physics simulation.
def __init__(self, x=0, y=0):
# Each rocket has an (x,y) position.
self.x = x
self.y = y
def move_up(self):
# Increment the y-position of the rocket.
self.y += 1 | 08 Classes and OOP.ipynb | leriomaggio/python-in-a-notebook | mit |
Now when you create a new Rocket object you have the choice of passing in arbitrary initial values for x and y: | class Rocket():
# Rocket simulates a rocket ship for a game,
# or a physics simulation.
def __init__(self, x=0, y=0):
# Each rocket has an (x,y) position.
self.x = x
self.y = y
def move_up(self):
# Increment the y-position of the rocket.
self.y += 1... | 08 Classes and OOP.ipynb | leriomaggio/python-in-a-notebook | mit |
top
<a name='method_parameters'></a>Accepting paremeters in a method
The __init__ method is just a special method that serves a particular purpose, which is to help create new objects from a class. Any method in a class can accept parameters of any kind. With this in mind, the move_up() method can be made much more fle... | class Rocket():
# Rocket simulates a rocket ship for a game,
# or a physics simulation.
def __init__(self, x=0, y=0):
# Each rocket has an (x,y) position.
self.x = x
self.y = y
def move_rocket(self, x_increment=0, y_increment=1):
# Move the rocket according... | 08 Classes and OOP.ipynb | leriomaggio/python-in-a-notebook | mit |
The paremeters for the move() method are named x_increment and y_increment rather than x and y. It's good to emphasize that these are changes in the x and y position, not new values for the actual position of the rocket. By carefully choosing the right default values, we can define a meaningful default behavior. If som... | class Rocket():
# Rocket simulates a rocket ship for a game,
# or a physics simulation.
def __init__(self, x=0, y=0):
# Each rocket has an (x,y) position.
self.x = x
self.y = y
def move_rocket(self, x_increment=0, y_increment=1):
# Move the rocket according... | 08 Classes and OOP.ipynb | leriomaggio/python-in-a-notebook | mit |
top
<a name='adding_method'></a>Adding a new method
One of the strengths of object-oriented programming is the ability to closely model real-world phenomena by adding appropriate attributes and behaviors to classes. One of the jobs of a team piloting a rocket is to make sure the rocket does not get too close to any oth... | from math import sqrt
class Rocket():
# Rocket simulates a rocket ship for a game,
# or a physics simulation.
def __init__(self, x=0, y=0):
# Each rocket has an (x,y) position.
self.x = x
self.y = y
def move_rocket(self, x_increment=0, y_increment=1):
# Mo... | 08 Classes and OOP.ipynb | leriomaggio/python-in-a-notebook | mit |
Hopefully these short refinements show that you can extend a class' attributes and behavior to model the phenomena you are interested in as closely as you want. The rocket could have a name, a crew capacity, a payload, a certain amount of fuel, and any number of other attributes. You could define any behavior you want ... | # Ex 9.2 : Your Own Rocket 2
# put your code here
# Ex 9.3 : Rocket Attributes
# put your code here
# Ex 9.4 : Rocket Methods
# put your code here
# Ex 9.5 : Person Class
# put your code here
# Ex 9.6 : Car Class
# put your code here | 08 Classes and OOP.ipynb | leriomaggio/python-in-a-notebook | mit |
top
<a name='inheritance'></a>Inheritance
One of the most important goals of the object-oriented approach to programming is the creation of stable, reliable, reusable code. If you had to create a new class for every kind of object you wanted to model, you would hardly have any reusable code.
In Python and any other la... | from math import sqrt
class Rocket():
# Rocket simulates a rocket ship for a game,
# or a physics simulation.
def __init__(self, x=0, y=0):
# Each rocket has an (x,y) position.
self.x = x
self.y = y
def move_rocket(self, x_increment=0, y_increment=1):
# Mo... | 08 Classes and OOP.ipynb | leriomaggio/python-in-a-notebook | mit |
When a new class is based on an existing class, you write the name of the parent class in parentheses when you define the new class: | class NewClass(ParentClass): | 08 Classes and OOP.ipynb | leriomaggio/python-in-a-notebook | mit |
The __init__() function of the new class needs to call the __init__() function of the parent class. The __init__() function of the new class needs to accept all of the parameters required to build an object from the parent class, and these parameters need to be passed to the __init__() function of the parent class. The... | class NewClass(ParentClass):
def __init__(self, arguments_new_class, arguments_parent_class):
super().__init__(arguments_parent_class)
# Code for initializing an object of the new class. | 08 Classes and OOP.ipynb | leriomaggio/python-in-a-notebook | mit |
The super() function passes the self argument to the parent class automatically. You could also do this by explicitly naming the parent class when you call the __init__() function, but you then have to include the self argument manually: | class Shuttle(Rocket):
# Shuttle simulates a space shuttle, which is really
# just a reusable rocket.
def __init__(self, x=0, y=0, flights_completed=0):
Rocket.__init__(self, x, y)
self.flights_completed = flights_completed | 08 Classes and OOP.ipynb | leriomaggio/python-in-a-notebook | mit |
This might seem a little easier to read, but it is preferable to use the super() syntax. When you use super(), you don't need to explicitly name the parent class, so your code is more resilient to later changes. As you learn more about classes, you will be able to write child classes that inherit from multiple parent c... | from math import sqrt
from random import randint
class Rocket():
# Rocket simulates a rocket ship for a game,
# or a physics simulation.
def __init__(self, x=0, y=0):
# Each rocket has an (x,y) position.
self.x = x
self.y = y
def move_rocket(self, x_increment=0, y... | 08 Classes and OOP.ipynb | leriomaggio/python-in-a-notebook | mit |
Inheritance is a powerful feature of object-oriented programming. Using just what you have seen so far about classes, you can model an incredible variety of real-world and virtual phenomena with a high degree of accuracy. The code you write has the potential to be stable and reusable in a variety of applications.
top
<... | # Ex 9.7 : Student Class
# put your code here
# Ex 9.8 : Refining Shuttle
# put your code here | 08 Classes and OOP.ipynb | leriomaggio/python-in-a-notebook | mit |
top
<a name='modules_classes'></a>Modules and classes
Now that you are starting to work with classes, your files are going to grow longer. This is good, because it means your programs are probably doing more interesting things. But it is bad, because longer files can be more difficult to work with. Python allows you to... | # Save as rocket.py
from math import sqrt
class Rocket():
# Rocket simulates a rocket ship for a game,
# or a physics simulation.
def __init__(self, x=0, y=0):
# Each rocket has an (x,y) position.
self.x = x
self.y = y
def move_rocket(self, x_increment=0, y_increm... | 08 Classes and OOP.ipynb | leriomaggio/python-in-a-notebook | mit |
Make a separate file called rocket_game.py. If you are more interested in science than games, feel free to call this file something like rocket_simulation.py. Again, to use standard naming conventions, make sure you are using a lowercase_underscore name for this file. | # Save as rocket_game.py
from rocket import Rocket
rocket = Rocket()
print("The rocket is at (%d, %d)." % (rocket.x, rocket.y)) | 08 Classes and OOP.ipynb | leriomaggio/python-in-a-notebook | mit |
This is a really clean and uncluttered file. A rocket is now something you can define in your programs, without the details of the rocket's implementation cluttering up your file. You don't have to include all the class code for a rocket in each of your files that deals with rockets; the code defining rocket attributes... | # Save as rocket.py
from math import sqrt
class Rocket():
# Rocket simulates a rocket ship for a game,
# or a physics simulation.
def __init__(self, x=0, y=0):
# Each rocket has an (x,y) position.
self.x = x
self.y = y
def move_rocket(self, x_increment=0, y_increm... | 08 Classes and OOP.ipynb | leriomaggio/python-in-a-notebook | mit |
Now you can import the Rocket and the Shuttle class, and use them both in a clean uncluttered program file: | # Save as rocket_game.py
from rocket import Rocket, Shuttle
rocket = Rocket()
print("The rocket is at (%d, %d)." % (rocket.x, rocket.y))
shuttle = Shuttle()
print("\nThe shuttle is at (%d, %d)." % (shuttle.x, shuttle.y))
print("The shuttle has completed %d flights." % shuttle.flights_completed) | 08 Classes and OOP.ipynb | leriomaggio/python-in-a-notebook | mit |
The first line tells Python to import both the Rocket and the Shuttle classes from the rocket module. You don't have to import every class in a module; you can pick and choose the classes you care to use, and Python will only spend time processing those particular classes.
<a name='multiple_ways_import'></a>A number of... | from module_name import ClassName | 08 Classes and OOP.ipynb | leriomaggio/python-in-a-notebook | mit |
is straightforward, and is used quite commonly. It allows you to use the class names directly in your program, so you have very clean and readable code. This can be a problem, however, if the names of the classes you are importing conflict with names that have already been used in the program you are working on. This i... | # Save as rocket_game.py
import rocket
rocket_0 = rocket.Rocket()
print("The rocket is at (%d, %d)." % (rocket_0.x, rocket_0.y))
shuttle_0 = rocket.Shuttle()
print("\nThe shuttle is at (%d, %d)." % (shuttle_0.x, shuttle_0.y))
print("The shuttle has completed %d flights." % shuttle_0.flights_completed) | 08 Classes and OOP.ipynb | leriomaggio/python-in-a-notebook | mit |
The general syntax for this kind of import is: | import module_name | 08 Classes and OOP.ipynb | leriomaggio/python-in-a-notebook | mit |
After this, classes are accessed using dot notation: | module_name.ClassName | 08 Classes and OOP.ipynb | leriomaggio/python-in-a-notebook | mit |
This prevents some name conflicts. If you were reading carefully however, you might have noticed that the variable name rocket in the previous example had to be changed because it has the same name as the module itself. This is not good, because in a longer program that could mean a lot of renaming.
import module_name ... | import module_name as local_module_name | 08 Classes and OOP.ipynb | leriomaggio/python-in-a-notebook | mit |
When you are importing a module into one of your projects, you are free to choose any name you want for the module in your project. So the last example could be rewritten in a way that the variable name rocket would not need to be changed: | # Save as rocket_game.py
import rocket as rocket_module
rocket = rocket_module.Rocket()
print("The rocket is at (%d, %d)." % (rocket.x, rocket.y))
shuttle = rocket_module.Shuttle()
print("\nThe shuttle is at (%d, %d)." % (shuttle.x, shuttle.y))
print("The shuttle has completed %d flights." % shuttle.flights_completed... | 08 Classes and OOP.ipynb | leriomaggio/python-in-a-notebook | mit |
This approach is often used to shorten the name of the module, so you don't have to type a long module name before each class name that you want to use. But it is easy to shorten a name so much that you force people reading your code to scroll to the top of your file and see what the shortened name stands for. In this ... | import rocket as rocket_module | 08 Classes and OOP.ipynb | leriomaggio/python-in-a-notebook | mit |
leads to much more readable code than something like: | import rocket as r | 08 Classes and OOP.ipynb | leriomaggio/python-in-a-notebook | mit |
from module_name import *
There is one more import syntax that you should be aware of, but you should probably avoid using. This syntax imports all of the available classes and functions in a module: | from module_name import * | 08 Classes and OOP.ipynb | leriomaggio/python-in-a-notebook | mit |
This is not recommended, for a couple reasons. First of all, you may have no idea what all the names of the classes and functions in a module are. If you accidentally give one of your variables the same name as a name from the module, you will have naming conflicts. Also, you may be importing way more code into your pr... | # Save as multiplying.py
def double(x):
return 2*x
def triple(x):
return 3*x
def quadruple(x):
return 4*x | 08 Classes and OOP.ipynb | leriomaggio/python-in-a-notebook | mit |
Now you can import the file multiplying.py, and use these functions. Using the from module_name import function_name syntax: | from multiplying import double, triple, quadruple
print(double(5))
print(triple(5))
print(quadruple(5)) | 08 Classes and OOP.ipynb | leriomaggio/python-in-a-notebook | mit |
Using the import module_name syntax: | import multiplying
print(multiplying.double(5))
print(multiplying.triple(5))
print(multiplying.quadruple(5)) | 08 Classes and OOP.ipynb | leriomaggio/python-in-a-notebook | mit |
Using the import module_name as local_module_name syntax: | import multiplying as m
print(m.double(5))
print(m.triple(5))
print(m.quadruple(5)) | 08 Classes and OOP.ipynb | leriomaggio/python-in-a-notebook | mit |
Using the from module_name import * syntax: | from multiplying import *
print(double(5))
print(triple(5))
print(quadruple(5)) | 08 Classes and OOP.ipynb | leriomaggio/python-in-a-notebook | mit |
top
<a name='exercises_importing'></a>Exercises
Importing Student
Take your program from Student Class
Save your Person and Student classes in a separate file called person.py.
Save the code that uses these classes in four separate files.
In the first file, use the from module_name import ClassName syntax to make your... | # Ex 9.9 : Importing Student
# put your code here
# Ex 9.10 : Importing Car
# put your code here | 08 Classes and OOP.ipynb | leriomaggio/python-in-a-notebook | mit |
top
<a name="mro"></a>Method Resolution Order (mro) | class A:
def __init__(self, a):
self.a = a
class GreatB:
def greetings(self):
print('Greetings from Type: ', self.__class__)
class B(GreatB):
def __init__(self, b):
self.b = b
class C(A,B):
def __init__(self, a, b):
A.__init__(sel... | 08 Classes and OOP.ipynb | leriomaggio/python-in-a-notebook | mit |
Load directories | root_directory = 'D:/github/w_vattenstatus/ekostat_calculator'#"../" #os.getcwd()
workspace_directory = root_directory + '/workspaces'
resource_directory = root_directory + '/resources'
#alias = 'lena'
user_id = 'test_user' #kanske ska vara off_line user?
# workspace_alias = 'lena_indicator' # kustzonsmodellen_3daydat... | notebooks/lv_notebook_kustzon.ipynb | ekostat/ekostat_calculator | mit |
Set subset filters | # #### year filter
w.set_data_filter(subset = subset_uuid, step=1,
filter_type='include_list',
filter_name='MYEAR',
data=[2007,2008,2009,2010,2011,2012])#['2011', '2012', '2013']) #, 2014, 2015, 2016
#########################################... | notebooks/lv_notebook_kustzon.ipynb | ekostat/ekostat_calculator | mit |
#########################################################################################################################
Step 2 | ### Load indicator settings filter
w.get_step_object(step = 2, subset = subset_uuid).load_indicator_settings_filters()
###############################################################################################################################
### set available indicators
w.get_available_indicators(subset= subs... | notebooks/lv_notebook_kustzon.ipynb | ekostat/ekostat_calculator | mit |
#########################################################################################################################
Step 3 | # ### Set up indicator objects
print('indicator set up to {}'.format(indicator_list))
w.get_step_object(step = 3, subset = subset_uuid).indicator_setup(indicator_list = indicator_list)
###############################################################################################################################
# ###... | notebooks/lv_notebook_kustzon.ipynb | ekostat/ekostat_calculator | mit |
Figure 1 csv data generation
Figure data consolidation for Figure 1, which maps samples and shows distribution across EMPO categories
Figure 1a and 1b
for these figure, we just need the samples, EMPO level categories, and lat/lon coordinates | # Load up metadata map
metadata_fp = '../../../data/mapping-files/emp_qiime_mapping_qc_filtered.tsv'
metadata = pd.read_csv(metadata_fp, header=0, sep='\t')
metadata.head()
metadata.columns
# take just the columns we need for this figure panel
fig1ab = metadata.loc[:,['#SampleID','empo_0','empo_1','empo_2','empo_... | methods/figure-data/fig-1/Fig1_data_files.ipynb | cuttlefishh/emp | bsd-3-clause |
Write to Excel notebook | fig1 = pd.ExcelWriter('Figure1_data.xlsx')
fig1ab.to_excel(fig1,'Fig-1ab')
fig1.save() | methods/figure-data/fig-1/Fig1_data_files.ipynb | cuttlefishh/emp | bsd-3-clause |
Optionally, enable debug level logging | # Uncomment this if you want debug logging enabled
#setup_logger(log_file="pytx.log") | ipynb/ThreatExchange Data Dashboard.ipynb | tiegz/ThreatExchange | bsd-3-clause |
Search for data in ThreatExchange
Start by running a query against the ThreatExchange APIs to pull down any/all data relevant to you over a specified period of days. | # Our basic search parameters, we default to querying over the past 14 days
days_back = 14
search_terms = ['abuse', 'phishing', 'malware', 'exploit', 'apt', 'ddos', 'brute', 'scan', 'cve'] | ipynb/ThreatExchange Data Dashboard.ipynb | tiegz/ThreatExchange | bsd-3-clause |
Next, we execute the query using our search parameters and put the results in a Pandas DataFrame | from datetime import datetime, timedelta
from time import strftime
import pandas as pd
import re
from pytx import ThreatDescriptor
from pytx.vocabulary import ThreatExchange as te
# Define your search string and other params, see
# https://pytx.readthedocs.org/en/latest/pytx.common.html#pytx.common.Common.objects
# ... | ipynb/ThreatExchange Data Dashboard.ipynb | tiegz/ThreatExchange | bsd-3-clause |
Do some data munging for easier analysis and then preview as a sanity check | from time import mktime
# Extract a datetime and timestamp, for easier analysis
data_frame['ds'] = pd.to_datetime(data_frame.added_on.str[0:10], format='%Y-%m-%d')
data_frame['ts'] = pd.to_datetime(data_frame.added_on)
# Extract the owner data
owner = data_frame.pop('owner')
owner = owner.apply(pd.Series)
data_frame ... | ipynb/ThreatExchange Data Dashboard.ipynb | tiegz/ThreatExchange | bsd-3-clause |
Create a Dashboard to Get a High-level View
The raw data is great, but it would be much better if we could take a higher level view of the data. This dashboard will provide more insight into:
what data is available
who's sharing it
how is labeled
how much of it is likely to be directly applicable for alerting | import math
import matplotlib.pyplot as plt
import seaborn as sns
from pytx.vocabulary import ThreatDescriptor as td
%matplotlib inline
# Setup subplots for our dashboard
fig, axes = plt.subplots(nrows=4, ncols=2, figsize=(16,32))
axes[0,0].set_color_cycle(sns.color_palette("coolwarm_r", 15))
# Plot by Type over ti... | ipynb/ThreatExchange Data Dashboard.ipynb | tiegz/ThreatExchange | bsd-3-clause |
Dive A Little Deeper
Take a subset of the data and understand it a little more.
In this example, we presume that we'd like to take phishing related data and study it, to see if we can use it to better defend a corporate network or abuse in a product.
As a simple example, we'll filter down to data labeled MALICIOUS ... | from pytx.vocabulary import Status as s
phish_data = data_frame[(data_frame.status == s.MALICIOUS)
& data_frame.description.apply(lambda x: x.find('phish') if x != None else False)]
# TODO: also filter for attack_type == PHISHING, when Pytx supports it
%matplotlib inline
# Setup subplots fo... | ipynb/ThreatExchange Data Dashboard.ipynb | tiegz/ThreatExchange | bsd-3-clause |
Extract The High Confidence / Severity Data For Use
With a better understanding of the data, let's filter the MALICIOUS, REVIEWED_MANUALLY labeled data down to a pre-determined threshold for confidence + severity.
You can add more filters, or change the threshold, as you see fit. | from pytx.vocabulary import ReviewStatus as rs
# define our threshold line, which is the same as the red, threshold line in the chart above
sev_min = 2
sev_max = 10
conf_min= 0
conf_max = 100
# build a new series, to indicate if a row passes our confidence + severity threshold
def is_high_value(conf, sev):
return... | ipynb/ThreatExchange Data Dashboard.ipynb | tiegz/ThreatExchange | bsd-3-clause |
Now, output all of the high value data to a file as CSV or JSON, for consumption in our other systems and workflows. | use_csv = False
if use_csv:
file_name = 'threat_exchange_high_value.csv'
high_value_data.to_csv(path_or_buf=file_name)
print "CSV data written to %s" % file_name
else:
file_name = 'threat_exchange_high_value.json'
high_value_data.to_json(path_or_buf=file_name, orient='index')
print "JSON data w... | ipynb/ThreatExchange Data Dashboard.ipynb | tiegz/ThreatExchange | bsd-3-clause |
Creamos una matriz cuadrada relativamente grande (4 millones de elementos). | np.random.seed(0)
data = np.random.randn(2000, 2000) | C elemental, querido Cython..ipynb | Ykharo/notebooks | bsd-2-clause |
Ya tenemos los datos listos para empezar a trabajar.
Vamos a crear una función en Python que busque los mínimos tal como los hemos definido. | def busca_min(malla):
minimosx = []
minimosy = []
for i in range(1, malla.shape[1]-1):
for j in range(1, malla.shape[0]-1):
if (malla[j, i] < malla[j-1, i-1] and
malla[j, i] < malla[j-1, i] and
malla[j, i] < malla[j-1, i+1] and
malla[j, i] ... | C elemental, querido Cython..ipynb | Ykharo/notebooks | bsd-2-clause |
Veamos cuanto tarda esta función en mi máquina: | %timeit busca_min(data) | C elemental, querido Cython..ipynb | Ykharo/notebooks | bsd-2-clause |
Buff, tres segundos y pico en un i7... Si tengo que buscar los mínimos en 500 de estos casos me va a tardar casi media hora.
Por casualidad, vamos a probar numba a ver si es capaz de resolver el problema sin mucho esfuerzo, es código Python muy sencillo en el cual no usamos cosas muy 'extrañas' del lenguaje. | from numba import jit
@jit
def busca_min_numba(malla):
minimosx = []
minimosy = []
for i in range(1, malla.shape[1]-1):
for j in range(1, malla.shape[0]-1):
if (malla[j, i] < malla[j-1, i-1] and
malla[j, i] < malla[j-1, i] and
malla[j, i] < malla[j-1, i+1... | C elemental, querido Cython..ipynb | Ykharo/notebooks | bsd-2-clause |
Ooooops! Parece que la magia de numba no funciona aquí.
Vamos a especificar los tipos de entrada y de salida (y a modificar el output) a ver si mejora algo: | from numba import jit
from numba import int32, float64
@jit(int32[:,:](float64[:,:]))
def busca_min_numba(malla):
minimosx = []
minimosy = []
for i in range(1, malla.shape[1]-1):
for j in range(1, malla.shape[0]-1):
if (malla[j, i] < malla[j-1, i-1] and
malla[j, i] < mal... | C elemental, querido Cython..ipynb | Ykharo/notebooks | bsd-2-clause |
Pues parece que no, el resultado es del mismo pelo. Usando la opción nopython me casca un error un poco feo,...
Habrá que seguir esperando a que numba esté un poco más maduro. En mis pocas experiencias no he conseguido aun el efecto que buscaba y en la mayoría de los casos obtengo errores muy crípticos. No es que no t... | # antes cythonmagic
%load_ext Cython | C elemental, querido Cython..ipynb | Ykharo/notebooks | bsd-2-clause |
EL comando %%cython nos permite escribir código Cython en una celda. Una vez que ejecutamos la celda, IPython se encarga de coger el código, crear un fichero de código Cython con extensión .pyx, compilarlo a C y, si todo está correcto, importar ese fichero para que todo esté disponible dentro del notebook.
[INCISO] a l... | %%cython --name probandocython1
import numpy as np
def busca_min_cython1(malla):
minimosx = []
minimosy = []
for i in range(1, malla.shape[1]-1):
for j in range(1, malla.shape[0]-1):
if (malla[j, i] < malla[j-1, i-1] and
malla[j, i] < malla[j-1, i] and
ma... | C elemental, querido Cython..ipynb | Ykharo/notebooks | bsd-2-clause |
El fichero se creará dentro de la carpeta cython disponible dentro del directorio resultado de la función get_ipython_cache_dir. Veamos la localización del fichero en mi equipo: | from IPython.utils.path import get_ipython_cache_dir
print(get_ipython_cache_dir() + '/cython/probandocython1.c') | C elemental, querido Cython..ipynb | Ykharo/notebooks | bsd-2-clause |
No lo muestro por aquí porque el resultado son más de ¡¡2400!! líneas de código C.
Veamos ahora lo que tarda. | %timeit busca_min_cython1(data) | C elemental, querido Cython..ipynb | Ykharo/notebooks | bsd-2-clause |
Bueno, parece que sin hacer mucho esfuerzo hemos conseguido ganar en torno a un 5% - 25% de rendimiento (dependerá del caso). No es gran cosa pero Cython es capaz de mucho más...
Cythonizando, que es gerundio (toma 2).
En esta parte vamos a introducir una de las palabras clave que Cython introduce para extender Python,... | %%cython --name probandocython2
import numpy as np
def busca_min_cython2(malla):
cdef list minimosx, minimosy
cdef unsigned int i, j
cdef unsigned int ii = malla.shape[1]-1
cdef unsigned int jj = malla.shape[0]-1
minimosx = []
minimosy = []
for i in range(1, ii):
for j in range(1, j... | C elemental, querido Cython..ipynb | Ykharo/notebooks | bsd-2-clause |
Vaya decepción... No hemos conseguido gran cosa, tenemos un código un poco más largo y estamos peor que en la toma 1.
En realidad, estamos usando objetos Python como listas (no es un tipo C/C++ puro pero Cython lo declara como puntero a algún tipo struct de Python) o numpy arrays y no hemos definido las variables de en... | %%cython --name probandocython3
import numpy as np
cdef tuple cbusca_min_cython3(malla):
cdef list minimosx, minimosy
cdef unsigned int i, j
cdef unsigned int ii = malla.shape[1]-1
cdef unsigned int jj = malla.shape[0]-1
cdef unsigned int start = 1
minimosx = []
minimosy = []
for i in r... | C elemental, querido Cython..ipynb | Ykharo/notebooks | bsd-2-clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.