markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Summary Supervised learning task is to predict $Y$ given $X$ Fit is using training data to fit parameters Predict uses the fitted parameters to do prediction Loss is a function that says how poorly you did on datum $x_i,y_i$ Intermission Risk and Empirical Risk Given a loss $\ell(\theta; X,Y)$, for parameters $\theta...
## randomly shuffle data and split n,p = X.shape Ind = np.arange(n) np.random.shuffle(Ind) train_size = 2 * n // 3 +1 # set training set size X_tr, X_te = X[Ind[:train_size],:], X[Ind[train_size:],:] Y_tr, Y_te = Y[Ind[:train_size]], Y[Ind[train_size:]] ## compute losses on test set betahat = fit(X_tr,Y_tr) Y_hat_te...
lectures/lecture1/.ipynb_checkpoints/lecture1-checkpoint.ipynb
jsharpna/DavisSML
mit
Basic LSTM from https://arxiv.org/abs/1409.2329 <img align="left" width="600px" src='./basic_lstm.png' />
num_hidden = 24 cell = tf.nn.rnn_cell.LSTMCell(num_hidden,state_is_tuple=True) val, state = tf.nn.dynamic_rnn(cell, data, dtype=tf.float32) val = tf.transpose(val, [1, 0, 2]) last = tf.gather(val, int(val.get_shape()[0]) - 1) weight = tf.Variable(tf.truncated_normal([num_hidden, int(target.get_shape()[1])])) bias =...
tensor-flow-exercises/7_SimpleLSTM.ipynb
texib/deeplearning_homework
mit
Softmax <img width='200px' align="left" src="./softmax.png" />
prediction = tf.nn.softmax(tf.matmul(last, weight) + bias)
tensor-flow-exercises/7_SimpleLSTM.ipynb
texib/deeplearning_homework
mit
什麼是 Corss Entropy http://blog.csdn.net/rtygbwwwerr/article/details/50778098
cross_entropy = -tf.reduce_sum(target * tf.log(tf.clip_by_value(prediction,1e-10,1.0)))
tensor-flow-exercises/7_SimpleLSTM.ipynb
texib/deeplearning_homework
mit
建立 Optimize Function
optimizer = tf.train.AdamOptimizer() minimize = optimizer.minimize(cross_entropy) mistakes = tf.not_equal(tf.argmax(target, 1), tf.argmax(prediction, 1)) error = tf.reduce_mean(tf.cast(mistakes, tf.float32)) init_op = tf.initialize_all_variables() sess = tf.Session() sess.run(init_op)
tensor-flow-exercises/7_SimpleLSTM.ipynb
texib/deeplearning_homework
mit
作 Training
batch_size = 1000 no_of_batches = int(len(train_input)/batch_size) epoch =500 for i in range(epoch): ptr = 0 for j in range(no_of_batches): inp, out = train_input[ptr:ptr+batch_size], train_output[ptr:ptr+batch_size] ptr+=batch_size sess.run(minimize,{data: inp, target: out}) # print...
tensor-flow-exercises/7_SimpleLSTM.ipynb
texib/deeplearning_homework
mit
Next, define the feature columns. mother_age and gestation_weeks should be numeric. The others (is_male, plurality) should be categorical.
## Build a Keras wide-and-deep model using its Functional API def rmse(y_true, y_pred): return tf.sqrt(tf.reduce_mean(tf.square(y_pred - y_true))) # Helper function to handle categorical columns def categorical_fc(name, values): orig = tf.feature_column.categorical_column_with_vocabulary_list(name, values) ...
courses/machine_learning/deepdive/06_structured/3_keras_wd.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
A ordem que as operações são executadas seguem uma ordem de precedência: - primeiro as operações de divisão e multiplicação, - em seguida adição e subtração.
1 + 2 * 3
Aula01.ipynb
folivetti/PIPYTHON
mit
A ordem pode ser alterada com o uso de parênteses.
(1+2)*3 1 + (2*3)
Aula01.ipynb
folivetti/PIPYTHON
mit
Além das operações básicas temos algumas operações mais complexas disponíveis. Precisamos indicar que queremos usar tais funções com o comando: python import math Nota: As funções matemáticas disponíveis podem ser consultadas na documentação.
import math math.sqrt(2.0) # raiz de 2 math.log(10) # ln(10) math.exp(1.0) # e^1 math.log(math.exp(1.0)) # ln(e) math.cos(math.pi) # cos(pi)
Aula01.ipynb
folivetti/PIPYTHON
mit
Os tipos numéricos em Python são chamados de: - int, para números inteiros e, - float, para números reais. Complete os códigos abaixo e aperte SHIFT+ENTER para verificar se a saída é a esperada.
# Exercício 01 # Vamos fazer algumas operações básicas: escreva o código logo abaixo das instruções, ao completar a tarefa aperte "shift+enter" # e verifique se a resposta está de acordo com o esperado # 1) A razão áurea é dada pela eq. (1 + raiz(5))/2, imprima o resultado # resultado deve ser 1.61803398875 # 2)...
Aula01.ipynb
folivetti/PIPYTHON
mit
Quando uma operação tem resultado indefinido o Python indica com o valor nan. Variáveis No exercício anterior, para calcular cada valor de entropia foi necessário digitar toda a fórmula para cada valor de p. Além disso o valor de p era utilizado duas vezes em cada equação, tornando o trabalho tedioso e com tendência a ...
x = 10 # o computador armazena o valor 10 na variável de nome x x + 2 x * 3
Aula01.ipynb
folivetti/PIPYTHON
mit
Dessa forma o calculo da entropia poderia ser feito como:
p = 0.4 -p*math.log(p,2) - (1.0-p)*math.log(1.0-p,2)
Aula01.ipynb
folivetti/PIPYTHON
mit
Ao alterar o valor de p, o programa retorna o resultado da nova entropia. Podemos pedir que o usuário entre com os valores utilizando o comando input(). Esse comando vai esperar que o usuário digite algum valor e o atribuirá em uma variável. Nota: precisamos especificar ao comando input o tipo de variável desejada, no ...
p = float(input("Digite o valor de p: ")) -p*math.log(p,2) - (1.0-p)*math.log(1.0-p,2)
Aula01.ipynb
folivetti/PIPYTHON
mit
O nome das variáveis deve: - começar com uma letra e, - conter apenas letras, números e o símbolo "_". Além disso existem alguns nomes já utilizados pelo Python e que não devem ser utilizados: python and, as, assert, break, class, continue, def, del, elif, else, except, exec, finally, for, from, global, if, ...
x = 1 type(x) x = 1.0 type(x)
Aula01.ipynb
folivetti/PIPYTHON
mit
Outros tipos de dados Booleanos Além dos tipos numéricos temos também os tipos lógicos que podem conter o valor de verdadeiro (True) ou falso (False). Esses valores são gerados através de operadores relacionais: - Igualdade: 1 == 2 => False - Desigualdade: 1 != 2 => True - Maior e Maior ou igual: 1 &gt; 2, 1 &gt;= 2 =>...
True and False True and True True or False True or True not True not False x = 1 y = 2 x == y x != y x > y x <= y x <= y and x != y # x < y? x <= y and not (x != y) # x >= y e x == y ==> x == y?
Aula01.ipynb
folivetti/PIPYTHON
mit
Strings Temos também a opção de trabalhar com textos, ou strings. Esse tipo é caracterizado por aspas simples ou duplas.
texto = "Olá Mundo" type(texto) len(texto)
Aula01.ipynb
folivetti/PIPYTHON
mit
Podemos usar os operadores + e *, representando concatenação e repetição:
ola = "Olá" espaco = " " mundo = "Mundo" ola + espaco + mundo (ola + espaco) * 6 + mundo
Aula01.ipynb
folivetti/PIPYTHON
mit
Podemos também obter um caractere da string utilizando o conceito de indexação. Na indexação, colocamos um valor entre colchetes após o nome da variável para indicar a posição do elemento que nos interessa naquele momento. A contagem de posição inicia do 0.
texto = "Olá Mundo" texto[0] texto[2] # terceira letra
Aula01.ipynb
folivetti/PIPYTHON
mit
Podemos também usar a indexação para pegar faixas de valores:
texto[0:3] texto[4:] # omitir o último valor significa que quero ir até o fim texto[:3] # nesse caso omiti o valor inicial texto[-1] # índice negativo representa uma contagem de trás para frente texto[-1:-6:-1] # o último valor, -1, indica que quero andar de trás para frente.
Aula01.ipynb
folivetti/PIPYTHON
mit
Listas Listas de valores são criadas colocando elementos de quaisquer tipos entre colchetes e separados por vírgulas. As listas podem ser úteis para armazenar uma coleção de valores que utilizaremos em nosso programa.
coordenadas = [1.0, 3.0] coordenadas lista = [1,2,3.0,'batata',True] lista len(lista)
Aula01.ipynb
folivetti/PIPYTHON
mit
O acesso aos elementos da lista é feito de forma similar às strings:
lista[0] # imprime o primeiro elemento da lista lista[0:3] # imprime os 3 primeiros elementos lista[-1] # último elemento
Aula01.ipynb
folivetti/PIPYTHON
mit
Existem outros tipos mais avançados que veremos ao longo do curso. Complete o código abaixo para realizar o que é pedido:
#Exercício 02 import math # 1) entre com o numero do mes do seu nascimento na variavel 'mes' e siga as instruções abaixo colocando o resultado # na variável 'resultado'. mes = int(input('Digite o mes do seu nascimento: ')) resultado = 0 # 1) multiplique o número por 2 e armazene na variavel de nome resultado # 2) som...
Aula01.ipynb
folivetti/PIPYTHON
mit
Entrada e Saída de Dados Entrada de Dados Durante essa primeira aula vimos sobre os comandos input() para capturar valores digitados pelo usuário e print() para imprimir os valores dos resultados. O comando input() captura uma string digitada pelo usuário, essa string deve ser convertida de acordo com o que se espera d...
x = float(input("Entre com um valor numérico: ")) # o valor digitado será um número em ponto flutuante x/2
Aula01.ipynb
folivetti/PIPYTHON
mit
Alguns dos comandos de conversão disponíveis são: int() para inteiros, float() para ponto flutuante e str() para strings.
x = 10 int(x) + 2 float(x) * 2 str(x) * 2
Aula01.ipynb
folivetti/PIPYTHON
mit
Saída de Dados A função print() permite escrever o valor de uma variável ou expressão na tela pulando para a próxima linha ao final. Esse comando permite a impressão de diversos valores na mesma linha separando-os por ",". Adicionalmente, se o último argumento da função for end=" " ele não pula para a próxima linha apó...
print(2) # imprime 2 e vai para a próxima linha print(3, "ola", 4+5) # imprime múltiplos valores de diferentes tipos e vai para a próxima linha print(1, 2, end=" ") # imprime os dois valores mas não pula para a próxima linha print(3,4) # continua impressão na mesma linha
Aula01.ipynb
folivetti/PIPYTHON
mit
A função print() permite o uso de alguns caracteres especiais como: - '\t': adiciona uma tabulação - '\n': pula uma linha Podemos complementar a formatação da string com o comando format():
m = 1 n = 6 d = 1/float(n) print('{}: {}/{} = {:.4}'.format("O valor da divisão", m, n, d)) # {} indica que as lacunas devem ser preenchidas e .4 é o número de casas decimais para o número. print("Elemento 1 \t Elemento 2 \nElemento 3 \t Elemento 4")
Aula01.ipynb
folivetti/PIPYTHON
mit
Bibliotecas Extras O Python conta com diversas bibliotecas que automatizam muitas tarefas e permitem realizarmos experimentos interessantes. Usualmente as bibliotecas, ou módulos, são importados através do comando: python import NOME e as funções das bibliotecas são chamadas precedidas pelo NOME do módulo. Vimos isso ...
import math math.sqrt(2)
Aula01.ipynb
folivetti/PIPYTHON
mit
Se soubermos exatamente as funções que iremos utilizar do módulo, podemos importá-los seletivamente com a sintaxe: python from NOME import FUNCAO Nesse caso não precisamos preceder a função com NOME para executá-la:
from math import sqrt, exp print(sqrt(2), exp(3))
Aula01.ipynb
folivetti/PIPYTHON
mit
Finalmente podemos apelidar o nome do módulo para facilitar a chamada de funções:
import math as mt print(mt.sqrt(2), mt.exp(3))
Aula01.ipynb
folivetti/PIPYTHON
mit
O comando dir lista todas as funções disponíveis em uma biblioteca:
print(dir(math))
Aula01.ipynb
folivetti/PIPYTHON
mit
E o comando help imprime uma ajuda sobre determinada função:
help(math.sin)
Aula01.ipynb
folivetti/PIPYTHON
mit
A biblioteca matplotlib permite plotar gráficos diversos. Para usá-la no Jupyter Notebook primeiro devemos importar os comandos de plotagem: python %matplotlib inline import matplotlib.pyplot as plt O comando %matplotlib inline indica para o Jupyter que todos os gráficos devem ser mostrados dentro do próprio notebook....
%matplotlib inline import matplotlib.pyplot as plt x = [-5,-4,-3,-2,-1,0,1,2,3,4,5] y = [25,16,9,4,1,0,1,4,9,16,25] plt.figure(figsize=(8,8)) # Cria uma nova figura com largura e altura definida por figsize plt.style.use('fivethirtyeight') # define um estilo de plotagem: # http://tonysyu.github.io/raw_content/matpl...
Aula01.ipynb
folivetti/PIPYTHON
mit
If you want to create a tuple with a single value, add a comma (,) after the value, but don’t add parenthesis You can also use the built in function tuple
a_tuple = tuple() print( a_tuple ) a_tuple = tuple( 'lupins' ) print( a_tuple )
CSNE2444-Intro-to-CS-I/jupyter-notebooks/ch12-tuples.ipynb
snucsne/CSNE-Course-Source-Code
mit
Most list operators (e.g., bracket and slice) work on tuples If you try to modify one of the elements, you get an error
a_tuple = ( 'a', 'b', 'c', 'd', 'e' ) print( a_tuple[1:3] ) print( a_tuple[:3] ) print( a_tuple[1:] ) # Uncomment to see error # a_tuple[0] = 'z'
CSNE2444-Intro-to-CS-I/jupyter-notebooks/ch12-tuples.ipynb
snucsne/CSNE-Course-Source-Code
mit
Tuple assignment Often, you may want to swap the values of two variables This is done conventionally using a temporary variable for storage
a = 5 b = 6 # Conventional value swap temp = a a = b b = temp print( a, b )
CSNE2444-Intro-to-CS-I/jupyter-notebooks/ch12-tuples.ipynb
snucsne/CSNE-Course-Source-Code
mit
Python allows you to do it using a tuple assignment
a, b = b, a print( a, b )
CSNE2444-Intro-to-CS-I/jupyter-notebooks/ch12-tuples.ipynb
snucsne/CSNE-Course-Source-Code
mit
On the left is a tuple of varaibles and on the right is a tuple of expressions Note that the number on each side of the equality sign must be the same The right side can be any kind of sequence (e.g., a string or list)
addr = 'monty@python.org' uname, domain = addr.split( '@' ) print( uname ) print( domain )
CSNE2444-Intro-to-CS-I/jupyter-notebooks/ch12-tuples.ipynb
snucsne/CSNE-Course-Source-Code
mit
Tuples as return values A function can only return one value However, if we make that value a tuple, we can effectively return multiple values For example, the divmod function takes two (2) arguments and retunrs a tuple of two (2) values, the quotient and remainder
quotient, remainder = divmod( 7, 3 ) print( quotient ) print( remainder )
CSNE2444-Intro-to-CS-I/jupyter-notebooks/ch12-tuples.ipynb
snucsne/CSNE-Course-Source-Code
mit
Note the use of a tuple assignment Here is how to build a function that returns a tuple
def min_max( a_tuple ): return min( a_tuple ), max( a_tuple ) numbers = ( 13, 7, 55, 42 ) min_num, max_num = min_max( numbers ) print( min_num ) print( max_num )
CSNE2444-Intro-to-CS-I/jupyter-notebooks/ch12-tuples.ipynb
snucsne/CSNE-Course-Source-Code
mit
Note that min and max are built-in functions Variable-length argument tuples All the functions we have built and used required a specific number of arguments You can use tuples to build functions that accept a variable number of arguments Prepend the argument’s variable name with an * to do this It is referred to as ...
def printall( *args ): print( args ) printall( 1 , 2.0 , '3' )
CSNE2444-Intro-to-CS-I/jupyter-notebooks/ch12-tuples.ipynb
snucsne/CSNE-Course-Source-Code
mit
The complement is the scatter operator It allows you to pass a sequence of values as individual arguments to the function
a_tuple = ( 7, 3 ) # divmod( a_tuple ) # Uncomment to see error divmod( *a_tuple )
CSNE2444-Intro-to-CS-I/jupyter-notebooks/ch12-tuples.ipynb
snucsne/CSNE-Course-Source-Code
mit
Lists and tuples The zip function takes two or more sequences and "zips" them into a list of tuples
a_string = 'abc' a_list = [ 0, 1, 2 ] for element in zip( a_string, a_list ): print( element )
CSNE2444-Intro-to-CS-I/jupyter-notebooks/ch12-tuples.ipynb
snucsne/CSNE-Course-Source-Code
mit
Essentially, it returns an iterator over a list of tuples If the sequences aren't the same length, the result has the length of the shorter one
for element in zip( 'Peter', 'Tony' ): print( element )
CSNE2444-Intro-to-CS-I/jupyter-notebooks/ch12-tuples.ipynb
snucsne/CSNE-Course-Source-Code
mit
You can also use tuple assignment to get the individual values
a_list = [ ('a', 0), ('b', 1), ('c', 2) ] for letter, number in a_list: print( letter, number )
CSNE2444-Intro-to-CS-I/jupyter-notebooks/ch12-tuples.ipynb
snucsne/CSNE-Course-Source-Code
mit
You can combine zip, for and tuple assignment to traverse two (or more) sequences at the same time
def has_match( tuple1, tuple2 ): result = False for x, y in zip( tuple1, tuple2 ): if( x == y ): result = True return result
CSNE2444-Intro-to-CS-I/jupyter-notebooks/ch12-tuples.ipynb
snucsne/CSNE-Course-Source-Code
mit
If you need the indices, use the enumerate function
for index , element in enumerate( 'abc' ): print( index, element )
CSNE2444-Intro-to-CS-I/jupyter-notebooks/ch12-tuples.ipynb
snucsne/CSNE-Course-Source-Code
mit
Dictionaries and tuples The method items returns a tuple of key-value pairs from a dictionary
a_dict = { 'a': 0, 'b':1, 'c':2 } dict_items = a_dict.items() print( type( dict_items ) ) print( dict_items ) for element in dict_items: print( element )
CSNE2444-Intro-to-CS-I/jupyter-notebooks/ch12-tuples.ipynb
snucsne/CSNE-Course-Source-Code
mit
Remember that there is no particular ordering in a dictionary You can also add a list of tuples to a dictionary using the update method Using items, tuple assignment, and a for loop is an easy way to traverse the keys and values of a dictionary
for key, value in a_dict.items(): print( key, value )
CSNE2444-Intro-to-CS-I/jupyter-notebooks/ch12-tuples.ipynb
snucsne/CSNE-Course-Source-Code
mit
Since tuples are immutable, you can even use them as keys in a dictionary
directory = dict() directory[ 'Smith', 'Bob' ] = '555-1234' directory[ 'Doe', 'Jane' ] = '555-9786' for last, first in directory: print( first, last, directory[last, first] )
CSNE2444-Intro-to-CS-I/jupyter-notebooks/ch12-tuples.ipynb
snucsne/CSNE-Course-Source-Code
mit
Overview We have already seen how to evaluate a Python function at a set of numerical points: $$ f(x) \rightarrow f_i = f(x_i) $$ Here is an array of points:
x = np.linspace(0,4*np.pi,10) x
days/day11/Interpolation.ipynb
LimeeZ/phys292-2015-work
mit
This creates a new array of points that are the values of $\sin(x_i)$ at each point $x_i$:
f = np.sin(x) print(f) c = np.cos(x) print (c) plt.plot(x, f, marker='o') plt.xlabel('x') plt.ylabel('f(x)');
days/day11/Interpolation.ipynb
LimeeZ/phys292-2015-work
mit
This plot shows that the points in this numerical array are an approximation to the actual function as they don't have the function's value at all possible points. In this case we know the actual function ($\sin(x)$). What if we only know the value of the function at a limited set of points, and don't know the analytic...
from scipy.interpolate import interp1d
days/day11/Interpolation.ipynb
LimeeZ/phys292-2015-work
mit
Let's create the numerical data we will use to build our interpolation.
x = np.linspace(0,4*np.pi,10) # only use 10 points to emphasize this is an approx f = np.sin(x)
days/day11/Interpolation.ipynb
LimeeZ/phys292-2015-work
mit
To create our approximate function, we call interp1d as follows, with the numerical data. Options for the kind argument includes: linear: draw a straight line between initial points. nearest: return the value of the function of the nearest point. slinear, quadratic, cubic: use a spline (particular kinds of piecewise p...
sin_approx = interp1d(x, f, kind='cubic')
days/day11/Interpolation.ipynb
LimeeZ/phys292-2015-work
mit
The sin_approx variabl that interp1d returns is a callable object that can be used to compute the approximate function at other points. Compute the approximate function on a fine grid:
newx = np.linspace(0,4*np.pi,100) newf = sin_approx(newx)
days/day11/Interpolation.ipynb
LimeeZ/phys292-2015-work
mit
Plot the original data points, along with the approximate interpolated values. It is quite amazing to see how the interpolation has done a good job of reconstructing the actual function with relatively few points.
plt.plot(x, f, marker='o', linestyle='', label='original data') plt.plot(newx, newf, marker='.', label='interpolated'); plt.legend(); plt.xlabel('x') plt.ylabel('f(x)');
days/day11/Interpolation.ipynb
LimeeZ/phys292-2015-work
mit
Let's look at the absolute error between the actual function and the approximate interpolated function:
plt.plot(newx, np.abs(np.sin(newx)-sin_approx(newx))) plt.xlabel('x') plt.ylabel('Absolute error');
days/day11/Interpolation.ipynb
LimeeZ/phys292-2015-work
mit
1d non-regular data It is also possible to use interp1d when the x data is not regularly spaced. To show this, let's repeat the above analysis with randomly distributed data in the range $[0,4\pi]$. Everything else is the same.
x = 4*np.pi*np.random.rand(15) f = np.sin(x) sin_approx = interp1d(x, f, kind='cubic') # We have to be careful about not interpolating outside the range newx = np.linspace(np.min(x), np.max(x),100) newf = sin_approx(newx) plt.plot(x, f, marker='o', linestyle='', label='original data') plt.plot(newx, newf, marker='.'...
days/day11/Interpolation.ipynb
LimeeZ/phys292-2015-work
mit
Notice how the absolute error is larger in the intervals where there are no points. 2d structured For the 2d case we want to construct a scalar function of two variables, given $$ {x_i, y_i, f_i} \rightarrow f(x,y) $$ For now, we will assume that the points ${x_i,y_i}$ are on a structured grid of points. This case is c...
from scipy.interpolate import interp2d
days/day11/Interpolation.ipynb
LimeeZ/phys292-2015-work
mit
Here is the actual function we will use the generate our original dataset:
def wave2d(x, y): return np.sin(2*np.pi*x)*np.sin(3*np.pi*y)
days/day11/Interpolation.ipynb
LimeeZ/phys292-2015-work
mit
Build 1d arrays to use as the structured grid:
x = np.linspace(0.0, 1.0, 10) y = np.linspace(0.0, 1.0, 10)
days/day11/Interpolation.ipynb
LimeeZ/phys292-2015-work
mit
Build 2d arrays to use in computing the function on the grid points:
X, Y = np.meshgrid(x, y) Z = wave2d(X, Y)
days/day11/Interpolation.ipynb
LimeeZ/phys292-2015-work
mit
Here is a scatter plot of the points overlayed with the value of the function at those points:
plt.pcolor(X, Y, Z) plt.colorbar(); plt.scatter(X, Y); plt.xlim(0,1) plt.ylim(0,1) plt.xlabel('x') plt.ylabel('y');
days/day11/Interpolation.ipynb
LimeeZ/phys292-2015-work
mit
You can see in this plot that the function is not smooth as we don't have its value on a fine grid. Now let's compute the interpolated function using interp2d. Notice how we are passing 2d arrays to this function:
wave2d_approx = interp2d(X, Y, Z, kind='cubic')
days/day11/Interpolation.ipynb
LimeeZ/phys292-2015-work
mit
Compute the interpolated function on a fine grid:
xnew = np.linspace(0.0, 1.0, 40) ynew = np.linspace(0.0, 1.0, 40) Xnew, Ynew = np.meshgrid(xnew, ynew) # We will use these in the scatter plot below Fnew = wave2d_approx(xnew, ynew) # The interpolating function automatically creates the meshgrid! Fnew.shape
days/day11/Interpolation.ipynb
LimeeZ/phys292-2015-work
mit
Plot the original course grid of points, along with the interpolated function values on a fine grid:
plt.pcolor(xnew, ynew, Fnew); plt.colorbar(); plt.scatter(X, Y, label='original points') plt.scatter(Xnew, Ynew, marker='.', color='green', label='interpolated points') plt.xlim(0,1) plt.ylim(0,1) plt.xlabel('x') plt.ylabel('y'); plt.legend(bbox_to_anchor=(1.2, 1), loc=2, borderaxespad=0.);
days/day11/Interpolation.ipynb
LimeeZ/phys292-2015-work
mit
Notice how the interpolated values (green points) are now smooth and continuous. The amazing thing is that the interpolation algorithm doesn't know anything about the actual function. It creates this nice approximation using only the original course grid (blue points). 2d unstructured It is also possible to perform int...
from scipy.interpolate import griddata
days/day11/Interpolation.ipynb
LimeeZ/phys292-2015-work
mit
There is an important difference between griddata and the interp1d/interp2d: interp1d and interp2d return callable Python objects (functions). griddata returns the interpolated function evaluated on a finer grid. This means that you have to pass griddata an array that has the finer grid points to be used. Here is the...
x = np.random.rand(100) y = np.random.rand(100)
days/day11/Interpolation.ipynb
LimeeZ/phys292-2015-work
mit
Notice how we pass these 1d arrays to our function and don't use meshgrid:
f = wave2d(x, y)
days/day11/Interpolation.ipynb
LimeeZ/phys292-2015-work
mit
It is clear that our grid is very unstructured:
plt.scatter(x, y); plt.xlim(0,1) plt.ylim(0,1) plt.xlabel('x') plt.ylabel('y');
days/day11/Interpolation.ipynb
LimeeZ/phys292-2015-work
mit
To use griddata we need to compute the final (strcutured) grid we want to compute the interpolated function on:
xnew = np.linspace(x.min(), x.max(), 40) ynew = np.linspace(y.min(), y.max(), 40) Xnew, Ynew = np.meshgrid(xnew, ynew) Xnew.shape, Ynew.shape Fnew = griddata((x,y), f, (Xnew, Ynew), method='cubic', fill_value=0.0) Fnew.shape plt.pcolor(Xnew, Ynew, Fnew, label="points") plt.colorbar() plt.scatter(x, y, label='origin...
days/day11/Interpolation.ipynb
LimeeZ/phys292-2015-work
mit
Some Motivation for Numerical Integration Let's say we have a system, defined as a system of differential equations $$ \frac{d\mathbf{y}}{dt} = f(t, \mathbf{y}(t)) $$ where $\mathbf{y}$ represents some vector of dependent variables, $t$ is time, and the system has some specified initial condition $\mathbf{y}(t_0) = \ma...
def rhs_function(y, t): """The right hand side of our ODE.""" dydt = -y return dydt def real_solution(y0, t): """The real (analytical) solution to the ODE""" return y0*np.exp(-t) def euler_solve(t0, t1, h, y0, func): """Solve a simple equation using the Euler method t0: initial time ...
6_Optimization_Integration_ODEs.ipynb
apozas/BIST-Python-Bootcamp
gpl-3.0
As you can see, the smaller the timestep becomes the closer our numerical soultion converges to the real solution. The Euler method is low order, and requires a small timestep in general in order to converge to a correct solution. However it is important to note is that (despite its low-order nature) it is quite useful...
from scipy.integrate import odeint
6_Optimization_Integration_ODEs.ipynb
apozas/BIST-Python-Bootcamp
gpl-3.0
The basic form of the right hand side function is the same as before.
# Solve with Euler t0 = 0 t1 = 10 h = 0.5 y0 = 1.0 T, Y = euler_solve(t0, t1, h, y0, rhs_function) # Solve with odeint sol = odeint(rhs_function, y0, T) tFine = np.linspace(T[0], T[-1], 1000) plt.plot(T, Y, 'k-o') plt.plot(T, sol, 'g-o') plt.plot(t_fine, real_solution(y0, tFine), 'r--') plt.xlabel('Time') plt.lege...
6_Optimization_Integration_ODEs.ipynb
apozas/BIST-Python-Bootcamp
gpl-3.0
It is evident that the more stable scheme used in odeint allows us to obtain a better solution using a larger timestep. Now we investigate the behaviour of a more interesting system, the 'Brusselator'. The Brusselator is a theoretical model for a type of autocatalytic chemical reaction. Its behaviour is characterised b...
def bruss_odeint(y, t, a, b): """RHS equations for the brusselator system. Arguments: y: the current state of the system t: time a, b: free parameters governing the dynamics Returns: dydt: the computed derivative at (y, t) """ # Unpack both species X, Y = y # ...
6_Optimization_Integration_ODEs.ipynb
apozas/BIST-Python-Bootcamp
gpl-3.0
The first thing to do is to define the parameters of interest:
a = 1.0 b = 1.0
6_Optimization_Integration_ODEs.ipynb
apozas/BIST-Python-Bootcamp
gpl-3.0
It is also necessary to define the initial conditions ($X(t_0)$ and $Y(t_0)$), and the time points over which we will integrate:
# Initial conditions y0 = [0.5, 0.5] # Time from 0 to 25 t = np.linspace(0, 25, 101)
6_Optimization_Integration_ODEs.ipynb
apozas/BIST-Python-Bootcamp
gpl-3.0
Finally we can solve the system through a single call to odeint. Note the function signature. odeint() requires the following arguments: - The function we wish to integrate - The initial point(s); these must have the same dimension as the derivative i.e., you need to have initial conditions specified for all dependent ...
sol, info = odeint(bruss_odeint, y0, t, args = (a, b), full_output = True)
6_Optimization_Integration_ODEs.ipynb
apozas/BIST-Python-Bootcamp
gpl-3.0
The variable sol (first returned value) contains the solution over the desired time points.
print('The number of time points is', len(t)) print('The solution matrix contains', sol.shape, 'entries')
6_Optimization_Integration_ODEs.ipynb
apozas/BIST-Python-Bootcamp
gpl-3.0
As you can see, there is a column of solutions for each variable (X and Y, in this case). So, we can plot these and observe the dynamics of our system.
plt.figure() plt.plot(t, sol[:, 0]) plt.plot(t, sol[:, 1]) plt.xlabel('Time (a.u.)') plt.ylabel('Concentration (a.u.)') plt.legend(['[X]', '[Y]'])
6_Optimization_Integration_ODEs.ipynb
apozas/BIST-Python-Bootcamp
gpl-3.0
Additionally, you may have noticed that we return a second value called info. This stores a record about the numerical process underlying your results. This information can be useful in case you need to debug some experiments, and additionally if you want to start building some routines that use the integrator (e.g., ...
print("Let's see what 'info' contains...:\n") print(info)
6_Optimization_Integration_ODEs.ipynb
apozas/BIST-Python-Bootcamp
gpl-3.0
These cryptically named fields are further detailed in the documentation, but in summary: 'hu': vector of step sizes successfully used for each time step. 'tcur' vector with the value of t reached for each time step. (will always be at least as large as the input times). 'tolsf': vector of tolerance scale factors, gre...
# Same variable as before b = 2.5 # Again the solution method is the same; we are just passing in a new value of b sol, info = odeint(bruss_odeint, y0, t, args=(a, b), full_output=True) # Make the plot plt.figure() plt.plot(t, sol[:, 0]) plt.plot(t, sol[:, 1]) plt.xlabel('Time (a.u.)') plt.ylabel('Concentration (a.u.)'...
6_Optimization_Integration_ODEs.ipynb
apozas/BIST-Python-Bootcamp
gpl-3.0
Since we are simulating both $[X]$ and $[Y]$, we can quite trivially plot one against the other in a phase plane.
# Steady-state behaviour, for a longer time b = 1.0 t = np.linspace(0, 50, 501) # Construct a grid of initial points in the phase plane X, Y = np.meshgrid(np.linspace(0, 2, 5), np.linspace(0, 2, 5)) plt.figure() for y0 in zip(X.ravel(), Y.ravel()): sol, info = odeint(bruss_odeint, y0, t, args=(a, b), full_output...
6_Optimization_Integration_ODEs.ipynb
apozas/BIST-Python-Bootcamp
gpl-3.0
If we're interested in seeing approximately when the transition from a stable steady state to a limit cycle occurs, we might instead plot a number of trajectories, using different values of $B$ rather than different intial conditions. _Aside: Numerical methods ('continuation') for finding the actual value of $B$ at whi...
from scipy.integrate import ode
6_Optimization_Integration_ODEs.ipynb
apozas/BIST-Python-Bootcamp
gpl-3.0
⚠ Warning ⚠ the arguments of the right-hand-side function $f(t, y)$, that is passed to ode(), are reversed relative to odeint()! I.e., - odeint expects a RHS function of the form func(y, t, ...) - ode expects a RHS function of the form func(t, y, ...) Consequently, we define a new function for the Brusselator, wher...
def bruss_ode(t, y, a, b): """The brusselator system, defined for scipy.integrate.ode""" # Unpack both species X, Y = y # Derivatives dydt = [ a + Y*(X**2) - (b + 1)*X, # d[X]/dt b*X - Y*(X**2), # d[Y]/dt ] return dydt
6_Optimization_Integration_ODEs.ipynb
apozas/BIST-Python-Bootcamp
gpl-3.0
Aside: We could also define this function just by swapping the arguments t and y in a wrapper function. This stops us from repeating code unnecessarily. One way of doing this is as follows: python def bruss_ode(t, y, a, b): return bruss_odeint(y, t, a, b) Generating a solution of the system is quite straightforwar...
def make_plot(traj): """A helper function to plot trajectories""" t = traj[:, 0] y = traj[:, 1:] plt.figure() plt.plot(t, y[:, 0]) plt.plot(t, y[:, 1]) plt.xlabel('Time (a.u.)') plt.ylabel('Concentration (a.u.)') plt.legend(['[X]', '[Y]'])
6_Optimization_Integration_ODEs.ipynb
apozas/BIST-Python-Bootcamp
gpl-3.0
Dopri5 Solver
# Define parameters as before a = 1.0 b = 2.5 # Define initial conditions y0 = [0.5, 0.5] t0 = 0 # Final time t1 = 25 # Define the ODE solver object solver = ode(bruss_ode).set_integrator('dopri5', nsteps=10000) # System/solver parameters are set as properties on the object solver.set_initial_value(y0, t0).set_f_pa...
6_Optimization_Integration_ODEs.ipynb
apozas/BIST-Python-Bootcamp
gpl-3.0
Vode Solver
# Define parameters as before a = 1.0 b = 10 # Define initial conditions y0 = [0.5, 0.5] t0 = 0 # Final time t1 = 100 # Define the ODE solver object solver = ode(bruss_ode).set_integrator('vode', method='bdf') # System/solver parameters are set as properties on the object solver.set_initial_value(y0, t0).set_f_para...
6_Optimization_Integration_ODEs.ipynb
apozas/BIST-Python-Bootcamp
gpl-3.0
Some Performance Improvements: Using the Jacobian We can specify the Jacobian, if known, to help the solver along a little bit. This will generally make the solution faster, and potentially allow the solver to perform fewer steps by providing knowledge about the system's derivatives a priori. More advanced packages, s...
def bruss_jac(t, y, a, b): """Jacobian function of the Brusselator.""" j = np.empty((2, 2)) j[0, 0] = 2*y[0]*y[1] - (b + 1) j[0, 1] = y[0]**2 j[1, 0] = b - 2*y[0]*y[1] j[1, 1] = - y[0]**2 return j # Previous trajectory old_trajectory = traj.copy() # Define parameters as before a = 1.0 b = ...
6_Optimization_Integration_ODEs.ipynb
apozas/BIST-Python-Bootcamp
gpl-3.0
An Illustration of Adaptive Sampling One thing to bear in mind is that it's worth using an integration scheme that supports adaptive sampling of the integration step. this means that when the derivative is large, small steps are taken and vice versa; as a result, simulations tend to be more efficient. What does this lo...
# Sampling density of new trajectory, as timeseries plt.figure(figsize=(12, 4)) plt.plot(traj[:, 0], traj[:, 1], '.') plt.xlabel('Time') plt.ylabel('[X]')
6_Optimization_Integration_ODEs.ipynb
apozas/BIST-Python-Bootcamp
gpl-3.0
It is quite obvious here that the sampling is dense in the regions where changes in $[X]$ are steep, and spreads out significantly in the regions where the gradient is small. Closing Comments Finally, in reality you will probably want to do some more in-depth experiments and analysis with your system (and your system m...
from scipy.optimize import curve_fit
6_Optimization_Integration_ODEs.ipynb
apozas/BIST-Python-Bootcamp
gpl-3.0
In order to test the performance of the curve fitting provided by scipy, we will generate some synthetic data. This data will take the form $ A \sin (\omega (x - t)) $, i.e., a sinusoidal curve with amplitude $A$, frequency $\omega$ and horizontal offset $t$.
def sinus(x, A, t, omega): """Sine wave, over x A: the amplitude omega: the frequency t: the horizontal translation of the curve """ return A*np.sin(omega*(t + x)) # The range of x over which we will observe the function x = np.linspace(0, 2*np.pi, 100) # The 'true' data, underlyin...
6_Optimization_Integration_ODEs.ipynb
apozas/BIST-Python-Bootcamp
gpl-3.0
To make our task a bit easier for this illustrative example we fix a couple of parameters and define a new function with these ($A = 1.0$ and $t = 0.0$), with only the frequency varying.
def fixed_sinus(x, p): """Sinusoidal curve with all parameters fixed apart from frequency. p: frequency """ A = 1.0 t = 0.0 return sinus(x, A, t, p)
6_Optimization_Integration_ODEs.ipynb
apozas/BIST-Python-Bootcamp
gpl-3.0
We can now try to fit this function to our noisy 'measured' data.
# Curve fit function: fits fixedSinus to measured data over x popt, pcov = curve_fit(fixed_sinus, x, y_measured) # Success? print('*** Fitted value of wavelength was: ', popt, '\n') plt.plot(x, y_measured, '*g') plt.plot(x, fixed_sinus(x, popt), '--k') plt.legend(['Experimental data', 'Fitted model'])
6_Optimization_Integration_ODEs.ipynb
apozas/BIST-Python-Bootcamp
gpl-3.0
Hmm... This is clearly quite wrong! It looks like although the function is quite powerful, maybe it needs a little help. We can sugegst an initial value for the unknown parameter to see if that helps:
# Curve fit function: fits fixedSinus to measured data over x # Now we add the keyword argument p0, which specifies an initial guess popt, pcov = curve_fit(fixed_sinus, x, y_measured, p0=1.5) # Success? print('*** Fitted value of wavelength was: ', popt, '\n') plt.plot(x, y_measured, '*g') plt.plot(x, fixed_sinus(x, ...
6_Optimization_Integration_ODEs.ipynb
apozas/BIST-Python-Bootcamp
gpl-3.0
Much better! Obviously this is not great as in general you may not know a good starting parameter value (although you should have an idea of bounds and constraints especially if your model is not too abstract). One way of getting around this is to initialise your fitting function from a bounded range of random initial ...
def objective_function(par): """Compute the sum of squares difference between the measured data and model output.""" # The current model prediction, based on the current parameters' values y_model = sinus(x, *par) # Sum-of-squares difference between the model and 'measured' data return np.sum(np.pow...
6_Optimization_Integration_ODEs.ipynb
apozas/BIST-Python-Bootcamp
gpl-3.0
The scipy.optimize.minimize function provides a general interface for minimization.
from scipy.optimize import minimize # We attempt to minimize our objective # This function now contains the full (3 parameter) sin function, # and so we need to provide 3 starting points; we choose [0.5, 0.5, 0.5] opt = minimize(objective_function, [0.5]*3) print('Optimal parameters: ') print('Amplitude: ', opt.x[0]) ...
6_Optimization_Integration_ODEs.ipynb
apozas/BIST-Python-Bootcamp
gpl-3.0
Not bad, considering it is more generic. If we wanted further control over the process, we can also provide bounds as an optional keyword argument to the minimizer:
# Here we specify that the parameters must all be positive bopt = minimize(objective_function, np.random.rand(3), bounds=[(0, None)]*3) print('Optimal parameters: ') print('Amplitude: ', bopt.x[0]) print('Offset: ', bopt.x[1]) print('Frequency: ', bopt.x[2]) plt.plot(x, y_measured, '*g') plt.plot(x, sinus(x, *bopt.x),...
6_Optimization_Integration_ODEs.ipynb
apozas/BIST-Python-Bootcamp
gpl-3.0
First, load up the data First you're going to want to create a data frame from the dailybots.csv file which can be found in the data directory. You should be able to do this with the pd.read_csv() function. Take a minute to look at the dataframe because we are going to be using it for this entire worksheet.
data = pd.read_csv( '../../data/dailybots.csv' ) #Look at a summary of the data data.describe() data['botfam'].value_counts()
Notebooks/EDA/EDA Worksheet - Python Version - Answers.ipynb
cgivre/oreilly-sec-ds-fundamentals
apache-2.0