markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Substrings can be indexed using string[start:end] | sample = MS2_spectrum[0:5]
sample # Note: The character at position 5 is not included in the substring.
ion = MS2_spectrum[10:13]
ion
file_format = MS2_spectrum[-3:]
file_format | Python_tutorial.ipynb | Michaelt293/ANZSMS-Programming-workshop | cc0-1.0 |
Type conversion - string to float | type(ion)
float(ion) | Python_tutorial.ipynb | Michaelt293/ANZSMS-Programming-workshop | cc0-1.0 |
Collection data types
Lists
Lists are mutable (i.e., modifiable), ordered collections of items. Lists are created by enclosing a collection of items with square brackets. An empty list may also be created simply by assigning [] to a variable, i.e., empty_list = []. | MS_files = ["MS_spectrum", "MS2_405", "MS2_471", "MS2_495"]
MS_files | Python_tutorial.ipynb | Michaelt293/ANZSMS-Programming-workshop | cc0-1.0 |
Indexing in lists is the same as for strings | MS_files[2] | Python_tutorial.ipynb | Michaelt293/ANZSMS-Programming-workshop | cc0-1.0 |
Several list 'methods' exist for manipulating lists | MS_files.remove("MS2_405")
MS_files
MS_files.append("MS3_225")
MS_files | Python_tutorial.ipynb | Michaelt293/ANZSMS-Programming-workshop | cc0-1.0 |
Tuples
Tuples are immutable (i.e., can't modified after their creation), ordered collections of items and are the simplist collection data type. Tuples are created by enclosing a collection of items by parentheses). | Fe_isotopes = (53.9, 55.9, 56.9, 57.9)
Fe_isotopes | Python_tutorial.ipynb | Michaelt293/ANZSMS-Programming-workshop | cc0-1.0 |
Indexing | Fe_isotopes[0] | Python_tutorial.ipynb | Michaelt293/ANZSMS-Programming-workshop | cc0-1.0 |
Dictionaries
Dictionaries are mutable, unordered collections of key: value pairs. Dictionaries are created created by enclosing key: value pairs with curly brackets. Importantly, keys must be hashable. This means, for example, that lists can't be used as keys since the items inside a list may be modified. | carbon_isotopes = {"12": 0.9893, "13": 0.0107} | Python_tutorial.ipynb | Michaelt293/ANZSMS-Programming-workshop | cc0-1.0 |
Fetching the value for a certain key | carbon_isotopes["12"] | Python_tutorial.ipynb | Michaelt293/ANZSMS-Programming-workshop | cc0-1.0 |
Dictionary methods | carbon_isotopes.keys()
carbon_isotopes.values()
carbon_isotopes.items() | Python_tutorial.ipynb | Michaelt293/ANZSMS-Programming-workshop | cc0-1.0 |
Sets
Sets are another data type which are like an unordered list with no dublicates. They are especially useful for finding all the unique items from a list as shown below. | phospholipids = ["PA(16:0/18:1)", "PA(16:0/18:2)", "PC(14:0/16:0)", "PC(16:0/16:1)", "PC(16:1/16:2)"]
# Lets assume we apply a function that finds the type of phospholipid name to
phospholipid_fatty_acids = ["16:0", "18:1", "16:0", "18:2", "14:0", "16:0", "16:0", "16:1", "16:1", "16:2"]
unique_fatty_acids = set(phosp... | Python_tutorial.ipynb | Michaelt293/ANZSMS-Programming-workshop | cc0-1.0 |
Boolean operators
Boolean operators asses the truth or falseness of a statement. | Ag > Au
Ag < Au
Ag == 106.9
Au >= 100
Ag <= Au and Ag > 200
Ag <= Au or Ag > 200 | Python_tutorial.ipynb | Michaelt293/ANZSMS-Programming-workshop | cc0-1.0 |
Conditional statements
Code is only executed if the conditional statement is evaluated as True. In the following example, Ag has a value of greater than 100 and therefore only the "Ag is greater than 100 Da" string is printed. A colon follows the conditional statement and the following code block is indented by 4 space... | if Ag < 100:
print("Ag is less than 100 Da")
elif Ag > 100:
print("Ag is greater than 100 Da.")
else:
print("Ag is equal to 100 Da.") | Python_tutorial.ipynb | Michaelt293/ANZSMS-Programming-workshop | cc0-1.0 |
While loops
While loops repeat the execution of a code block while a condition is evaulated as True. When using while loops, be careful not to make an infinite loop where the conditional statement never evaluates as False. (Note: You could, however, use 'break' to break from an infinite loop.) | mass_spectrometers = 0
while mass_spectrometers < 5:
print("Ask for money")
mass_spectrometers = mass_spectrometers + 1
# Comment: This can be written as mass_spectrometers += 1
print("Number of mass spectrometers equals", mass_spectrometers)
print("\nNow we need more lab space") | Python_tutorial.ipynb | Michaelt293/ANZSMS-Programming-workshop | cc0-1.0 |
For loops
For loops iterate over each item of collection data types (lists, tuples, dictionaries and sets). For loops can also be used to loop over the characters of a string. In fact, this fact will be utilised later to evaluate each amino acid residue of a peptide string. | lipid_masses = [674.5, 688.6, 690.6, 745.7]
Na = 23.0
lipid_Na_adducts = []
for mass in lipid_masses:
lipid_Na_adducts.append(mass + Na)
lipid_Na_adducts | Python_tutorial.ipynb | Michaelt293/ANZSMS-Programming-workshop | cc0-1.0 |
List comprehension
The following is a list comprehension which performs the same operation of the for loop above but in less lines of code. | adducts_comp = [mass + Na for mass in lipid_masses]
adducts_comp | Python_tutorial.ipynb | Michaelt293/ANZSMS-Programming-workshop | cc0-1.0 |
We could also add a predicate to a list comprehension. Here, we calculate the mass of lipids less than 700 Da. | adducts_comp = [mass + Na for mass in lipid_masses if mass < 700]
adducts_comp | Python_tutorial.ipynb | Michaelt293/ANZSMS-Programming-workshop | cc0-1.0 |
While and for loops with conditional statements
Both while and for loops can be combined with conditional statements for greater control of flow within a program. | mass_spectrometers = 0
while mass_spectrometers < 5:
mass_spectrometers += 1
print("Number of mass spectrometers equals", mass_spectrometers)
if mass_spectrometers == 1:
print("Woohoo, the first of many!")
elif mass_spectrometers == 5:
print("That'll do for now.")
else:
print... | Python_tutorial.ipynb | Michaelt293/ANZSMS-Programming-workshop | cc0-1.0 |
Exercise: Calculate peptide masses
In the following example, we will calculate the mass of a peptide from a string containing one letter amino acid residue codes. For example, peptide = "GASPV". To do this, we will first need a dictionary containing the one letter codes as keys and the masses of the amino acid residues... | amino_dict = {
'G': 57.02147,
'A': 71.03712,
'S': 87.03203,
'P': 97.05277,
'V': 99.06842,
'T': 101.04768,
'C': 103.00919,
'I': 113.08407,
'L': 113.08407,
'N': 114.04293,
'D': 115.02695,
'Q': 128.05858,
'K': 128.09497,
'E': 129.0426,
'M': 131.04049,
'H': 13... | Python_tutorial.ipynb | Michaelt293/ANZSMS-Programming-workshop | cc0-1.0 |
Functions
Functions perform a specified task when called during the execution of a program. Functions reduce the amount of code that needs to be written and greatly improves code readability. (Note: readability matters!) The for loop created above is better placed in a function so that the for loop doesn't need to be r... | def peptide_mass(peptide):
mass = 18.010565
for amino_acid in peptide:
mass += amino_dict[amino_acid]
return mass
peptide_mass(peptide_name) | Python_tutorial.ipynb | Michaelt293/ANZSMS-Programming-workshop | cc0-1.0 |
User input
A simple means to gather user inputted data is to use input. This will prompt the user to enter data which may be used within the program. In the example below, we prompt the user to enter a peptide name. The peptide name is then used for the function call to calculate the peptide's mass. | user_peptide = input("Enter peptide name: ")
peptide_mass(user_peptide) | Python_tutorial.ipynb | Michaelt293/ANZSMS-Programming-workshop | cc0-1.0 |
Exceptions
An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.
You've already seen some exceptions in the Debugging lesson.
*
Many programs want to know about exceptions when they occur. For example, if the input to a program is a file ... | def divide(numerator, denominator):
result = numerator/denominator
print("result = %f" % result)
divide(1.0, 0)
def divide1(numerator, denominator):
try:
GARBAGE
result = numerator/denominator
print("result = %f" % result)
except (ZeroDivisionError, NameError) as err:
i... | week_4/Exceptions.ipynb | UWSEDS/LectureNotes | bsd-2-clause |
Why didn't we catch this SyntaxError? | # Handle division by 0 by using a small number
SMALL_NUMBER = 1e-3
def divide3(numerator, denominator):
try:
result = numerator/denominator
except ZeroDivisionError:
result = numerator/SMALL_NUMBER
print("result = %f" % result)
except Exception as err:
print("Different error ... | week_4/Exceptions.ipynb | UWSEDS/LectureNotes | bsd-2-clause |
What do you do when you get an exception?
First, you can feel relieved that you caught a problematic element of your software! Yes, relieved. Silent fails are much worse. (Again, another plug for testing.)
Generating Exceptions
Why generate exceptions? (Don't I have enough unintentional errors?) | import pandas as pd
def validateDF(df):
""""
:param pd.DataFrame df: should have a column named "hours"
"""
if not "hours" in df.columns:
raise ValueError("DataFrame should have a column named 'hours'.")
df = pd.DataFrame({'hours': range(10) })
validateDF(df)
class SeattleCrimeError(Exception)... | week_4/Exceptions.ipynb | UWSEDS/LectureNotes | bsd-2-clause |
Determine the costs of processing existing articles
Based on complete data files from through 2019-09-07.
Each 1000 words of an article submitted is one "unit", rounded up.
1,496,665 units total = $2487 to process at once, or 300 months in free batches of 5k... | crimetags = tagnews.CrimeTags()
df_all = tagnews.load_data()
df_all['read_date'] = df_all['created'].str.slice(0, 10)
### Limiting it to last two years because the data volume is unstable before that
df = df_all.loc[df_all['read_date'] >= '2017-01-01']
del df_all
### Number of units to process title and article throug... | lib/notebooks/senteval_budgeting.ipynb | chicago-justice-project/article-tagging | mit |
Relevance scoring/binning | ### Full dataset takes up too much memory, so dropping all but the most recent now
### This keeps 276122 of the original 1.5e6, or a little less than 1/5th of the total
df2 = df.loc[df['read_date'] >= '2019-03-01']
del df
new_units = df2['n_units'].sum()
downscale = new_units/units
print(new_units, downscale)
### Ass... | lib/notebooks/senteval_budgeting.ipynb | chicago-justice-project/article-tagging | mit |
(1b) Plural
Vamos criar uma função que transforma uma palavra no plural adicionando uma letra 's' ao final da string. Em seguida vamos utilizar a função map() para aplicar a transformação em cada palavra do RDD.
Em Python (e muitas outras linguagens) a concatenação de strings é custosa. Uma alternativa melhor é criar ... | # EXERCICIO
def Plural(palavra):
"""Adds an 's' to `palavra`.
Args:
palavra (str): A string.
Returns:
str: A string with 's' added to it.
"""
return <COMPLETAR>
print Plural('gato')
help(Plural)
assert Plural('rato')=='ratos', 'resultado incorreto!'
print 'OK' | Spark/Lab2_Spark_PySpark.ipynb | folivetti/BIGDATA | mit |
(1c) Aplicando a função ao RDD
Transforme cada palavra do nosso RDD em plural usando map()
Em seguida, utilizaremos o comando collect() que retorna a RDD como uma lista do Python. | # EXERCICIO
pluralRDD = palavrasRDD.<COMPLETAR>
print pluralRDD.collect()
assert pluralRDD.collect()==['gatos','elefantes','ratos','ratos','gatos'], 'valores incorretos!'
print 'OK' | Spark/Lab2_Spark_PySpark.ipynb | folivetti/BIGDATA | mit |
Nota: utilize o comando collect() apenas quando tiver certeza de que a lista caberá na memória. Para gravar os resultados de volta em arquivo texto ou base de dados utilizaremos outro comando.
(1d) Utilizando uma função lambda
Repita a criação de um RDD de plurais, porém utilizando uma função lambda. | # EXERCICIO
pluralLambdaRDD = palavrasRDD.<COMPLETAR>
print pluralLambdaRDD.collect()
assert pluralLambdaRDD.collect()==['gatos','elefantes','ratos','ratos','gatos'], 'valores incorretos!'
print 'OK' | Spark/Lab2_Spark_PySpark.ipynb | folivetti/BIGDATA | mit |
(1e) Tamanho de cada palavra
Agora use map() e uma função lambda para retornar o número de caracteres em cada palavra. Utilize collect() para armazenar o resultado em forma de listas na variável destino. | # EXERCICIO
pluralTamanho = (pluralRDD
<COMPLETAR>
)
print pluralTamanho
assert pluralTamanho==[5,9,5,5,5], 'valores incorretos'
print "OK" | Spark/Lab2_Spark_PySpark.ipynb | folivetti/BIGDATA | mit |
(1f) RDDs de pares e tuplas
Para contar a frequência de cada palavra de maneira distribuída, primeiro devemos atribuir um valor para cada palavra do RDD. Isso irá gerar um base de dados (chave, valor). Desse modo podemos agrupar a base através da chave, calculando a soma dos valores atribuídos. No nosso caso, vamos at... | # EXERCICIO
palavraPar = palavrasRDD.<COMPLETAR>
print palavraPar.collect()
assert palavraPar.collect() == [('gato',1),('elefante',1),('rato',1),('rato',1),('gato',1)], 'valores incorretos!'
print "OK" | Spark/Lab2_Spark_PySpark.ipynb | folivetti/BIGDATA | mit |
Parte 2: Manipulando RDD de tuplas
Vamos manipular nossa RDD para contar as palavras do texto.
(2a) Função groupByKey()
A função groupByKey() agrupa todos os valores de um RDD através da chave (primeiro elemento da tupla) agregando os valores em uma lista.
Essa abordagem tem um ponto fraco pois:
A operação requer... | # EXERCICIO
palavrasGrupo = palavraPar.groupByKey()
for chave, valor in palavrasGrupo.collect():
print '{0}: {1}'.format(chave, list(valor))
assert sorted(palavrasGrupo.mapValues(lambda x: list(x)).collect()) == [('elefante', [1]), ('gato',[1, 1]), ('rato',[1, 2])],
'Valores incorretos!'
print "OK" | Spark/Lab2_Spark_PySpark.ipynb | folivetti/BIGDATA | mit |
(2b) Calculando as contagens
Após o groupByKey() nossa RDD contém elementos compostos da palavra, como chave, e um iterador contendo todos os valores correspondentes aquela chave.
Utilizando a transformação map() e a função sum(), contrua um novo RDD que consiste de tuplas (chave, soma). | # EXERCICIO
contagemGroup = palavrasGrupo.<COMPLETAR>
print contagemGroup.collect()
assert sorted(contagemGroup.collect())==[('elefante',1), ('gato',2), ('rato',2)], 'valores incorretos!'
print "OK" | Spark/Lab2_Spark_PySpark.ipynb | folivetti/BIGDATA | mit |
(2c) reduceByKey
Um comando mais interessante para a contagem é o reduceByKey() que cria uma nova RDD de tuplas.
Essa transformação aplica a transformação reduce() vista na aula anterior para os valores de cada chave. Dessa forma, a função de transformação pode ser aplicada em cada partição local para depois ser envi... | # EXERCICIO
contagem = palavraPar.<COMPLETAR>
print contagem.collect()
assert sorted(contagem.collect())==[('elefante',1), ('gato',2), ('rato',2)], 'valores incorretos!'
print "OK" | Spark/Lab2_Spark_PySpark.ipynb | folivetti/BIGDATA | mit |
(2d) Agrupando os comandos
A forma mais usual de realizar essa tarefa, partindo do nosso RDD palavrasRDD, é encadear os comandos map e reduceByKey em uma linha de comando. | # EXERCICIO
contagemFinal = (palavrasRDD
<COMPLETAR>
<COMPLETAR>
)
print contagemFinal.collect()
assert sorted(contagemFinal)==[('elefante',1), ('gato',2), ('rato',2)], 'valores incorretos!'
print "OK" | Spark/Lab2_Spark_PySpark.ipynb | folivetti/BIGDATA | mit |
Parte 3: Encontrando as palavras únicas e calculando a média de contagem
(3a) Palavras Únicas
Calcule a quantidade de palavras únicas do RDD. Utilize comandos de RDD da API do PySpark e alguma das últimas RDDs geradas nos exercícios anteriores. | # EXERCICIO
palavrasUnicas = <COMPLETAR>
print palavrasUnicas
assert palavrasUnicas==3, 'valor incorreto!'
print "OK" | Spark/Lab2_Spark_PySpark.ipynb | folivetti/BIGDATA | mit |
(3b) Calculando a Média de contagem de palavras
Encontre a média de frequência das palavras utilizando o RDD contagem.
Note que a função do comando reduce() é aplicada em cada tupla do RDD. Para realizar a soma das contagens, primeiro é necessário mapear o RDD para um RDD contendo apenas os valores das frequências (se... | # EXERCICIO
# add é equivalente a lambda x,y: x+y
from operator import add
total = (contagemFinal
<COMPLETAR>
<COMPLETAR>
)
media = total / float(palavrasUnicas)
print total
print round(media, 2)
assert round(media, 2)==1.67, 'valores incorretos!'
print "OK" | Spark/Lab2_Spark_PySpark.ipynb | folivetti/BIGDATA | mit |
Parte 4: Aplicar nosso algoritmo em um arquivo
(4a) Função contaPalavras
Para podermos aplicar nosso algoritmo genéricamente em diversos RDDs, vamos primeiro criar uma função para aplicá-lo em qualquer fonte de dados. Essa função recebe de entrada um RDD contendo uma lista de chaves (palavras) e retorna um RDD de tu... | # EXERCICIO
def contaPalavras(chavesRDD):
"""Creates a pair RDD with word counts from an RDD of words.
Args:
chavesRDD (RDD of str): An RDD consisting of words.
Returns:
RDD of (str, int): An RDD consisting of (word, count) tuples.
"""
return (chavesRDD
<COMPLETAR>
... | Spark/Lab2_Spark_PySpark.ipynb | folivetti/BIGDATA | mit |
(4b) Normalizando o texto
Quando trabalhamos com dados reais, geralmente precisamos padronizar os atributos de tal forma que diferenças sutis por conta de erro de medição ou diferença de normatização, sejam desconsideradas. Para o próximo passo vamos padronizar o texto para:
Padronizar a capitalização das palavras (... | # EXERCICIO
import re
def removerPontuacao(texto):
"""Removes punctuation, changes to lower case, and strips leading and trailing spaces.
Note:
Only spaces, letters, and numbers should be retained. Other characters should should be
eliminated (e.g. it's becomes its). Leading and trailing spac... | Spark/Lab2_Spark_PySpark.ipynb | folivetti/BIGDATA | mit |
(4c) Carregando arquivo texto
Para a próxima parte vamos utilizar o livro Trabalhos completos de William Shakespeare do Projeto Gutenberg.
Para converter um texto em uma RDD, utilizamos a função textFile() que recebe como entrada o nome do arquivo texto que queremos utilizar e o número de partições.
O nome do arquivo... | # Apenas execute a célula
import os.path
import urllib
url = 'http://www.gutenberg.org/cache/epub/100/pg100.txt' # url do livro
arquivo = os.path.join('Data','Aula02','shakespeare.txt') # local de destino: 'Data/Aula02/shakespeare.txt'
if os.path.isfile(arquivo): # verifica se já fizemos download do arquivo
... | Spark/Lab2_Spark_PySpark.ipynb | folivetti/BIGDATA | mit |
(4d) Extraindo as palavras
Antes de poder usar nossa função Before we can use the contaPalavras(), temos ainda que trabalhar em cima da nossa RDD:
Precisamos gerar listas de palavras ao invés de listas de sentenças.
Eliminar linhas vazias.
As strings em Python tem o método split() que faz a separação de uma stri... | # EXERCICIO
shakesPalavrasRDD = shakesRDD.<COMPLETAR>
total = shakesPalavrasRDD.count()
print shakesPalavrasRDD.take(5)
print total | Spark/Lab2_Spark_PySpark.ipynb | folivetti/BIGDATA | mit |
Conforme deve ter percebido, o uso da função map() gera uma lista para cada linha, criando um RDD contendo uma lista de listas.
Para resolver esse problema, o Spark possui uma função análoga chamada flatMap() que aplica a transformação do map(), porém achatando o retorno em forma de lista para uma lista unidimensional. | # EXERCICIO
shakesPalavrasRDD = shakesRDD.flatMap(lambda x: x.split())
total = shakesPalavrasRDD.count()
print shakesPalavrasRDD.top(5)
print total
assert total==927631 or total == 928908, "valor incorreto de palavras!"
print "OK"
assert shakesPalavrasRDD.top(5)==[u'zwaggerd', u'zounds', u'zounds', u'zounds', u'zounds... | Spark/Lab2_Spark_PySpark.ipynb | folivetti/BIGDATA | mit |
(4e) Remover linhas vazias
Para o próximo passo vamos filtrar as linhas vazias com o comando filter(). Uma linha vazia é uma string sem nenhum conteúdo. | # EXERCICIO
shakesLimpoRDD = shakesPalavrasRDD.<COMPLETAR>
total = shakesLimpoRDD.count()
print total
assert total==882996, 'valor incorreto!'
print "OK" | Spark/Lab2_Spark_PySpark.ipynb | folivetti/BIGDATA | mit |
(4f) Contagem de palavras
Agora que nossa RDD contém uma lista de palavras, podemos aplicar nossa função contaPalavras().
Aplique a função em nossa RDD e utilize a função takeOrdered para imprimir as 15 palavras mais frequentes.
takeOrdered() pode receber um segundo parâmetro que instrui o Spark em como ordenar os ele... | # EXERCICIO
top15 = <COMPLETAR>
print '\n'.join(map(lambda (w, c): '{0}: {1}'.format(w, c), top15))
assert top15 == [(u'the', 27361), (u'and', 26028), (u'i', 20681), (u'to', 19150), (u'of', 17463),
(u'a', 14593), (u'you', 13615), (u'my', 12481), (u'in', 10956), (u'that', 10890),
(... | Spark/Lab2_Spark_PySpark.ipynb | folivetti/BIGDATA | mit |
Parte 5: Similaridade entre Objetos
Nessa parte do laboratório vamos aprender a calcular a distância entre atributos numéricos, categóricos e textuais.
(5a) Vetores no espaço Euclidiano
Quando nossos objetos são representados no espaço Euclidiano, medimos a similaridade entre eles através da p-Norma definida por:
$$... | import numpy as np
# Vamos criar uma função pNorm que recebe como parâmetro p e retorna uma função que calcula a pNorma
def pNorm(p):
"""Generates a function to calculate the p-Norm between two points.
Args:
p (int): The integer p.
Returns:
Dist: A function that calculates the p-Norm.
... | Spark/Lab2_Spark_PySpark.ipynb | folivetti/BIGDATA | mit |
(5b) Valores Categóricos
Quando nossos objetos são representados por atributos categóricos, eles não possuem uma similaridade espacial. Para calcularmos a similaridade entre eles podemos primeiro transformar nosso vetor de atrbutos em um vetor binário indicando, para cada possível valor de cada atributo, se ele possui... | # Vamos criar uma função para calcular a distância de Hamming
def Hamming(x,y):
"""Calculates the Hamming distance between two binary vectors.
Args:
x, y (np.array): Array of binary integers x and y.
Returns:
H (int): The Hamming distance between x and y.
"""
return (x!=y).sum()
#... | Spark/Lab2_Spark_PySpark.ipynb | folivetti/BIGDATA | mit |
Now let us implement an extension algorithm. We are leaving out the cancelling step for clarity. | def join(a, b):
"""Return the join of 2 simplices a and b."""
return tuple(sorted(set(a).union(b)))
def extend(K, f):
"""Extend the field to the complex K.
Function on vertices is given in f.
Returns the pair V, C, where V is the dictionary containing discrete gradient vector field
and C is the... | 2015_2016/lab13/Extending values on vertices-template.ipynb | gregorjerse/rt2 | gpl-3.0 |
As usual, we will begin by creating a small dataset to test with. It will consist of 10 samples, where each input observation has four features and targets are scalar values. | nb_samples = 10
X = np.outer(np.arange(1, nb_samples + 1, dtype=np.uint8), np.arange(1, 4 + 1, dtype=np.uint8))
y = np.arange(nb_samples, dtype=np.uint8)
for i in range(nb_samples):
print('Input: {} -> Target: {}'.format(X[i], y[i])) | examples/torch-dataset.ipynb | vicolab/ml-pyxis | mit |
The data is written using a with statement. | with px.Writer(dirpath='data', map_size_limit=10, ram_gb_limit=1) as db:
db.put_samples('input', X, 'target', y) | examples/torch-dataset.ipynb | vicolab/ml-pyxis | mit |
To be sure the data was stored correctly, we will read the data back - again using a with statement. | with px.Reader('data') as db:
print(db) | examples/torch-dataset.ipynb | vicolab/ml-pyxis | mit |
Working with PyTorch | try:
import torch
import torch.utils.data
except ImportError:
raise ImportError('Could not import the PyTorch library `torch` or '
'`torch.utils.data`. Please refer to '
'https://pytorch.org/ for installation instructions.') | examples/torch-dataset.ipynb | vicolab/ml-pyxis | mit |
In pyxis.torch we have implemented a wrapper around torch.utils.data.Dataset called pyxis.torch.TorchDataset. This object is not imported into the pyxis name space because it relies on PyTorch being installed. As such, we first need to import pyxis.torch: | import pyxis.torch as pxt | examples/torch-dataset.ipynb | vicolab/ml-pyxis | mit |
pyxis.torch.TorchDataset has a single constructor argument: dirpath, i.e. the location of the pyxis LMDB. | dataset = pxt.TorchDataset('data') | examples/torch-dataset.ipynb | vicolab/ml-pyxis | mit |
The pyxis.torch.TorchDataset object has only three methods: __len__, __getitem__, and __repr__, each of which you can see an example of below: | len(dataset)
dataset[0]
dataset | examples/torch-dataset.ipynb | vicolab/ml-pyxis | mit |
pyxis.torch.TorchDataset can be directly combined with torch.utils.data.DataLoader to create an iterator type object: | use_cuda = True and torch.cuda.is_available()
kwargs = {"num_workers": 4, "pin_memory": True} if use_cuda else {}
loader = torch.utils.data.DataLoader(dataset, batch_size=2, shuffle=False, **kwargs)
for i, d in enumerate(loader):
print('Batch:', i)
print('\t', d['input'])
print('\t', d['target']) | examples/torch-dataset.ipynb | vicolab/ml-pyxis | mit |
Parsing the Data
We got some datetimes back from the API -- but what do these mean?!
We can use python to find out!
Lets use a new library, arrow, to parse that.
http://crsmithdev.com/arrow/ | import arrow | SHARE_Curation_Associates_Overview.ipynb | erinspace/share_tutorials | apache-2.0 |
open your terminal
pip install arrow | from arrow.arrow import Arrow
for item in data['response']:
datetime = Arrow.fromtimestamp(item['risetime'])
print(
'The ISS will be visable over Charlottesville on {} at {} for {} seconds.'.format(
datetime.date(),
datetime.time(),
item['duration']
)
) | SHARE_Curation_Associates_Overview.ipynb | erinspace/share_tutorials | apache-2.0 |
pokeapi = 'http://pokeapi.co/api/v2/generation/1/'
pokedata = requests.get(pokeapi).json()
# Take that data, print out a nicely formatted version of the first 5 results
print(json.dumps(pokedata['pokemon_species'][:5], indent=4))
# Let's get more info about the first pokemon on the list
# By following the chain of l... | SHARE_Curation_Associates_Overview.ipynb | erinspace/share_tutorials | apache-2.0 | |
Some Great APIs YOU can use!
Twitter
Google Maps
Twillio
Yelp
Spotify
Genius
...and so many more!
Many require some kind of authentication, so aren't as simple as the ISS, or PokeAPI.
Access an OAI-PMH Feed!
Many institutions have an OAI-PMH based API.
This is great because they all have a unified way of interacting ... | from furl import furl
vt_url = furl('http://vtechworks.lib.vt.edu/oai/request')
vt_url.args['verb'] = 'ListRecords'
vt_url.args['metadataPrefix'] = 'oai_dc'
vt_url.url
data = requests.get(vt_url.url)
data.content | SHARE_Curation_Associates_Overview.ipynb | erinspace/share_tutorials | apache-2.0 |
Let's parse this!
conda install lxml | from lxml import etree
etree_element = etree.XML(data.content)
etree_element
etree_element.getchildren()
# A little namespace parsing and cleanup
namespaces = etree_element.nsmap
namespaces['ns0'] = etree_element.nsmap[None]
del namespaces[None]
records = etree_element.xpath('//ns0:record', namespaces=namespaces)
... | SHARE_Curation_Associates_Overview.ipynb | erinspace/share_tutorials | apache-2.0 |
SHARE Search API
Also a fantastic resource!
One Way to Access Data
Instead of writing custom code to parse both data coming from JSON and XML APIs
The SHARE Search Schema
The SHARE search API is built on a tool called elasticsearch. It lets you search a subset of SHARE's normalized metadata in a simple format.
Here ar... | SHARE_SEARCH_API = 'https://staging-share.osf.io/api/search/abstractcreativework/_search'
from furl import furl
search_url = furl(SHARE_SEARCH_API)
search_url.args['size'] = 3
recent_results = requests.get(search_url.url).json()
recent_results = recent_results['hits']['hits']
recent_results
print('The request URL ... | SHARE_Curation_Associates_Overview.ipynb | erinspace/share_tutorials | apache-2.0 |
Sending a Query to the SHARE Search API
First, we'll define a function to do the hard work for us.
It will take 2 parameters, a URL, and a query to send to the search API. | import json
def query_share(url, query):
# A helper function that will use the requests library,
# pass along the correct headers, and make the query we want
headers = {'Content-Type': 'application/json'}
data = json.dumps(query)
return requests.post(url, headers=headers, data=data).json()
search... | SHARE_Curation_Associates_Overview.ipynb | erinspace/share_tutorials | apache-2.0 |
Other SHARE APIs
SHARE has a host of other APIs that provide direct access to the data stored in SHARE.
You can read more about the SHARE Data Models here: http://share-research.readthedocs.io/en/latest/share_models.html | SHARE_API = 'https://staging-share.osf.io/api/'
share_endpoints = requests.get(SHARE_API).json()
share_endpoints | SHARE_Curation_Associates_Overview.ipynb | erinspace/share_tutorials | apache-2.0 |
Visit the API In Your Browser
You can visit https://staging-share.osf.io/api/ and see the data formatted in "pretty printed" JSON
SHARE Providers API
Access the information about the providers that SHARE harvests from | SHARE_PROVIDERS = 'https://staging-share.osf.io/api/providers/'
data = requests.get(SHARE_PROVIDERS).json()
data | SHARE_Curation_Associates_Overview.ipynb | erinspace/share_tutorials | apache-2.0 |
We can print that out a little nicer
Using a loop and using the lookups that'd we'd like! | print('Here are the first 10 Providers:')
for source in data['results']:
print(
'{}\n{}\n{}\n'.format(
source['long_title'],
source['home_page'],
source['provider_name']
)
) | SHARE_Curation_Associates_Overview.ipynb | erinspace/share_tutorials | apache-2.0 |
Fixed-point approximation
The regression results are converted to a fixed-point representation,
with the exponent in Q6 and the scale in Q3. | plt.figure(figsize=(7, 6))
plt.axis('equal')
plt.xticks([0, 10])
plt.yticks([0, 10])
plt.minorticks_on()
plt.grid(b=True, which='major')
plt.grid(b=True, which='minor', alpha=0.2)
segments = dict()
for b, accumulator in partials.items():
Ax, Ay, Sxy, Sxx, n, minx, maxx = accumulator
fti = b & 3
beta = Sx... | doc/regress_log-bitrate_wrt_log-quantizer.ipynb | xiph/rav1e | bsd-2-clause |
The endpoints of each linear regression, rounding only the exponent, are detailed in the following output.
We use a cubic interpolation of these points to adjust the segment boundaries. | pprint(segments) | doc/regress_log-bitrate_wrt_log-quantizer.ipynb | xiph/rav1e | bsd-2-clause |
Piecewise-linear fit
We applied a 3-segment piecewise-linear fit. The boundaries were aligned to integer values of pixels-per-bit,
while optimizing for similarity to a cubic interpolation of the control points
(log-quantizer as a function of log-bitrate). | plt.figure(figsize=(7, 6))
plt.axis('equal')
plt.xticks([0, 10])
plt.yticks([0, 10])
plt.minorticks_on()
plt.grid(b=True, which='major')
plt.grid(b=True, which='minor', alpha=0.2)
from scipy import optimize
for ft, xy in segments.items():
f = np.poly1d(np.polyfit(np.array(xy[1]).astype(float), np.array(xy[0]).ast... | doc/regress_log-bitrate_wrt_log-quantizer.ipynb | xiph/rav1e | bsd-2-clause |
MMW production API endpoint base url. | api_url = "https://app.wikiwatershed.org/api/" | MMW_API_landproperties_demo.ipynb | emiliom/stuff | cc0-1.0 |
The job is not completed instantly and the results are not returned directly by the API request that initiated the job. The user must first issue an API request to confirm that the job is complete, then fetch the results. The demo presented here performs automated retries (checks) until the server confirms the job is c... | def get_job_result(api_url, s, jobrequest):
url_tmplt = api_url + "jobs/{job}/"
get_url = url_tmplt.format
result = ''
while not result:
get_req = requests_retry_session(session=s).get(get_url(job=jobrequest['job']))
result = json.loads(get_req.content)['result']
return res... | MMW_API_landproperties_demo.ipynb | emiliom/stuff | cc0-1.0 |
2. Construct AOI GeoJSON for job request
Parameters passed to the "analyze" API requests. | from shapely.geometry import box, MultiPolygon
width = 0.0004 # Looks like using a width smaller than 0.0002 causes a problem with the API?
# GOOS: (-88.5552, 40.4374) elev 240.93. Agriculture Site—Goose Creek (Corn field) Site (GOOS) at IML CZO
# SJER: (-119.7314, 37.1088) elev 403.86. San Joaquin Experimental Rese... | MMW_API_landproperties_demo.ipynb | emiliom/stuff | cc0-1.0 |
3. Issue job requests, fetch job results when done, then examine results. Repeat for each request type | # convenience function, to simplify the request calls, below
def analyze_api_request(api_name, s, api_url, json_payload):
post_url = "{}analyze/{}/".format(api_url, api_name)
post_req = requests_retry_session(session=s).post(post_url, data=json_payload)
jobrequest_json = json.loads(post_req.content)
# F... | MMW_API_landproperties_demo.ipynb | emiliom/stuff | cc0-1.0 |
Issue job request: analyze/land/ | result = analyze_api_request('land', s, api_url, json_payload) | MMW_API_landproperties_demo.ipynb | emiliom/stuff | cc0-1.0 |
Everything below is just exploration of the results. Examine the content of the results (as JSON, and Python dictionaries) | type(result), result.keys() | MMW_API_landproperties_demo.ipynb | emiliom/stuff | cc0-1.0 |
result is a dictionary with one item, survey. This item in turn is a dictionary with 3 items: displayName, name, categories. The first two are just labels. The data are in the categories item. | result['survey'].keys()
categories = result['survey']['categories']
len(categories), categories[1]
land_categories_nonzero = [d for d in categories if d['coverage'] > 0]
land_categories_nonzero | MMW_API_landproperties_demo.ipynb | emiliom/stuff | cc0-1.0 |
Issue job request: analyze/terrain/ | result = analyze_api_request('terrain', s, api_url, json_payload) | MMW_API_landproperties_demo.ipynb | emiliom/stuff | cc0-1.0 |
result is a dictionary with one item, survey. This item in turn is a dictionary with 3 items: displayName, name, categories. The first two are just labels. The data are in the categories item. | categories = result['survey']['categories']
len(categories), categories
[d for d in categories if d['type'] == 'average'] | MMW_API_landproperties_demo.ipynb | emiliom/stuff | cc0-1.0 |
Issue job request: analyze/climate/ | result = analyze_api_request('climate', s, api_url, json_payload) | MMW_API_landproperties_demo.ipynb | emiliom/stuff | cc0-1.0 |
result is a dictionary with one item, survey. This item in turn is a dictionary with 3 items: displayName, name, categories. The first two are just labels. The data are in the categories item. | categories = result['survey']['categories']
len(categories), categories[:2]
ppt = [d['ppt'] for d in categories]
tmean = [d['tmean'] for d in categories]
# ppt is in cm, right?
sum(ppt)
import calendar
import numpy as np
calendar.mdays
# Annual tmean needs to be weighted by the number of days per month
sum(np.asa... | MMW_API_landproperties_demo.ipynb | emiliom/stuff | cc0-1.0 |
to make use of periodicity of the provided data grid, use | m.add( PeriodicBox( boxOrigin, boxSize ) ) | doc/pages/example_notebooks/extragalactic_fields/MHD_models.v4.ipynb | CRPropa/CRPropa3 | gpl-3.0 |
to not follow particles forever, use | m.add( MaximumTrajectoryLength( 400*Mpc ) ) | doc/pages/example_notebooks/extragalactic_fields/MHD_models.v4.ipynb | CRPropa/CRPropa3 | gpl-3.0 |
Uniform injection
The most simple scenario of UHECR sources is a uniform distribution of their sources. This can be realized via use of | source = Source()
source.add( SourceUniformBox( boxOrigin, boxSize )) | doc/pages/example_notebooks/extragalactic_fields/MHD_models.v4.ipynb | CRPropa/CRPropa3 | gpl-3.0 |
Injection following density field
The distribution of gas density can be used as a probability density function for the injection of particles from random positions. | filename_density = "mass-density_clues.dat" ## filename of the density field
source = Source()
## initialize grid to hold field values
mgrid = ScalarGrid( gridOrigin, gridSize, spacing )
## load values to grid
loadGrid( mgrid, filename_density )
## add source module to simulation
source.add( SourceDensityGrid( mgrid ... | doc/pages/example_notebooks/extragalactic_fields/MHD_models.v4.ipynb | CRPropa/CRPropa3 | gpl-3.0 |
Mass Halo injection
Alternatively, for the CLUES models, we also provide a list of mass halo positions. These positions can be used as sources with the same properties by use of the following | import numpy as np
filename_halos = 'clues_halos.dat'
# read data from file
data = np.loadtxt(filename_halos, unpack=True, skiprows=39)
sX = data[0]
sY = data[1] ... | doc/pages/example_notebooks/extragalactic_fields/MHD_models.v4.ipynb | CRPropa/CRPropa3 | gpl-3.0 |
additional source properties | ## use isotropic emission from all sources
source.add( SourceIsotropicEmission() )
## set particle type to be injected
A, Z = 1, 1 # proton
source.add( SourceParticleType( nucleusId(A,Z) ) )
## set injected energy spectrum
Emin, Emax = 1*EeV, 1000*EeV
specIndex = -1
source.add( SourcePowerLawSpectrum( Emin, Emax, spe... | doc/pages/example_notebooks/extragalactic_fields/MHD_models.v4.ipynb | CRPropa/CRPropa3 | gpl-3.0 |
Observer
To register particles, an observer has to be defined. In the provided constrained simulations the position of the Milky Way is, by definition, in the center of the volume. | filename_output = 'data/output_MW.txt'
obsPosition = Vector3d(0.5*size,0.5*size,0.5*size) # position of observer, MW is in center of constrained simulations
obsSize = 800*kpc ## physical size of observer sphere
## initialize observer that registers particles that enter into sphere of given size around its position
... | doc/pages/example_notebooks/extragalactic_fields/MHD_models.v4.ipynb | CRPropa/CRPropa3 | gpl-3.0 |
finally run the simulation by | N = 1000
m.showModules() ## optional, see summary of loaded modules
m.setShowProgress(True) ## optional, see progress during runtime
m.run(source, N, True) ## perform simulation with N particles injected from source | doc/pages/example_notebooks/extragalactic_fields/MHD_models.v4.ipynb | CRPropa/CRPropa3 | gpl-3.0 |
The Data
Let's generate a simple Cepheids-like dataset: observations of $y$ with reported uncertainties $\sigma_y$, at given $x$ values. | import numpy as np
import pylab as plt
xlimits = [0,350]
ylimits = [0,250]
def generate_data(seed=None):
"""
Generate a 30-point data set, with x and sigma_y as standard, but with
y values given by
y = a_0 + a_1 * x + a_2 * x**2 + a_3 * x**3 + noise
"""
Ndata = 30
xbar = 0.5*(xlimits[0] ... | tutorials/old/GPRegression.ipynb | KIPAC/StatisticalMethods | gpl-2.0 |
Fitting a Gaussian Process
Let's follow Jake VanderPlas' example, to see how to work with the scikit-learn v0.18 Gaussian Process regression model. | from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import RBF as SquaredExponential | tutorials/old/GPRegression.ipynb | KIPAC/StatisticalMethods | gpl-2.0 |
Defining a GP
First we define a kernel function, for populating the covariance matrix of our GP. To avoid confusion, a Gaussian kernel is referred to as a "squared exponential" (or a "radial basis function", RBF). The squared exponential kernel has one hyper-parameter, the length scale that is the Gaussian width. | h = 10.0
kernel = SquaredExponential(length_scale=h, length_scale_bounds=(0.01, 1000.0))
gp0 = GaussianProcessRegressor(kernel=kernel, n_restarts_optimizer=9) | tutorials/old/GPRegression.ipynb | KIPAC/StatisticalMethods | gpl-2.0 |
Now, let's draw some samples from the unconstrained process, o equivalently, the prior. Each sample is a function $y(x)$, which we evaluate on a grid. We'll need to assert a value for the kernel hyperparameter $h$, which dictates the correlation length between the datapoints. That will allow us to compute a mean functi... | np.random.seed(1)
xgrid = np.atleast_2d(np.linspace(0, 399, 100)).T
print("y(x) will be predicted on a grid of length", len(xgrid))
# Draw three sample y(x) functions:
draws = gp0.sample_y(xgrid, n_samples=3)
print("Drew 3 samples, stored in an array with shape ", draws.shape) | tutorials/old/GPRegression.ipynb | KIPAC/StatisticalMethods | gpl-2.0 |
Let's plot these, to see what our prior looks like. | # Start a 4-panel figure:
fig = plt.figure(figsize=(10,10))
# Plot our three prior draws:
ax = fig.add_subplot(221)
ax.plot(xgrid, draws[:,0], '-r')
ax.plot(xgrid, draws[:,1], '-g')
ax.plot(xgrid, draws[:,2], '-b', label='Rescaled prior sample $y(x)$')
ax.set_xlim(0, 399)
ax.set_ylim(-5, 5)
ax.set_xlabel('$x$')
ax.set... | tutorials/old/GPRegression.ipynb | KIPAC/StatisticalMethods | gpl-2.0 |
Each predicted $y(x)$ is drawn from a Gaussian of unit variance, and with off-diagonal elements determined by the covariance function.
Try changing h to see what happens to the smoothness of the predictions.
Go back up to the cell where h is assigned, and re-run that cell and the subsequent ones.
For our data to be... | class Rescale():
def __init__(self, y, err):
self.original_data = y
self.original_err = err
self.mean = np.mean(y)
self.std = np.std(y)
self.transform()
return
def transform(self):
self.y = (self.original_data - self.mean) / self.std
self.err = sel... | tutorials/old/GPRegression.ipynb | KIPAC/StatisticalMethods | gpl-2.0 |
Check that we can undo the scaling, for any y and sigmay: | y2, sigmay2 = rescaled.invert(rescaled.y, rescaled.err)
print('Mean, variance of inverted, rescaled data: ',np.round(np.mean(y2)), np.round(np.var(y2)))
print('Maximum differences in y, sigmay, after round trip: ',np.max(np.abs(y2 - y)), np.max(np.abs(sigmay2 - sigmay))) | tutorials/old/GPRegression.ipynb | KIPAC/StatisticalMethods | gpl-2.0 |
Constraining the GP
Now, using the same covariance function, lets "fit" the GP by constraining each draw from the GP to go through our data points, and optimizing the length scale hyperparameter h.
Let's first look at how this would work for two data points with no uncertainty. | # Choose two of our (rescaled) datapoints:
x1 = np.array([x[10], x[12]])
rescaled_y1 = np.array([rescaled.y[10], rescaled.y[12]])
rescaled_sigmay1 = np.array([rescaled.err[10], rescaled.err[12]])
# Instantiate a GP model, with initial length_scale h=10:
kernel = SquaredExponential(length_scale=10.0, length_scale_bound... | tutorials/old/GPRegression.ipynb | KIPAC/StatisticalMethods | gpl-2.0 |
In the absence of information, the GP tends to produce $y(x)$ that fluctuate around the prior mean function, which we chose to be a constant. Let's draw some samples from the posterior PDF, and overlay them. | draws = gp1.sample_y(xgrid, n_samples=3)
for k in range(3):
draws[:,k], dummy = rescaled.invert(draws[:,k], np.zeros(len(xgrid)))
ax.plot(xgrid, draws[:,0], '-r')
ax.plot(xgrid, draws[:,1], '-g')
ax.plot(xgrid, draws[:,2], '-b', label='Posterior sample $y(x)$')
ax.legend(fontsize=8)
fig | tutorials/old/GPRegression.ipynb | KIPAC/StatisticalMethods | gpl-2.0 |
See how the posterior sample $y(x)$ functions all pass through the constrained points.
Including Observational Uncertainties
The mechanism for including uncertainties is a little esoteric: scikit-learn wants to be given a "nugget," called alpha, to multiply the diagonal elements of the covariance matrix. | # Choose two of our datapoints:
x2 = np.array([x[10], x[12]])
rescaled_y2 = np.array([rescaled.y[10], rescaled.y[12]])
rescaled_sigmay2 = np.array([rescaled.err[10], rescaled.err[12]])
# Instantiate a GP model, including observational errors:
kernel = SquaredExponential(length_scale=10.0, length_scale_bounds=(0.01, 10... | tutorials/old/GPRegression.ipynb | KIPAC/StatisticalMethods | gpl-2.0 |
Now, the posterior sample $y(x)$ functions pass through the constraints within the errors.
Using all the Data
Now let's extend the above example to use all of our datapoints. This additional information should pull the predictions further away from the initial mean function. We'll also compute the marginal log likeliho... | # Use all of our datapoints:
x3 = x
rescaled_y3 = rescaled.y
rescaled_sigmay3 = rescaled.err
# Instantiate a GP model, including observational errors:
kernel = SquaredExponential(length_scale=10.0, length_scale_bounds=(0.01, 1000.0))
# Could comment this out, and then import and use an
# alternative kernel here.
gp... | tutorials/old/GPRegression.ipynb | KIPAC/StatisticalMethods | gpl-2.0 |
We now see the Gaussian Process model providing a smooth interpolation between the points. The posterior samples show fluctuations, but all are plausible under our assumptions.
Exercises
Try a different kernel function, from the list given in the scikit-learn docs here. "Matern" could be a good choice. Do you get a hi... | def generate_replica_data(xgrid, ygrid, seed=None):
"""
Generate a 30-point data set, with x and sigma_y as standard, but with
y values given by the "lookup tables" (gridded function) provided.
"""
Ndata = 30
xbar = 0.5*(xlimits[0] + xlimits[1])
xstd = 0.25*(xlimits[1] - xlimits[0])
if... | tutorials/old/GPRegression.ipynb | KIPAC/StatisticalMethods | gpl-2.0 |
Bonus1: Make sure the function returns an empty list if the iterable is empty | multimax([]) | Python/Python Morsels/multimax/my_try/multimax.ipynb | nitin-cherian/LifeLongLearning | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.