markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Create a dense vector for each word in the pair. The output of Embedding has shape (batch_size, sequence_length, output_dim) which in our case is (batch_size, 1, DENSEVEC_DIM). We'll use Flatten to get rid of that pesky middle dimension (1), so going into the dot product we'll have shape (batch_size, DENSEVEC_DIM). | word1 = Input(shape=(1,), dtype='int64', name='word1')
word2 = Input(shape=(1,), dtype='int64', name='word2')
shared_embedding = Embedding(
input_dim=VOCAB_SIZE+1,
output_dim=DENSEVEC_DIM,
input_length=1,
embeddings_constraint = unit_norm(),
name='shared_embedding')
embedded_w1 = shared_embeddi... | .ipynb_checkpoints/TextModels-checkpoint.ipynb | peterfig/keras-deep-learning-course | mit |
At this point you can check out how the data flows through your compiled model. | sg_model.layers
def print_layer(model, num):
print model.layers[num]
print model.layers[num].input_shape
print model.layers[num].output_shape
print_layer(sg_model,3) | .ipynb_checkpoints/TextModels-checkpoint.ipynb | peterfig/keras-deep-learning-course | mit |
Let's try training it with our toy data set! | import numpy as np
pairs = np.array(sg[0])
targets = np.array(sg[1])
targets
pairs
w1_list = np.reshape(pairs[:, 0], (len(pairs), 1))
w1_list
w2_list = np.reshape(pairs[:, 1], (len(pairs), 1))
w2_list
w2_list.shape
w2_list.dtype
sg_model.fit(x=[w1_list, w2_list], y=targets, epochs=10)
sg_model.layers[2].weigh... | .ipynb_checkpoints/TextModels-checkpoint.ipynb | peterfig/keras-deep-learning-course | mit |
Continuous Bag of Words (CBOW) model
CBOW means we take all the words in the window and use them to predict the target word. Note we are trying to predict an actual word (or a probability distribution over words) with CBOW, whereas in skip-gram we are trying to predict a similarity score.
FastText Model
FastText is c... | MAX_FEATURES = 20000 # number of unique words in the dataset
MAXLEN = 400 # max word (feature) length of a review
EMBEDDING_DIMS = 50
NGRAM_RANGE = 2 | .ipynb_checkpoints/TextModels-checkpoint.ipynb | peterfig/keras-deep-learning-course | mit |
Some data prep functions lifted from the example | def create_ngram_set(input_list, ngram_value=2):
"""
Extract a set of n-grams from a list of integers.
"""
return set(zip(*[input_list[i:] for i in range(ngram_value)]))
create_ngram_set([1, 2, 3, 4, 5], ngram_value=2)
create_ngram_set([1, 2, 3, 4, 5], ngram_value=3)
def add_ngram(sequences, token_in... | .ipynb_checkpoints/TextModels-checkpoint.ipynb | peterfig/keras-deep-learning-course | mit |
load canned training data | from keras.datasets import imdb
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=MAX_FEATURES)
x_train[0:2]
y_train[0:2] | .ipynb_checkpoints/TextModels-checkpoint.ipynb | peterfig/keras-deep-learning-course | mit |
Add n-gram features | ngram_set = set()
for input_list in x_train:
for i in range(2, NGRAM_RANGE + 1):
set_of_ngram = create_ngram_set(input_list, ngram_value=i)
ngram_set.update(set_of_ngram)
len(ngram_set) | .ipynb_checkpoints/TextModels-checkpoint.ipynb | peterfig/keras-deep-learning-course | mit |
Assign id's to the new features | ngram_set.pop()
start_index = MAX_FEATURES + 1
token_indice = {v: k + start_index for k, v in enumerate(ngram_set)}
indice_token = {token_indice[k]: k for k in token_indice} | .ipynb_checkpoints/TextModels-checkpoint.ipynb | peterfig/keras-deep-learning-course | mit |
Update MAX_FEATURES | import numpy as np
MAX_FEATURES = np.max(list(indice_token.keys())) + 1
MAX_FEATURES | .ipynb_checkpoints/TextModels-checkpoint.ipynb | peterfig/keras-deep-learning-course | mit |
Add n-grams to the input data | x_train = add_ngram(x_train, token_indice, NGRAM_RANGE)
x_test = add_ngram(x_test, token_indice, NGRAM_RANGE) | .ipynb_checkpoints/TextModels-checkpoint.ipynb | peterfig/keras-deep-learning-course | mit |
Make all input sequences the same length by padding with zeros | from keras.preprocessing import sequence
sequence.pad_sequences([[1,2,3,4,5], [6,7,8]], maxlen=10)
x_train = sequence.pad_sequences(x_train, maxlen=MAXLEN)
x_test = sequence.pad_sequences(x_test, maxlen=MAXLEN)
x_train.shape
x_test.shape | .ipynb_checkpoints/TextModels-checkpoint.ipynb | peterfig/keras-deep-learning-course | mit |
FastText Model | Image('diagrams/fasttext.png')
from keras.models import Sequential
from keras.layers.embeddings import Embedding
from keras.layers.pooling import GlobalAveragePooling1D
from keras.layers import Dense
ft_model = Sequential()
ft_model.add(Embedding(
input_dim = MAX_FEATURES,
output_dim = EMBEDDING_DIMS,
... | .ipynb_checkpoints/TextModels-checkpoint.ipynb | peterfig/keras-deep-learning-course | mit |
fastText classifier vs. convolutional neural network (CNN) vs. long short-term memory (LSTM) classifier: Fight!
A CNN takes the dot product of various "filters" (some new vector) with each word window down the sentence. For each convolutional layer in your model, you can choose the size of the filter (for example, 3 w... | Image('diagrams/text-cnn-classifier.png') | .ipynb_checkpoints/TextModels-checkpoint.ipynb | peterfig/keras-deep-learning-course | mit |
Diagram from Convolutional Neural Networks for Sentence Classification, Kim Yoon (2014)
A CNN sentence classifier | embedding_dim = 50 # we'll get a vector representation of words as a by-product
filter_sizes = (2, 3, 4) # we'll make one convolutional layer for each filter we specify here
num_filters = 10 # each layer will contain this many filters
dropout_prob = (0.2, 0.2)
hidden_dims = 50
# Prepossessing parameters
sequence_l... | .ipynb_checkpoints/TextModels-checkpoint.ipynb | peterfig/keras-deep-learning-course | mit |
Canned input data | from keras.datasets import imdb
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=max_words) # limits vocab to num_words
?imdb.load_data
from keras.preprocessing import sequence
x_train = sequence.pad_sequences(x_train, maxlen=sequence_length, padding="post", truncating="post")
x_test = sequence.pad_... | .ipynb_checkpoints/TextModels-checkpoint.ipynb | peterfig/keras-deep-learning-course | mit |
Model build | from keras.models import Model
from keras.layers import Input
from keras.layers import Embedding
from keras.layers import Dropout
from keras.layers import Conv1D
from keras.layers import MaxPooling1D
from keras.layers import Flatten
from keras.layers import Dense
from keras.layers.merge import Concatenate
# Input, emb... | .ipynb_checkpoints/TextModels-checkpoint.ipynb | peterfig/keras-deep-learning-course | mit |
An LSTM sentence classifier | Image('diagrams/LSTM.png')
from keras.models import Sequential
from keras.layers import Embedding
from keras.layers.core import SpatialDropout1D
from keras.layers.core import Dropout
from keras.layers.recurrent import LSTM
from keras.layers.core import Dense
hidden_dims = 50
embedding_dim = 50
lstm_model = Sequentia... | .ipynb_checkpoints/TextModels-checkpoint.ipynb | peterfig/keras-deep-learning-course | mit |
Appendix: Our own data download and preparation
We'll use the Large Movie Review Dataset v1.0 for our corpus. While Keras has its own data samples you can import for modeling (including this one), I think it's very important to get and process your own data. Otherwise, the results appear to materialize out of thin ai... | %matplotlib inline
import pandas as pd
import glob
datapath = "/Users/pfigliozzi/aclImdb/train/unsup"
files = glob.glob(datapath+"/*.txt")[:1000] #first 1000 (there are 50k)
df = pd.concat([pd.read_table(filename, header=None, names=['raw']) for filename in files], ignore_index=True)
df.raw.map(lambda x: len(x)).... | .ipynb_checkpoints/TextModels-checkpoint.ipynb | peterfig/keras-deep-learning-course | mit |
O pacote Caryocar também fornece algumas funções e classes auxiliares para realizar a limpeza dos dados. | from caryocar.cleaning import NamesAtomizer, namesFromString
from caryocar.cleaning import normalize, read_NamesMap_fromJson
from caryocar.cleaning import getNamesIndexes | _notebooks/construindo-redes-sociais-com-dados-de-colecoes-biologicas.ipynb | pedrosiracusa/pedrosiracusa.github.io | mit |
Etapa 1. Leitura do conjunto de dados
O primeiro passo é ler o conjunto de dados de ocorrência de espécies.
Para isso vamos extender as funcionalidades da linguagem Python usando uma biblioteca muito útil para a análise de dados: a Pandas.
Com esta biblioteca, podemos carregar, transformar e analisar nosso conjunto de ... | import pandas as pd | _notebooks/construindo-redes-sociais-com-dados-de-colecoes-biologicas.ipynb | pedrosiracusa/pedrosiracusa.github.io | mit |
Com a função read_csv do Pandas, carregaremos nossos dados que estão no arquivo CSV e os colocaremos na estrutura de um Data Frame, que é basicamente uma tabela.
Esta função espera receber o nome do arquivo CSV que contém os dados, bem como uma lista com os nomes das colunas que estamos interessados em carregar.
Especi... | dsetPath = '/home/pedro/datasets/ub_herbarium/occurrence.csv'
cols = ['recordedBy','species']
occs_df = pd.read_csv(dsetPath, sep='\t', usecols=cols) | _notebooks/construindo-redes-sociais-com-dados-de-colecoes-biologicas.ipynb | pedrosiracusa/pedrosiracusa.github.io | mit |
Vamos dar uma olhada no jeitão do dataframe. Para isso, vamos pedir as 10 primeira linhas apenas. | occs_df.head(10) | _notebooks/construindo-redes-sociais-com-dados-de-colecoes-biologicas.ipynb | pedrosiracusa/pedrosiracusa.github.io | mit |
Etapa 2: Limpeza dos dados
Antes de construir o modelo, precisamos fazer uma limpeza de dados para garantir que eles estejam no formato adequado para a construção dos modelos.
O primeiro passo é filtrar os registros com elementos nulos (NaN) para cada um dos campos do dataframe. Um elemento nulo significa ausência de ... | occs_df.isnull().sum() | _notebooks/construindo-redes-sociais-com-dados-de-colecoes-biologicas.ipynb | pedrosiracusa/pedrosiracusa.github.io | mit |
A informação de coletor está ausente em apenas 9 dos registros. Vamos simplesmente eliminá-los. Um outro ponto é que para simplificar nossa modelagem, vou apenas usar registros que tenham sido identificados ao nível de espécie. Isso significa que teremos que descartar 32711 registros, nos quais a informação sobre a ide... | occs_df.dropna(how='any', inplace=True) | _notebooks/construindo-redes-sociais-com-dados-de-colecoes-biologicas.ipynb | pedrosiracusa/pedrosiracusa.github.io | mit |
Agora não temos mais nulos em nenhuma das colunas, e podemos prosseguir: | occs_df.isnull().sum() | _notebooks/construindo-redes-sociais-com-dados-de-colecoes-biologicas.ipynb | pedrosiracusa/pedrosiracusa.github.io | mit |
Atomização dos nomes de coletores
O campo de coletores (recordedBy) é fundamental para nossa modelagem, mas infelizmente costuma ser um pouco problemático.
O primeiro problema é que os nomes dos coletores não são atômicos. Isso significa múltiplos nomes podem ser codificados em um mesmo valor (no caso, a lista de nomes... | na = NamesAtomizer(atomizeOp=namesFromString) | _notebooks/construindo-redes-sociais-com-dados-de-colecoes-biologicas.ipynb | pedrosiracusa/pedrosiracusa.github.io | mit |
O atomizador de nomes resolve a grande maioria dos casos. Mas existem alguns poucos registros com erros na delimitação dos nomes. Neste caso a correção deve ser feita fazendo a substituição em cada registro pela sua forma correta.
Para o dataset do UB, estas substituições estão especificadas no arquivo armazenado na va... | names_replaces_file = '/home/pedro/data/ub_collectors_replaces.json' | _notebooks/construindo-redes-sociais-com-dados-de-colecoes-biologicas.ipynb | pedrosiracusa/pedrosiracusa.github.io | mit |
Só por curiosidade, vejamos o conteúdo deste arquivo: | ! cat {names_replaces_file} | _notebooks/construindo-redes-sociais-com-dados-de-colecoes-biologicas.ipynb | pedrosiracusa/pedrosiracusa.github.io | mit |
Prosseguindo com a substituição: | na.read_replaces(names_replaces_file) | _notebooks/construindo-redes-sociais-com-dados-de-colecoes-biologicas.ipynb | pedrosiracusa/pedrosiracusa.github.io | mit |
Agora, com o auxílio do atomizador de nomes, vamos adicionar uma nova coluna ao dataframe, contendo os nomes dos coletores atomizados. Ela se chamará recordedBy_atomized: | occs_df['recordedBy_atomized'] = na.atomize(occs_df['recordedBy']) | _notebooks/construindo-redes-sociais-com-dados-de-colecoes-biologicas.ipynb | pedrosiracusa/pedrosiracusa.github.io | mit |
Normalização e mapeamento de nomes
Um segundo problema é que nomes de coletores podem ter sido escritos de algumas formas diferentes, seja por conta de erros ou omissão de partes do nome.
Por exemplo, o nome 'Proença, C.E.B.' pode ter alguns variantes, incluindo 'Proenca, C.E.B,', 'Proença, C.E.', Proença, C.'.
Precisa... | namesMap_file = '/home/pedro/data/ub_namesmap.json' | _notebooks/construindo-redes-sociais-com-dados-de-colecoes-biologicas.ipynb | pedrosiracusa/pedrosiracusa.github.io | mit |
Este arquivo é grande, mas vamos ver as 20 primeiras linhas para termos uma ideia: | ! head {namesMap_file} -n 20 | _notebooks/construindo-redes-sociais-com-dados-de-colecoes-biologicas.ipynb | pedrosiracusa/pedrosiracusa.github.io | mit |
Note que alguns nomes de coletores que não eram nulos porêm remetem à falta da informação (por exemplo '.', '?') são mapeados para uma string vazia. Mais tarde iremos filtrar estes nomes.
Vamos agora ler o mapa de nomes do arquivo e armazená-lo na variável nm. | nm = read_NamesMap_fromJson(namesMap_file, normalizationFunc=normalize) | _notebooks/construindo-redes-sociais-com-dados-de-colecoes-biologicas.ipynb | pedrosiracusa/pedrosiracusa.github.io | mit |
Caso haja nomes de coletores que não estão no arquivo, vamos nos assegurar de que eles serão inseridos: | collectors_names = list(set( n for n,st,num in na.getCachedNames() ))
nm.addNames(collectors_names) | _notebooks/construindo-redes-sociais-com-dados-de-colecoes-biologicas.ipynb | pedrosiracusa/pedrosiracusa.github.io | mit |
Assim, este mapa nos permite buscar, para cada variante do nome, sua forma normal: | nm.getMap()['Proença, CEB']
nm.getMap()['Proença, C'] | _notebooks/construindo-redes-sociais-com-dados-de-colecoes-biologicas.ipynb | pedrosiracusa/pedrosiracusa.github.io | mit |
A figura abaixo ilustra as etapas envolvidas no preprocessamento do campo dos coletores, conforme descrito.
{:width="700px"}
O índice de nomes
Finalmente, vamos construir um índice de nomes, apenas para mantermos a referência de quais linhas do dataframe cada coletor aparece. Para isso usaremos a função getNamesIndexes... | ni = getNamesIndexes(occs_df,'recordedBy_atomized', namesMap=nm.getMap()) | _notebooks/construindo-redes-sociais-com-dados-de-colecoes-biologicas.ipynb | pedrosiracusa/pedrosiracusa.github.io | mit |
Etapa 3: Construindo os modelos
Chegamos na etapa que realmente interessa. Já temos um dataframe com os dados minimamente limpos e estruturados, e podemos então construir os modelos!
Rede Espécie-Coletor (SCN)
Redes espécie-coletor modelam relações de interesse, envolvendo necessariamente um coletor e uma espécie. A se... | scn = SCN(species=occs_df['species'], collectors=occs_df['recordedBy_atomized'], namesMap=nm) | _notebooks/construindo-redes-sociais-com-dados-de-colecoes-biologicas.ipynb | pedrosiracusa/pedrosiracusa.github.io | mit |
Após a construção do modelo, vamos remover nomes de coletores indevidos, como 'etal', 'ilegivel', 'incognito'. | cols_to_filter = ['','ignorado','ilegivel','incognito','etal']
scn.remove_nodes_from(cols_to_filter) | _notebooks/construindo-redes-sociais-com-dados-de-colecoes-biologicas.ipynb | pedrosiracusa/pedrosiracusa.github.io | mit |
Vejamos então um pequeno resumo sobre esta rede. Este pedaço de código pode ser um pouco feio, mas o que importa mesmo aqui são as informações imprimidas abaixo dele. | n_cols = len(scn.listCollectorsNodes())
cols_degrees = scn.degree(scn.listCollectorsNodes())
n_spp = len(scn.listSpeciesNodes())
spp_degrees = scn.degree(scn.listSpeciesNodes())
print(
f"""Rede Espécie-Coletor (SCN)
==========================
Número total de coletores:{n_cols}
Número total de espécies: {n_spp}
Em médi... | _notebooks/construindo-redes-sociais-com-dados-de-colecoes-biologicas.ipynb | pedrosiracusa/pedrosiracusa.github.io | mit |
Um aspecto interessante a ser notado é a distribuição de grau (número de conexões de um vértice) nesta rede.
Embora em média um coletor registre 21 espécies diferentes, os coletores mais produtivos registraram mais de 1000!
De forma simlar, embora em média uma espécie seja registrada por 9 coletores distintos, as prime... | cwn = CWN(cliques=occs_df['recordedBy_atomized'],namesMap=nm) | _notebooks/construindo-redes-sociais-com-dados-de-colecoes-biologicas.ipynb | pedrosiracusa/pedrosiracusa.github.io | mit |
Assim como fizemos com a SCN, vamos remover nomes de coletores indevidos | cols_to_filter = ['','ignorado','ilegivel','incognito','etal']
cwn.remove_nodes_from(cols_to_filter) | _notebooks/construindo-redes-sociais-com-dados-de-colecoes-biologicas.ipynb | pedrosiracusa/pedrosiracusa.github.io | mit |
Vejamos um resumo sobre a rede: | n_cols = len(cwn.nodes)
cols_degrees = cwn.degree()
print(
f"""Rede de Colaboração de Coletores (CWN)
======================================
Número total de coletores:{n_cols}
Número total de arestas: {len(cwn.edges)}
Em média, um coletor colabora com {round( sum(k for n,k in cols_degrees)/n_cols )} pares ao longo de ... | _notebooks/construindo-redes-sociais-com-dados-de-colecoes-biologicas.ipynb | pedrosiracusa/pedrosiracusa.github.io | mit |
In previous tutorials, we set interactive mode to True, and we obtained the result
of every operation. | ibis.options.interactive = True
countries['name', 'continent', 'population'].limit(3) | docs/source/tutorial/03-Expressions-Lazy-Mode-Logging.ipynb | cloudera/ibis | apache-2.0 |
But now let's see what happens if we leave the interactive option to False (the default),
and we operate in lazy mode. | ibis.options.interactive = False
countries['name', 'continent', 'population'].limit(3) | docs/source/tutorial/03-Expressions-Lazy-Mode-Logging.ipynb | cloudera/ibis | apache-2.0 |
What we find is the graph of the expressions that would return the desired result instead of the result itself.
Let's analyze the expressions in the graph:
We query the countries table (all rows and all columns)
We select the name, continent and population columns
We limit the results to only the first 3 rows
Now con... | countries_expression = countries['name', 'continent', 'population'].limit(3)
type(countries_expression) | docs/source/tutorial/03-Expressions-Lazy-Mode-Logging.ipynb | cloudera/ibis | apache-2.0 |
The type is an Ibis TableExpr, since the result is a table (in a broad way, you can consider it a dataframe).
Now we have our query instructions (our expression, fetching only 3 columns and 3 rows) in the variable countries_expression.
At this point, nothing has been requested from the database. We have defined what we... | countries_expression.execute() | docs/source/tutorial/03-Expressions-Lazy-Mode-Logging.ipynb | cloudera/ibis | apache-2.0 |
We can build other types of expressions, for example, one that instead of returning a table,
returns a columns. | population_in_millions = (countries['population'] / 1_000_000).name('population_in_millions')
population_in_millions | docs/source/tutorial/03-Expressions-Lazy-Mode-Logging.ipynb | cloudera/ibis | apache-2.0 |
If we check its type, we can see how it is a FloatingColumn expression. | type(population_in_millions) | docs/source/tutorial/03-Expressions-Lazy-Mode-Logging.ipynb | cloudera/ibis | apache-2.0 |
We can combine the previous expression to be a column of a table expression. | countries['name', 'continent', population_in_millions].limit(3) | docs/source/tutorial/03-Expressions-Lazy-Mode-Logging.ipynb | cloudera/ibis | apache-2.0 |
Since we are in lazy mode (not interactive), those expressions don't request any data from the database
unless explicitly requested with .execute().
Logging queries
For SQL backends (and for others when it makes sense), the query sent to the database can be logged.
This can be done by setting the verbose option to True... | ibis.options.verbose = True
countries['name', 'continent', population_in_millions].limit(3).execute() | docs/source/tutorial/03-Expressions-Lazy-Mode-Logging.ipynb | cloudera/ibis | apache-2.0 |
By default, the logging is done to the terminal, but we can process the query with a custom function.
This allows us to save executed queries to a file, save to a database, send them to a web service, etc.
For example, to save queries to a file, we can write a custom function that given a query, saves it to a
log file. | import os
import datetime
def log_query_to_file(query):
"""
Log queries to `data/tutorial_queries.log`.
Each file is a query. Line breaks in the query are represented with the string '\n'.
A timestamp of when the query is executed is added.
"""
fname = os.path.join('data', 'tutorial_q... | docs/source/tutorial/03-Expressions-Lazy-Mode-Logging.ipynb | cloudera/ibis | apache-2.0 |
Then we can set the verbose_log option to the custom function, execute one query,
wait one second, and execute another query. | import time
ibis.options.verbose_log = log_query_to_file
countries.execute()
time.sleep(1.)
countries['name', 'continent', population_in_millions].limit(3).execute() | docs/source/tutorial/03-Expressions-Lazy-Mode-Logging.ipynb | cloudera/ibis | apache-2.0 |
This has created a log file in data/tutorial_queries.log where the executed queries have been logged. | !cat data/tutorial_queries.log | docs/source/tutorial/03-Expressions-Lazy-Mode-Logging.ipynb | cloudera/ibis | apache-2.0 |
ZeroPadding2D
[convolutional.ZeroPadding2D.0] padding (1,1) on 3x5x2 input, data_format='channels_last' | data_in_shape = (3, 5, 2)
L = ZeroPadding2D(padding=(1, 1), data_format='channels_last')
layer_0 = Input(shape=data_in_shape)
layer_1 = L(layer_0)
model = Model(inputs=layer_0, outputs=layer_1)
# set weights to random (use seed for reproducibility)
np.random.seed(250)
data_in = 2 * np.random.random(data_in_shape) - 1... | notebooks/layers/convolutional/ZeroPadding2D.ipynb | transcranial/keras-js | mit |
[convolutional.ZeroPadding2D.1] padding (1,1) on 3x5x2 input, data_format='channels_first' | data_in_shape = (3, 5, 2)
L = ZeroPadding2D(padding=(1, 1), data_format='channels_first')
layer_0 = Input(shape=data_in_shape)
layer_1 = L(layer_0)
model = Model(inputs=layer_0, outputs=layer_1)
# set weights to random (use seed for reproducibility)
np.random.seed(251)
data_in = 2 * np.random.random(data_in_shape) - ... | notebooks/layers/convolutional/ZeroPadding2D.ipynb | transcranial/keras-js | mit |
[convolutional.ZeroPadding2D.2] padding (3,2) on 2x6x4 input, data_format='channels_last' | data_in_shape = (2, 6, 4)
L = ZeroPadding2D(padding=(3, 2), data_format='channels_last')
layer_0 = Input(shape=data_in_shape)
layer_1 = L(layer_0)
model = Model(inputs=layer_0, outputs=layer_1)
# set weights to random (use seed for reproducibility)
np.random.seed(252)
data_in = 2 * np.random.random(data_in_shape) - 1... | notebooks/layers/convolutional/ZeroPadding2D.ipynb | transcranial/keras-js | mit |
[convolutional.ZeroPadding2D.3] padding (3,2) on 2x6x4 input, data_format='channels_first' | data_in_shape = (2, 6, 4)
L = ZeroPadding2D(padding=(3, 2), data_format='channels_first')
layer_0 = Input(shape=data_in_shape)
layer_1 = L(layer_0)
model = Model(inputs=layer_0, outputs=layer_1)
# set weights to random (use seed for reproducibility)
np.random.seed(253)
data_in = 2 * np.random.random(data_in_shape) - ... | notebooks/layers/convolutional/ZeroPadding2D.ipynb | transcranial/keras-js | mit |
[convolutional.ZeroPadding2D.4] padding ((1,2),(3,4)) on 2x6x4 input, data_format='channels_last' | data_in_shape = (2, 6, 4)
L = ZeroPadding2D(padding=((1,2),(3,4)), data_format='channels_last')
layer_0 = Input(shape=data_in_shape)
layer_1 = L(layer_0)
model = Model(inputs=layer_0, outputs=layer_1)
# set weights to random (use seed for reproducibility)
np.random.seed(254)
data_in = 2 * np.random.random(data_in_sha... | notebooks/layers/convolutional/ZeroPadding2D.ipynb | transcranial/keras-js | mit |
[convolutional.ZeroPadding2D.5] padding 2 on 2x6x4 input, data_format='channels_last' | data_in_shape = (2, 6, 4)
L = ZeroPadding2D(padding=2, data_format='channels_last')
layer_0 = Input(shape=data_in_shape)
layer_1 = L(layer_0)
model = Model(inputs=layer_0, outputs=layer_1)
# set weights to random (use seed for reproducibility)
np.random.seed(255)
data_in = 2 * np.random.random(data_in_shape) - 1
resu... | notebooks/layers/convolutional/ZeroPadding2D.ipynb | transcranial/keras-js | mit |
export for Keras.js tests | import os
filename = '../../../test/data/layers/convolutional/ZeroPadding2D.json'
if not os.path.exists(os.path.dirname(filename)):
os.makedirs(os.path.dirname(filename))
with open(filename, 'w') as f:
json.dump(DATA, f)
print(json.dumps(DATA)) | notebooks/layers/convolutional/ZeroPadding2D.ipynb | transcranial/keras-js | mit |
V Jupyter notebook (nástroj v kterém je tento tutoriál vytvořen) každý blok kódu ukončení proměnnou nebo výrazem vytiskne obsah této proměnné. Toho je v tomto tutoriálu využívano. Následuje příklad: | a = 1 # tady si vytvorim promennou
a # tohle vytiskne hodnotu bez uziti prikazu print | podklady/notebooks/skriptovani_v_pythonu.ipynb | matousc89/PPSI | mit |
List
List je pravděpodobně nejznámější kontejner na data v jazyce Python. Položky v listu se můžou opakovat a mají pořadí položek dané při vytvoření listu. Položky v listu je možné měnit, mazat a přidávat. Následují příklady. | [1, 1, 2] # list celych cisel, polozka 1 se opakukuje
["abc", 1, 0.5] # list obsahujici ruzne datove typy
[] # prazdny list
[[1,2], "abc", {1, "0", 3}] # list obsahujici take dalsi listy
[1, "a", 2] + [5, 3, 5] # spojeni dvou listu
[1, 2, 3]*5 # opakovani listu | podklady/notebooks/skriptovani_v_pythonu.ipynb | matousc89/PPSI | mit |
Indexování a porcování
V Pythonu se pro indexování užívají hranaté závorky []. Symbol : zastupuje všechny položky v daném rozsahu. Indexuje se od 0. Indexování a porcování listu je ukázáno na nasledujících příkladech. | a = ["a", "b", "c", "d", "e", "f", "g", "h"] # ukázkový list
a[3] # vrati objekt z indexem 3 (ctvrty objekt)
a[:2] # vrati prvni dva objekty
a[3:] # vrati vse od objektu 3 dal
a[2:5] # vse mezi objekty s indexy 2 a 5
a[-3] # treti objekt od konce
a[0:-1:2] # kazdy druhy objekt od zacatku do konce
a[::2] # kratsi... | podklady/notebooks/skriptovani_v_pythonu.ipynb | matousc89/PPSI | mit |
Přepisování, přidávání, vkládání a mazání položek z listu
Ukázáno na následujících příkladech. | a = ["a", "b", "c", "d"]
a[2] = "x" # prepsani objektu s indexem 2
print(a)
a.append("h") # pridani objektu h na konec
print(a)
a.insert(2, "y") # pridani objektu y na pozici 2
print(a)
del a[2] # odebere objekt na pozici 2
print (a) | podklady/notebooks/skriptovani_v_pythonu.ipynb | matousc89/PPSI | mit |
Podmínka If, else, elif
Podmínky slouží k implementaci logiky. Logika operuje s proměnnou bool, která nabývá pouze hodnot True nebo False.
Výrazy a jejich vyhodnocení
Následuje ukázka vyhodnocení pravdivosti několika výrazů. | a = 1
a == 1
a == 1
not a == 1
a > 1
a >= 1
1 in [1, 2]
not (1 in [1, 2]) == (not 1 > 0) | podklady/notebooks/skriptovani_v_pythonu.ipynb | matousc89/PPSI | mit |
Podmínky a jejich vyhodnocení
Podmínka if testuje, zda výraz pravdivé hodnoty - pokud ano, podmínka vykoná svůj kód. Následuje příklad. | fruit = "apple"
color = "No color"
if fruit == "apple":
color = "green"
color | podklady/notebooks/skriptovani_v_pythonu.ipynb | matousc89/PPSI | mit |
Podmínka else umožňuje nastavit alternativní kód pro případ kdy podmínka if není splněna. Příklad následuje. | fruit = "orange"
if fruit == "apple":
color = "red"
else:
color = "orange"
color | podklady/notebooks/skriptovani_v_pythonu.ipynb | matousc89/PPSI | mit |
Podmínka elif umožňuje zadat více podmínek pro případ nesplnění podmínky if. Podmínek elif je možné umístit více za jednu podmínku if. Příklad následuje. | fruit = "apple"
if fruit == "apple":
color = "red"
elif fruit == "orange":
color = "orange"
elif fruit == "pear":
color = "green"
else:
color = "yellow"
color | podklady/notebooks/skriptovani_v_pythonu.ipynb | matousc89/PPSI | mit |
Smyčky
Iterace je jedna z nejčastější operací v programování. Následující ukázky se vztahují k rovnici
$\forall i \in {2,\ldots,9}.\ a_i = a_{i-1} + a_{i-2}$.
For smyčka
For smyčka je navržena pro iterování přes předem daný iterovatelný objekt. Příklad následuje. | a = [] # list na vysledky
a.append(1) # prvni pocatecni podminka
a.append(1) # druha pocatecni podminka
for i in [2, 3, 4, 5, 6, 7, 8]: # rozsah pres ktery iterovat
a.append(a[i-1] + a[i-2]) # pridavani vypoctenych polozek do listu
print(a) | podklady/notebooks/skriptovani_v_pythonu.ipynb | matousc89/PPSI | mit |
Vylepšení předchozího příkladu následuje. | a = [0]*9 # list na vysledky
a[0:2] = [1, 1] # pocatecni podminky
for i in range(2,9): # fukce range
a[i] = a[i-1] + a[i-2] # realizace vypoctu
print(a) | podklady/notebooks/skriptovani_v_pythonu.ipynb | matousc89/PPSI | mit |
V případě že je potřeba přerušit smyčku před koncem, je možné použít příkaz break.
While smyčka
Tato smyčka iteruje dokud není splněna podmínka. Příklad následuje. | a = [0]*9
a[0:2] = [1, 1]
i = 2 # nastaveni pomocne promenne
while i < 9: # iteruj dokud pomocna promenna nesplni podminku
a[i] = a[i-1] + a[i-2]
i += 1 # pridej 1 k pomocne promenne
print(a) | podklady/notebooks/skriptovani_v_pythonu.ipynb | matousc89/PPSI | mit |
Get the Data | df = pd.read_csv("../kyphosis.csv")
df.head() | notebooks/launching_into_ml/labs/supplemental/decision_trees_and_random_Forests_in_Python.ipynb | GoogleCloudPlatform/asl-ml-immersion | apache-2.0 |
Exploratory Data Analysis
Lab Task #1: Check a pairplot for this small dataset. | # TODO 1
# TODO -- Your code here. | notebooks/launching_into_ml/labs/supplemental/decision_trees_and_random_Forests_in_Python.ipynb | GoogleCloudPlatform/asl-ml-immersion | apache-2.0 |
Train Test Split
Let's split up the data into a training set and a test set! | from sklearn.model_selection import train_test_split
X = df.drop("Kyphosis", axis=1)
y = df["Kyphosis"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30) | notebooks/launching_into_ml/labs/supplemental/decision_trees_and_random_Forests_in_Python.ipynb | GoogleCloudPlatform/asl-ml-immersion | apache-2.0 |
Decision Trees
Lab Task #2: Train a single decision tree. | from sklearn.tree import DecisionTreeClassifier
dtree = DecisionTreeClassifier()
# TODO 2
# TODO -- Your code here. | notebooks/launching_into_ml/labs/supplemental/decision_trees_and_random_Forests_in_Python.ipynb | GoogleCloudPlatform/asl-ml-immersion | apache-2.0 |
Prediction and Evaluation
Let's evaluate our decision tree. | predictions = dtree.predict(X_test)
from sklearn.metrics import classification_report, confusion_matrix
# TODO 3a
# TODO -- Your code here.
# TODO 3b
print(confusion_matrix(y_test, predictions)) | notebooks/launching_into_ml/labs/supplemental/decision_trees_and_random_Forests_in_Python.ipynb | GoogleCloudPlatform/asl-ml-immersion | apache-2.0 |
Tree Visualization
Scikit learn actually has some built-in visualization capabilities for decision trees, you won't use this often and it requires you to install the pydot library, but here is an example of what it looks like and the code to execute this: | import pydot
from IPython.display import Image
from six import StringIO
from sklearn.tree import export_graphviz
features = list(df.columns[1:])
features
dot_data = StringIO()
export_graphviz(
dtree, out_file=dot_data, feature_names=features, filled=True, rounded=True
)
graph = pydot.graph_from_dot_data(dot_data... | notebooks/launching_into_ml/labs/supplemental/decision_trees_and_random_Forests_in_Python.ipynb | GoogleCloudPlatform/asl-ml-immersion | apache-2.0 |
Random Forests
Lab Task #4: Compare the decision tree model to a random forest. | from sklearn.ensemble import RandomForestClassifier
rfc = RandomForestClassifier(n_estimators=100)
rfc.fit(X_train, y_train)
rfc_pred = rfc.predict(X_test)
# TODO 4a
# TODO -- Your code here.
# TODO 4b
# TODO -- Your code here. | notebooks/launching_into_ml/labs/supplemental/decision_trees_and_random_Forests_in_Python.ipynb | GoogleCloudPlatform/asl-ml-immersion | apache-2.0 |
<H2> Create a normally distributed random variable</H2> | # create some data
mymean = 28.74
mysigma = 8.33 # standard deviation!
rv_norm = norm(loc = mymean, scale = mysigma)
data = rv_norm.rvs(size = 150)
plt.hist(data, bins=20, facecolor='red', alpha=.3);
plt.ylabel('Number of events');
plt.xlim(0,100); | Optimization/Maximum_likelihood_estimation.ipynb | JoseGuzman/myIPythonNotebooks | gpl-2.0 |
<H2> Define a model function</H2> | def mynorm(x, params):
mu, sigma = params
# scipy implementation
mynorm = norm(loc = mu, scale = sigma)
return mynorm.pdf(x)
mynorm(0, [0,1]) # 0.39 | Optimization/Maximum_likelihood_estimation.ipynb | JoseGuzman/myIPythonNotebooks | gpl-2.0 |
<H2> Loglikelihood function to be minimize </H2> | def loglikelihood(params, data):
mu = params['mean'].value
sigma = params['std'].value
l1 = np.log( mynorm(data, [mu, sigma]) ).sum()
return(-l1) # return negative loglikelihood to minimize
myfoo = Parameters()
myfoo.add('mean', value = 20)
myfoo.add('std', value = 5.0)
loglikelihood(myfoo, data)
... | Optimization/Maximum_likelihood_estimation.ipynb | JoseGuzman/myIPythonNotebooks | gpl-2.0 |
The estimated mean and standard deviation should be identical to the mean
and the standard deviation of the sample population | np.mean(data), np.std(data) | Optimization/Maximum_likelihood_estimation.ipynb | JoseGuzman/myIPythonNotebooks | gpl-2.0 |
<H2> Plot histogram and model together </H2> | # Compute binwidth
counts, binedge = np.histogram(data, bins=20);
bincenter = [0.5 * (binedge[i] + binedge[i+1]) for i in xrange(len(binedge)-1)]
binwidth = (max(bincenter) - min(bincenter)) / len(bincenter)
# Adjust PDF function to data
ivar = np.linspace(0, 100, 100)
params = [ myparams['mean'].value, myparams['s... | Optimization/Maximum_likelihood_estimation.ipynb | JoseGuzman/myIPythonNotebooks | gpl-2.0 |
<a name="part-1---generative-adversarial-networks-gan--deep-convolutional-gan-dcgan"></a>
Part 1 - Generative Adversarial Networks (GAN) / Deep Convolutional GAN (DCGAN)
<a name="introduction"></a>
Introduction
Recall from the lecture that a Generative Adversarial Network is two networks, a generator and a discriminato... | # We'll keep a variable for the size of our image.
n_pixels = 32
n_channels = 3
input_shape = [None, n_pixels, n_pixels, n_channels]
# And then create the input image placeholder
X = tf.placeholder(dtype=tf.float32, name='X', shape=[None, n_pixels, n_pixels,n_channels]) | session-5/session-5-part-1-new.ipynb | goddoe/CADL | apache-2.0 |
<a name="building-the-encoder"></a>
Building the Encoder
Let's build our encoder just like in Session 3. We'll create a function which accepts the input placeholder, a list of dimensions describing the number of convolutional filters in each layer, and a list of filter sizes to use for the kernel sizes in each convolu... | def encoder(x, channels, filter_sizes, activation=tf.nn.tanh, reuse=None):
# Set the input to a common variable name, h, for hidden layer
h = x
# Now we'll loop over the list of dimensions defining the number
# of output filters in each layer, and collect each hidden layer
hs = []
for layer_i i... | session-5/session-5-part-1-new.ipynb | goddoe/CADL | apache-2.0 |
<a name="building-the-discriminator-for-the-training-samples"></a>
Building the Discriminator for the Training Samples
Finally, let's take the output of our encoder, and make sure it has just 1 value by using a fully connected layer. We can use the libs/utils module's, linear layer to do this, which will also reshape ... | def discriminator(X,
channels=[50, 50, 50, 50],
filter_sizes=[4, 4, 4, 4],
activation=utils.lrelu,
reuse=None):
# We'll scope these variables to "discriminator_real"
with tf.variable_scope('discriminator', reuse=reuse):
# Encode X:... | session-5/session-5-part-1-new.ipynb | goddoe/CADL | apache-2.0 |
Now let's create the discriminator for the real training data coming from X: | D_real = discriminator(X) | session-5/session-5-part-1-new.ipynb | goddoe/CADL | apache-2.0 |
And we can see what the network looks like now: | graph = tf.get_default_graph()
nb_utils.show_graph(graph.as_graph_def()) | session-5/session-5-part-1-new.ipynb | goddoe/CADL | apache-2.0 |
<a name="building-the-decoder"></a>
Building the Decoder
Now we're ready to build the Generator, or decoding network. This network takes as input a vector of features and will try to produce an image that looks like our training data. We'll send this synthesized image to our discriminator which we've just built above... | # We'll need some variables first. This will be how many
# channels our generator's feature vector has. Experiment w/
# this if you are training your own network.
n_code = 16
# And in total how many feature it has, including the spatial dimensions.
n_latent = (n_pixels // 16) * (n_pixels // 16) * n_code
# Let's buil... | session-5/session-5-part-1-new.ipynb | goddoe/CADL | apache-2.0 |
Now we'll build the decoder in much the same way as we built our encoder. And exactly as we've done in Session 3! This requires one additional parameter "channels" which is how many output filters we want for each net layer. We'll interpret the dimensions as the height and width of the tensor in each new layer, the ... | def decoder(z, dimensions, channels, filter_sizes,
activation=tf.nn.relu, reuse=None):
h = z
hs = []
for layer_i in range(len(dimensions)):
with tf.variable_scope('layer{}'.format(layer_i+1), reuse=reuse):
h, W = utils.deconv2d(x=h,
n_output_h=d... | session-5/session-5-part-1-new.ipynb | goddoe/CADL | apache-2.0 |
<a name="building-the-generator"></a>
Building the Generator
Now we're ready to use our decoder to take in a vector of features and generate something that looks like our training images. We have to ensure that the last layer produces the same output shape as the discriminator's input. E.g. we used a [None, 64, 64, 3]... | # Explore these parameters.
def generator(Z,
dimensions=[n_pixels//8, n_pixels//4, n_pixels//2, n_pixels],
channels=[50, 50, 50, n_channels],
filter_sizes=[4, 4, 4, 4],
activation=utils.lrelu):
with tf.variable_scope('generator'):
G, Hs = decoder(Z_te... | session-5/session-5-part-1-new.ipynb | goddoe/CADL | apache-2.0 |
Now let's call the generator function with our input placeholder Z. This will take our feature vector and generate something in the shape of an image. | G = generator(Z)
graph = tf.get_default_graph()
nb_utils.show_graph(graph.as_graph_def()) | session-5/session-5-part-1-new.ipynb | goddoe/CADL | apache-2.0 |
<a name="building-the-discriminator-for-the-generated-samples"></a>
Building the Discriminator for the Generated Samples
Lastly, we need another discriminator which takes as input our generated images. Recall the discriminator that we have made only takes as input our placeholder X which is for our actual training sam... | D_fake = discriminator(G, reuse=True) | session-5/session-5-part-1-new.ipynb | goddoe/CADL | apache-2.0 |
Now we can look at the graph and see the new discriminator inside the node for the discriminator. You should see the original discriminator and a new graph of a discriminator within it, but all the weights are shared with the original discriminator. | nb_utils.show_graph(graph.as_graph_def()) | session-5/session-5-part-1-new.ipynb | goddoe/CADL | apache-2.0 |
<a name="gan-loss-functions"></a>
GAN Loss Functions
We now have all the components to our network. We just have to train it. This is the notoriously tricky bit. We will have 3 different loss measures instead of our typical network with just a single loss. We'll later connect each of these loss measures to two opti... | with tf.variable_scope('loss/generator'):
loss_G = tf.reduce_mean(utils.binary_cross_entropy(D_fake, tf.ones_like(D_fake))) | session-5/session-5-part-1-new.ipynb | goddoe/CADL | apache-2.0 |
What we've just written is a loss function for our generator. The generator is optimized when the discriminator for the generated samples produces all ones. In contrast to the generator, the discriminator will have 2 measures to optimize. One which is the opposite of what we have just written above, as well as 1 mor... | with tf.variable_scope('loss/discriminator/real'):
loss_D_real = utils.binary_cross_entropy(D_real, tf.zeros_like(D_real))
with tf.variable_scope('loss/discriminator/fake'):
loss_D_fake = utils.binary_cross_entropy(D_fake, tf.ones_like(D_fake))
with tf.variable_scope('loss/discriminator'):
loss_D = tf.reduc... | session-5/session-5-part-1-new.ipynb | goddoe/CADL | apache-2.0 |
With our loss functions, we can create an optimizer for the discriminator and generator:
<a name="building-the-optimizers-w-regularization"></a>
Building the Optimizers w/ Regularization
We're almost ready to create our optimizers. We just need to do one extra thing. Recall that our loss for our generator has a flow ... | # Grab just the variables corresponding to the discriminator
# and just the generator:
vars_d = [v for v in tf.trainable_variables()
if v.name.startswith('discriminator')]
print('Training discriminator variables:')
[print(v.name) for v in tf.trainable_variables()
if v.name.startswith('discriminator')]
vars_... | session-5/session-5-part-1-new.ipynb | goddoe/CADL | apache-2.0 |
We can also apply regularization to our network. This will penalize weights in the network for growing too large. | d_reg = tf.contrib.layers.apply_regularization(
tf.contrib.layers.l2_regularizer(1e-6), vars_d)
g_reg = tf.contrib.layers.apply_regularization(
tf.contrib.layers.l2_regularizer(1e-6), vars_g) | session-5/session-5-part-1-new.ipynb | goddoe/CADL | apache-2.0 |
The last thing you may want to try is creating a separate learning rate for each of your generator and discriminator optimizers like so: | learning_rate = 0.0001
lr_g = tf.placeholder(tf.float32, shape=[], name='learning_rate_g')
lr_d = tf.placeholder(tf.float32, shape=[], name='learning_rate_d') | session-5/session-5-part-1-new.ipynb | goddoe/CADL | apache-2.0 |
Now you can feed the placeholders to your optimizers. If you run into errors creating these, then you likely have a problem with your graph's definition! Be sure to go back and reset the default graph and check the sizes of your different operations/placeholders.
With your optimizers, you can now train the network by... | opt_g = tf.train.AdamOptimizer(learning_rate=lr_g).minimize(loss_G + g_reg, var_list=vars_g)
opt_d = tf.train.AdamOptimizer(learning_rate=lr_d).minimize(loss_D + d_reg, var_list=vars_d) | session-5/session-5-part-1-new.ipynb | goddoe/CADL | apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.