markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Train
Train the neural network on the preprocessed data. If you have a hard time getting a good loss, check the forums to see if anyone is having the same problem. | """
DON'T MODIFY ANYTHING IN THIS CELL
"""
import time, sys
def get_accuracy(target, logits):
"""
Calculate accuracy
"""
max_seq = max(target.shape[1], logits.shape[1])
if max_seq - target.shape[1]:
target = np.pad(
target,
[(0,0),(0,max_seq - target.shape[1])],
... | language-translation/dlnd_language_translation.ipynb | retnuh/deep-learning | mit |
Sentence to Sequence
To feed a sentence into the model for translation, you first need to preprocess it. Implement the function sentence_to_seq() to preprocess new sentences.
Convert the sentence to lowercase
Convert words into ids using vocab_to_int
Convert words not in the vocabulary, to the <UNK> word id. | def sentence_to_seq(sentence, vocab_to_int):
"""
Convert a sentence to a sequence of ids
:param sentence: String
:param vocab_to_int: Dictionary to go from the words to an id
:return: List of word ids
"""
unk = vocab_to_int['<UNK>']
return [vocab_to_int.get(word, unk) for word in sentenc... | language-translation/dlnd_language_translation.ipynb | retnuh/deep-learning | mit |
Translate
This will translate translate_sentence from English to French. | translate_sentence = 'Paris is cold and wet in the winter .'
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
translate_sentence = sentence_to_seq(translate_sentence, source_vocab_to_int)
loaded_graph = tf.Graph()
with tf.Session(graph=loaded_graph) as sess:
# Load saved model
loader = tf.train.import_meta_graph(l... | language-translation/dlnd_language_translation.ipynb | retnuh/deep-learning | mit |
Change the cron schedule (line 1) to the desired frequency. | %%writefile modem/bqml/pipeline/shell_scheduler.sh
cron_schedule="*/2 * * * *"
echo "$cron_schedule cd ~/modem/bqml/pipeline && python main.py >> logs.csv" | crontab -
echo "Your workflow has been scheduled with the cron schedule of $cron_schedule. Enjoy!" | bqml/utils/BQML_Deployment_Template_Compute_Engine.ipynb | google/modem | apache-2.0 |
Step 3: Deploy the code
Run the cell below. | !sh enable_firewall.sh
!gcloud compute scp --recurse modem $SSH_DESTINATION:~/
!echo "Code deployed." | bqml/utils/BQML_Deployment_Template_Compute_Engine.ipynb | google/modem | apache-2.0 |
Step 4: Test and schedule the code
When you run the cell below, an interactive shell opens up. Use the following commands -
1. Test the code.
If successful, you should see a SUCCESS message along with a timestamp. Proceed to Step 2. <br>
If there are any errors, you can either work through the colab from Step 1, fixi... | !gcloud compute ssh $SSH_DESTINATION | bqml/utils/BQML_Deployment_Template_Compute_Engine.ipynb | google/modem | apache-2.0 |
Implement Preprocessing Functions
The first thing to do to any dataset is preprocessing. Implement the following preprocessing functions below:
- Lookup Table
- Tokenize Punctuation
Lookup Table
To create a word embedding, you first need to transform the words to ids. In this function, create two dictionaries:
- Dict... | import numpy as np
from collections import Counter
import problem_unittests as tests
from sklearn.feature_extraction.text import CountVectorizer
def create_lookup_tables(text, min_count=1):
"""
Create lookup tables for vocabulary
:param text: The text of tv scripts split into words
:return: A tuple of ... | tv-script-generation/dlnd_tv_script_generation.ipynb | seinberg/deep-learning | mit |
Tokenize Punctuation
We'll be splitting the script into a word array using spaces as delimiters. However, punctuations like periods and exclamation marks make it hard for the neural network to distinguish between the word "bye" and "bye!".
Implement the function token_lookup to return a dict that will be used to token... | def token_lookup():
"""
Generate a dict to turn punctuation into a token.
:return: Tokenize dictionary where the key is the punctuation and the value is the token
"""
return {
'.': '__period__',
',': '__comma__',
'"': '__double_quote__',
';': '__semi-colon__',
... | tv-script-generation/dlnd_tv_script_generation.ipynb | seinberg/deep-learning | mit |
Input
Implement the get_inputs() function to create TF Placeholders for the Neural Network. It should create the following placeholders:
- Input text placeholder named "input" using the TF Placeholder name parameter.
- Targets placeholder
- Learning Rate placeholder
Return the placeholders in the following tuple (Inpu... | def get_inputs():
"""
Create TF Placeholders for input, targets, and learning rate.
:return: Tuple (input, targets, learning rate)
"""
input_test = tf.placeholder(tf.int32, [None, None], name='input')
targets = tf.placeholder(tf.int32, [None, None], name='targets')
learning_rate = tf.placeho... | tv-script-generation/dlnd_tv_script_generation.ipynb | seinberg/deep-learning | mit |
Build RNN Cell and Initialize
Stack one or more BasicLSTMCells in a MultiRNNCell.
- The Rnn size should be set using rnn_size
- Initalize Cell State using the MultiRNNCell's zero_state() function
- Apply the name "initial_state" to the initial state using tf.identity()
Return the cell and initial state in the follo... | def get_init_cell(batch_size, rnn_size, lstm_layers=1, keep_prob=1.0):
"""
Create an RNN Cell and initialize it.
:param batch_size: Size of batches
:param rnn_size: Size of RNNs
:param lstm_layers: Number of layers to apply to LSTM
:param keep_prob: Dropout keep probability for cell
:return:... | tv-script-generation/dlnd_tv_script_generation.ipynb | seinberg/deep-learning | mit |
Word Embedding
Apply embedding to input_data using TensorFlow. Return the embedded sequence. | def get_embed(input_data, vocab_size, embed_dim):
"""
Create embedding for <input_data>.
:param input_data: TF placeholder for text input.
:param vocab_size: Number of words in vocabulary.
:param embed_dim: Number of embedding dimensions
:return: Embedded input.
"""
#embedding = tf.Varia... | tv-script-generation/dlnd_tv_script_generation.ipynb | seinberg/deep-learning | mit |
Build RNN
You created a RNN Cell in the get_init_cell() function. Time to use the cell to create a RNN.
- Build the RNN using the tf.nn.dynamic_rnn()
- Apply the name "final_state" to the final state using tf.identity()
Return the outputs and final_state state in the following tuple (Outputs, FinalState) | def build_rnn(cell, inputs):
"""
Create a RNN using a RNN Cell
:param cell: RNN Cell
:param inputs: Input text data
:return: Tuple (Outputs, Final State)
"""
# note: third argument is placeholder for initial_state
outputs, final_state = tf.nn.dynamic_rnn(
cell=cell, inputs=inputs... | tv-script-generation/dlnd_tv_script_generation.ipynb | seinberg/deep-learning | mit |
Build the Neural Network
Apply the functions you implemented above to:
- Apply embedding to input_data using your get_embed(input_data, vocab_size, embed_dim) function.
- Build RNN using cell and your build_rnn(cell, inputs) function.
- Apply a fully connected layer with a linear activation and vocab_size as the number... | def build_nn(cell, rnn_size, input_data, vocab_size, embed_dim):
"""
Build part of the neural network
:param cell: RNN cell
:param embed_dim: Size of word embeddings to use
:param input_data: Input data
:param vocab_size: Vocabulary size
:param embed_dim: Number of embedding dimensions
:... | tv-script-generation/dlnd_tv_script_generation.ipynb | seinberg/deep-learning | mit |
Batches
Implement get_batches to create batches of input and targets using int_text. The batches should be a Numpy array with the shape (number of batches, 2, batch size, sequence length). Each batch contains two elements:
- The first element is a single batch of input with the shape [batch size, sequence length]
- Th... | def get_batches(int_text, batch_size, seq_length):
"""
Return batches of input and target
:param int_text: Text with the words replaced by their ids
:param batch_size: The size of batch
:param seq_length: The length of sequence
:return: Batches as a Numpy array
"""
n_batches = (len(int_t... | tv-script-generation/dlnd_tv_script_generation.ipynb | seinberg/deep-learning | mit |
Neural Network Training
Hyperparameters
Tune the following parameters:
Set num_epochs to the number of epochs.
Set batch_size to the batch size.
Set rnn_size to the size of the RNNs.
Set embed_dim to the size of the text word embeddings.
Set seq_length to the length of sequence.
Set learning_rate to the learning rate.... | # reminder: tune hyper params according to advice at
# check out https://nd101.slack.com/messages/C3PJV4741/convo/C3PJV4741-1490412688.590254/
# Number of Epochs
num_epochs = 50
# Batch Size
batch_size = 128
# RNN Size
rnn_size = 512
# Number of embedding dimensions
embed_dim = 300
# Sequence Length
seq_length = 16
#... | tv-script-generation/dlnd_tv_script_generation.ipynb | seinberg/deep-learning | mit |
Build the Graph
Build the graph using the neural network you implemented. | """
DON'T MODIFY ANYTHING IN THIS CELL
"""
from tensorflow.contrib import seq2seq
train_graph = tf.Graph()
with train_graph.as_default():
vocab_size = len(int_to_vocab)
input_text, targets, lr = get_inputs()
input_data_shape = tf.shape(input_text)
cell, initial_state = get_init_cell(input_data_shape[0]... | tv-script-generation/dlnd_tv_script_generation.ipynb | seinberg/deep-learning | mit |
Choose Word
Implement the pick_word() function to select the next word using probabilities. | def weighted_choice(choices):
"""
Cribbed from http://stackoverflow.com/questions/3679694/a-weighted-version-of-random-choice
"""
total = sum(w for c, w in choices)
r = random.uniform(0, total)
upto = 0
for c, w in choices:
if upto + w >= r:
return c
upto += w
... | tv-script-generation/dlnd_tv_script_generation.ipynb | seinberg/deep-learning | mit |
Generate TV Script
This will generate the TV script for you. Set gen_length to the length of TV script you want to generate. | gen_length = 400
# homer_simpson, moe_szyslak, or Barney_Gumble
prime_word = 'bart_simpson'
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
loaded_graph = tf.Graph()
with tf.Session(graph=loaded_graph) as sess:
# Load saved model
loader = tf.train.import_meta_graph(load_dir + '.meta')
lo... | tv-script-generation/dlnd_tv_script_generation.ipynb | seinberg/deep-learning | mit |
Cost of running a business (difficulty: 5)
You are running a small business for n months. Each month i, you either run it out of your office in New York and incur an operating cost Ni, or out of your office in Seattle and incur a cost Si. If you move to a different city in month i + 1, you pay a fixed cost M. <br>
A pl... | n = 4
M = 10
NY = [1, 3, 20, 30]
SE = [50, 20, 2, 4]
NY = [100, 1, 100, 1, 100, 1, 100, 1, 100, 1]
SE = [1, 100, 1, 100, 1, 100, 1, 100, 1, 100]
n = 10
M = 10
dp = [0]*n
dp[0] = 'NY' if NY[0] < SE[0] else 'SE'
for i in range(1, n):
if dp[i-1] == 'NY':
dp[i] = 'NY' if NY[i] + M < SE[i] else 'SE'
els... | dynamic_programming.ipynb | pablovicente/python-tutorials | mit |
Travel Planning (difficulty: 5)
You are going on a long trip. You start on the road at mile post 0. Along the way there are n hotels, at mile posts
a1 < a2 < · · · < an, where each ai is measured from the starting point. The only places you are allowed to stop are at these hotels, but you can choose which of the hotels... | a = [0]
opt = [0]
a = [0,200]
opt = [0, 0]
a = [0,200,400,600,800,1000]
opt = [0, 0, 0, 0, 0, 0]
a = [0,400,800,1600,1700,112000]
opt = [0, 40000, 80000, 440000, 450000, 12122460000]
a = [0,100,150,300,350,550,750,800,950]
opt = [0, 10000, 2500, 5000, 2500, 2500, 2500, 5000, 2500]
n = len(a)
dp = [0]*n
for i in r... | dynamic_programming.ipynb | pablovicente/python-tutorials | mit |
A game with stones (difficulty: 5)
You’re playing a game with stones. At the beginning of the game, there are n piles of stones, each of size pi ≥ 1, in a line. Your goal is to merge the stones in one big pile subject to the following rules of the game: <br>
1. At each step, you can merge two adjacent piles of sizes x,... | a = [5,2,8,6,3,6,7]
n = len(a)
dp = [1]*n
for i in range(1,n):
for j in range(0,i):
if a[i] > a[j] and dp[i] < dp[j] + 1:
dp[i] = dp[j]+1
print dp | dynamic_programming.ipynb | pablovicente/python-tutorials | mit |
A card game (dificulty: 8)
Consider the following game. To begin, n cards are laid out in order from left to right, where n is even. The i-th card from the left has value vi. Two players take turns, each taking one card, with the restriction that on a player’s turn, they can only take either the leftmost or the rightmo... | def card_game(a):
n = len(a)
dp = [[0]*n for _ in range(n)]
for gap in range(n):
for i, j in zip(range(0, n), range(gap, n)):
x = dp[i+2][j] if (i+2) <= j else 0
y = dp[i+1][j-1] if (i+1) <= (j-1) else 0
z = dp[i+2][j] if i <= (j-2) else 0
... | dynamic_programming.ipynb | pablovicente/python-tutorials | mit |
But if our goal is to partition the space of $k$-mers, couldn't we use a hash function instead? Say $k$ is 10 and $l$ is 4. A 10,4-minimizing scheme is a way for dividing the space of $4^{10}$ 10-mers (a million or so) into $4^4 = 256$ partitions. We can accomplish this with a hash function that maps $k$-mers to int... | minimizer('abracadabr', 4), minimizer('bracadabra', 4) | notebooks/Minimizers.ipynb | BenLangmead/comp-genomics-class | gpl-2.0 |
But their hash values (modulo 256) are not the same: | # you might need to 'pip install mmh3' first
import mmh3
mmh3.hash('abracadabr') % 256, mmh3.hash('bracadabra') % 256 | notebooks/Minimizers.ipynb | BenLangmead/comp-genomics-class | gpl-2.0 |
Partition size distribution
A feature of hash functions is that they divide the 10-mers quite uniformly (evenly) among the 256 buckets. 10,4-minimzers divide them much less uniformly. This becomes clear when you consider that, given a random 10-mer, the 4-mer TTTT is very unlikely to be its minimizer, whereas the 4-... | import random
random.seed(629)
def random_kmer(k):
return ''.join([random.choice('ACGT') for _ in range(k)])
%matplotlib inline
import matplotlib.pyplot as plt
def plot_counts(counter, title=None):
idx = range(256)
cnts = list(map(lambda x: counter.get(x, 0), idx))
plt.bar(idx, cnts, ec='none')
... | notebooks/Minimizers.ipynb | BenLangmead/comp-genomics-class | gpl-2.0 |
Récupération des données
Les données ont été préalablement téléchargées et zippées. | from ensae_teaching_cs.data import load_irep
load_irep()
import pandas
df = pandas.read_csv("2017/Prod_dechets_dangereux.csv")
df.head()
[_ for _ in set(df.Nom_Etablissement) if "lubrizol" in _.lower()]
df[df.Nom_Etablissement.str.contains("LUBRI")].head().T
ets = pandas.read_csv("2017/etablissements.csv")
ets.head... | _doc/notebooks/data/data_irep.ipynb | sdpython/ensae_teaching_cs | mit |
Conversion des coordonnées
Les coordonnées utilisées par l'admnistration française sont souvent différentes des longitudes et latitudes, il pourrait s'agir du système Lambert 93. Il faut convertir. | from pyproj import Proj, transform
p1 = Proj(init='epsg:4326') # longitude / latidude
p2 = Proj(init='epsg:2154') # Lambert 93
exp = (509411.0, 2494315.0) # Rouen dans la base de données reçues.
transform(p1, p2, 1.059011, 49.434654), exp | _doc/notebooks/data/data_irep.ipynb | sdpython/ensae_teaching_cs | mit |
Ca n'a pas l'air d'être ça. On en essaye plusieurs. | from tqdm import tqdm
summary = []
for i in tqdm(range(2000, 10000)):
try:
p2 = Proj(init='epsg:%d' % i)
except RuntimeError:
# does not exist
continue
try:
res = transform(p1, p2, 1.059011, 49.434654)
except RuntimeError:
# impossible
continue
d = abs... | _doc/notebooks/data/data_irep.ipynb | sdpython/ensae_teaching_cs | mit |
On tombe donc sur espg:2192 ou espg:7401. | p2 = Proj(init='epsg:2192')
long, lat = transform(p2, p1, ets.Coordonnees_X.values, ets.Coordonnees_Y.values)
ets['LLX'] = long
ets['LLY'] = lat
ets[ets.Nom_Etablissement.str.contains("LUBRI")] | _doc/notebooks/data/data_irep.ipynb | sdpython/ensae_teaching_cs | mit |
Ca a l'air de coller. | ets16 = pandas.read_csv("2016/etablissements.csv")
ets17 = pandas.read_csv("2017/etablissements.csv")
p16 = pandas.read_csv("2016/Prod_dechets_dangereux.csv")
p17 = pandas.read_csv("2017/Prod_dechets_dangereux.csv")
long, lat = transform(p2, p1, ets16.Coordonnees_X.values, ets16.Coordonnees_Y.values)
ets16['LLX'] = lo... | _doc/notebooks/data/data_irep.ipynb | sdpython/ensae_teaching_cs | mit |
Les fusions se sont bien passées. On vérifie que les unités sont comparables. | set(p16.Unite), set(p17.Unite) | _doc/notebooks/data/data_irep.ipynb | sdpython/ensae_teaching_cs | mit |
Vue dynamique | from ipywidgets import interact
@interact(annee=[2016, 2017], column=list(sorted(p16.columns)), x=(0, 100000, 100))
def show_rows(annee=2017, column='Quantite', x=100000):
if annee == 2017:
return ets17_2[ets17_2[column] >= x].sort_values(column).T
else:
return ets16_2[ets16_2[column] >= x].sor... | _doc/notebooks/data/data_irep.ipynb | sdpython/ensae_teaching_cs | mit |
Cartes
On regarde les projets sur la métropole en 2017. | lim_metropole = [-5, 10, 41, 52]
ets17_2_metro = ets17_2[((ets17_2.LLX >= lim_metropole[0]) & (ets17_2.LLX <= lim_metropole[1]) &
(ets17_2.LLY >= lim_metropole[2]) & (ets17_2.LLY <= lim_metropole[3]))]
ets17_2_metro.shape, ets17_2.shape
import cartopy.crs as ccrs
import cartopy.feature as cfe... | _doc/notebooks/data/data_irep.ipynb | sdpython/ensae_teaching_cs | mit |
Q: Determine the parameters ${\bf w}$ fit by the model. It might be helpful to consult the documentation for the classifier on the <a href="http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html">sklearn website</a>. Hint: The classifier stores the coefficients and bias term sepa... | import numpy as np
import math
fig = plt.figure(figsize=(8,8))
plt.scatter(X_train[:, 0], X_train[:, 1], s=100, c=[mycolors["red"] if yi==1 else mycolors["blue"] for yi in y_train])
plt.xlabel('Sepal length')
plt.ylabel('Sepal width')
x_min, x_max = np.min(X_train[:,0])-0.1, np.max(X_train[:,0])+0.1
y_min, y_max = np.... | notebooks/ML_morning_JTN/02_Logistic_Regression_and_Text_Models.ipynb | jamesfolberth/NGC_STEM_camp_AWS | bsd-3-clause |
To be consistent with sklearn conventions, we'll encode the documents as row-vectors stored in a matrix. In this case, each row of the matrix corresponds to a document, and each column corresponds to a term in the vocabulary. For our example this gives us a matrix $M$ of shape $3 \times 6$. The $(d,t)$-entry in $M$ ... | M = np.zeros((len(D),len(V)))
for ii, doc in enumerate(D):
for term in doc.split():
if(term in V): #only print if the term is in our dictionary
... #TODO
print(M) | notebooks/ML_morning_JTN/02_Logistic_Regression_and_Text_Models.ipynb | jamesfolberth/NGC_STEM_camp_AWS | bsd-3-clause |
Notice that the query document included the word $\texttt{new}$ twice, which corresponds to the entry in the $(0,2)$-position.
Q: What's missing from $x4$ that we might expect to see from the query document?
<br>
Problem 3: Term Frequency - Inverse Document Frequency
The Bag-of-Words model for text classification is... | idf = np.array([np.log(3), np.log(3), np.log(3./2), np.log(3), np.log(3./2), np.log(3./2)])
Xtfidf = np.dot(X.todense(), np.diag(idf)) | notebooks/ML_morning_JTN/02_Logistic_Regression_and_Text_Models.ipynb | jamesfolberth/NGC_STEM_camp_AWS | bsd-3-clause |
Explore the Data
The dataset is broken into batches to prevent your machine from running out of memory. The CIFAR-10 dataset consists of 5 batches, named data_batch_1, data_batch_2, etc.. Each batch contains the labels and images that are one of the following:
* airplane
* automobile
* bird
* cat
* deer
* dog
* frog
*... | %matplotlib inline
%config InlineBackend.figure_format = 'retina'
import helper
import numpy as np
from sklearn.preprocessing import LabelBinarizer
# Explore the dataset
batch_id = 1
sample_id = 6
helper.display_stats(cifar10_dataset_folder_path, batch_id, sample_id)
features, labels = helper.load_cfar10_batch(cifar1... | image-classification/dlnd_image_classification.ipynb | joeandrewkey/deep-learning | mit |
Implement Preprocess Functions
Normalize
In the cell below, implement the normalize function to take in image data, x, and return it as a normalized Numpy array. The values should be in the range of 0 to 1, inclusive. The return object should be the same shape as x. | def normalize(x):
"""
Normalize a list of sample image data in the range of 0 to 1
: x: List of image data. The image shape is (32, 32, 3)
: return: Numpy array of normalize data
"""
# TODO: Implement Function
# Apply normalization over the entire numpy array (fast)
possible_values = 25... | image-classification/dlnd_image_classification.ipynb | joeandrewkey/deep-learning | mit |
One-hot encode
Just like the previous code cell, you'll be implementing a function for preprocessing. This time, you'll implement the one_hot_encode function. The input, x, are a list of labels. Implement the function to return the list of labels as One-Hot encoded Numpy array. The possible values for labels are 0 t... | from sklearn import preprocessing
def one_hot_encode(x):
"""
One hot encode a list of sample labels. Return a one-hot encoded vector for each label.
: x: List of sample Labels
: return: Numpy array of one-hot encoded labels
"""
# TODO: Implement Function
labels = np.array(x)
lb = preproc... | image-classification/dlnd_image_classification.ipynb | joeandrewkey/deep-learning | mit |
Build the network
For the neural network, you'll build each layer into a function. Most of the code you've seen has been outside of functions. To test your code more thoroughly, we require that you put each layer in a function. This allows us to give you better feedback and test for simple mistakes using our unittest... | import tensorflow as tf
#Also seen in 11.30
def neural_net_image_input(image_shape):
"""
Return a Tensor for a batch of image input
: image_shape: Shape of the images
: return: Tensor for image input.
"""
# Tensor of floats for an unbounded list of tensors (32, 32, 3), named x
return tf... | image-classification/dlnd_image_classification.ipynb | joeandrewkey/deep-learning | mit |
Convolution and Max Pooling Layer
Convolution layers have a lot of success with images. For this code cell, you should implement the function conv2d_maxpool to apply convolution then max pooling:
* Create the weight and bias using conv_ksize, conv_num_outputs and the shape of x_tensor.
* Apply a convolution to x_tensor... | def conv2d_maxpool(x_tensor, conv_num_outputs, conv_ksize, conv_strides, pool_ksize, pool_strides):
"""
Apply convolution then max pooling to x_tensor
:param x_tensor: TensorFlow Tensor
:param conv_num_outputs: Number of outputs for the convolutional layer
:param conv_ksize: kernal size 2-D Tuple fo... | image-classification/dlnd_image_classification.ipynb | joeandrewkey/deep-learning | mit |
Flatten Layer
Implement the flatten function to change the dimension of x_tensor from a 4-D tensor to a 2-D tensor. The output should be the shape (Batch Size, Flattened Image Size). Shortcut option: you can use classes from the TensorFlow Layers or TensorFlow Layers (contrib) packages for this layer. For more of a ch... | from tensorflow.contrib.layers import flatten as contrib_flatten
def flatten(x_tensor):
"""
Flatten x_tensor to (Batch Size, Flattened Image Size)
: x_tensor: A tensor of size (Batch Size, ...), where ... are the image dimensions.
: return: A tensor of size (Batch Size, Flattened Image Size).
"""
... | image-classification/dlnd_image_classification.ipynb | joeandrewkey/deep-learning | mit |
Fully-Connected Layer
Implement the fully_conn function to apply a fully connected layer to x_tensor with the shape (Batch Size, num_outputs). Shortcut option: you can use classes from the TensorFlow Layers or TensorFlow Layers (contrib) packages for this layer. For more of a challenge, only use other TensorFlow packag... | from tensorflow.contrib.layers import fully_connected
def fully_conn(x_tensor, num_outputs):
"""
Apply a fully connected layer to x_tensor using weight and bias
: x_tensor: A 2-D tensor where the first dimension is batch size.
: num_outputs: The number of output that the new tensor should be.
: retu... | image-classification/dlnd_image_classification.ipynb | joeandrewkey/deep-learning | mit |
Output Layer
Implement the output function to apply a fully connected layer to x_tensor with the shape (Batch Size, num_outputs). Shortcut option: you can use classes from the TensorFlow Layers or TensorFlow Layers (contrib) packages for this layer. For more of a challenge, only use other TensorFlow packages.
Note: Act... | def output(x_tensor, num_outputs):
"""
Apply a output layer to x_tensor using weight and bias
: x_tensor: A 2-D tensor where the first dimension is batch size.
: num_outputs: The number of output that the new tensor should be.
: return: A 2-D tensor where the second dimension is num_outputs.
"""... | image-classification/dlnd_image_classification.ipynb | joeandrewkey/deep-learning | mit |
Create Convolutional Model
Implement the function conv_net to create a convolutional neural network model. The function takes in a batch of images, x, and outputs logits. Use the layers you created above to create this model:
Apply 1, 2, or 3 Convolution and Max Pool layers
Apply a Flatten Layer
Apply 1, 2, or 3 Full... | def conv_net(x, keep_prob):
"""
Create a convolutional neural network model
: x: Placeholder tensor that holds image data.
: keep_prob: Placeholder tensor that hold dropout keep probability.
: return: Tensor that represents logits
"""
# local variables
#conv_num_outputs = 32
conv_ksi... | image-classification/dlnd_image_classification.ipynb | joeandrewkey/deep-learning | mit |
Train the Neural Network
Single Optimization
Implement the function train_neural_network to do a single optimization. The optimization should use optimizer to optimize in session with a feed_dict of the following:
* x for image input
* y for labels
* keep_prob for keep probability for dropout
This function will be cal... | def train_neural_network(session, optimizer, keep_probability, feature_batch, label_batch):
"""
Optimize the session on a batch of images and labels
: session: Current TensorFlow session
: optimizer: TensorFlow optimizer function
: keep_probability: keep probability
: feature_batch: Batch of Num... | image-classification/dlnd_image_classification.ipynb | joeandrewkey/deep-learning | mit |
Show Stats
Implement the function print_stats to print loss and validation accuracy. Use the global variables valid_features and valid_labels to calculate validation accuracy. Use a keep probability of 1.0 to calculate the loss and validation accuracy. | def print_stats(session, feature_batch, label_batch, cost, accuracy):
"""
Print information about loss and validation accuracy
: session: Current TensorFlow session
: feature_batch: Batch of Numpy image data
: label_batch: Batch of Numpy label data
: cost: TensorFlow cost function
: accuracy... | image-classification/dlnd_image_classification.ipynb | joeandrewkey/deep-learning | mit |
Create forward bond future PV (Exposure) time profile
Setting up parameters | t_step = 1.0 / 365.0
simNumber = 10
trim_start = date(2005,3,10)
trim_end = date(2010,12,31) # Last Date of the Portfolio
start = date(2005, 3, 10)
referenceDate = date(2005, 3, 10) | GroupHW_1_Exposure_ForwardBond.ipynb | sytjyjj/Group-Homeproject1 | apache-2.0 |
Data input for the CouponBond portfolio
The word portfolio is used to describe just a dict of CouponBonds.
This line creates a referenceDateList
myScheduler = Scheduler()
ReferenceDateList = myScheduler.getSchedule(start=referenceDate,end=trim_end,freq="1M", referencedate=referenceDate)
Create Simulator
This section cr... | myScheduler = Scheduler()
ReferenceDateList = myScheduler.getSchedule(start=referenceDate,end=trim_end,freq="1M", referencedate=referenceDate)
# Create Simulator
xOIS = [ 3.0, 0.07536509, -0.208477, 0.07536509]
myVasicek = MC_Vasicek_Sim(ReferenceDateList,xOIS,simNumber,1/365.0)
myVasicek.setVasicek(x=xOIS,minDay=tri... | GroupHW_1_Exposure_ForwardBond.ipynb | sytjyjj/Group-Homeproject1 | apache-2.0 |
Create Libor and portfolioScheduleOfCF. This datelist contains all dates
to be used in any calculation of the portfolio positions.
BondCoupon class has to have a method getScheduleComplete, which return
fullSet on [0] and datelist on [1], calculated by BondCoupon as:
def getScheduleComplete(self):
self.datelist=self.... | # Create FullDateList
portfolioScheduleOfCF = set(ReferenceDateList)
for i in range(len(myPortfolio)):
portfolioScheduleOfCF=portfolioScheduleOfCF.union(myPortfolio[i].getScheduleComplete()[0]
)
portfolioScheduleOfCF = sorted(portfolioScheduleOfCF.union(ReferenceDateList))
OIS = myVasicek.getSmallLibor(datelist=por... | GroupHW_1_Exposure_ForwardBond.ipynb | sytjyjj/Group-Homeproject1 | apache-2.0 |
Hide/Show tip labels
The argument tip_labels can be entered as True, False, or as a list of names, with the default being True in which case the tip labels are shown and are taken from the tree object (parsed from the newick string). | ## A tree with edge lengths
newick = "((apple:2,orange:4):2,(((tomato:2,eggplant:1):2,pepper:3):1,tomatillo:2):1);"
tre = toytree.tree(newick)
## show tip labels
tre.draw();
## hide tip labels
tre.draw(tip_labels=False); | docs/TipLabels.ipynb | eaton-lab/toytree | bsd-3-clause |
Modify tip labels
You can enter a list to tip_labels if which case the list of names will replace the labels at the tips of the tree. The list must be the same length as the number of tips. You can use the function .get_tip_labels() to return a list of names that are currently on the tree. Names are ordered from top to... | ## enter a new list of names
tipnames = ["a", "b", "c", "d", "e", "f"]
tre.draw(tip_labels=tipnames);
## get list of existing names and modify it
modnames = ["tip - " + i for i in tre.get_tip_labels()]
tre.draw(tip_labels=modnames);
## you can use HTML tags to further style the text
modnames = ["<b>{}</b>".format(i) ... | docs/TipLabels.ipynb | eaton-lab/toytree | bsd-3-clause |
Color tip labels
You can color all tip labels to be the same color or you can enter a different color for each tip label by entering a list of colors. Colors can be entered as HTML names, as HEX strings, or as rgba codes. See the excellent Toyplot color guide for more color options. | ## set a single tip labels color
tre.draw(tip_labels_colors="darkcyan");
## use a list of colors to assign different values to tips
colorlist = ["darkcyan" if "tom" in t else "darkorange" for t in tre.get_tip_labels()]
tre.draw(tip_labels_colors=colorlist); | docs/TipLabels.ipynb | eaton-lab/toytree | bsd-3-clause |
Aligning tip labels
By default Toytree plots trees without edge length information so that the tips are aligned. If you add the argument use_edge_lengths=True then tips of the tree will no longer necessarily be aligned and thus tip labels may not be aligned. To use edge lengths but still enforce aligning of the tip lab... | ## default tree
tre.draw();
## with edge lengths
tre.draw(use_edge_lengths=False);
## with edge lengths and aligned tips
tre.draw(tip_labels_align=True); | docs/TipLabels.ipynb | eaton-lab/toytree | bsd-3-clause |
Styling edges on aligned tip trees
You can of course modify the styling of the dashed edge lengths (such as making them not dashed or changing their color) by using the edge_align_style dictionary. | ## style the edges and alignment-edges
tre.draw(
use_edge_lengths=True,
tip_labels_align=True,
edge_style={"stroke": "darkcyan"},
edge_align_style={"stroke": "darkorange"},
); | docs/TipLabels.ipynb | eaton-lab/toytree | bsd-3-clause |
Price History
Retrieve Google's stock price history. | %%with_globals
%%bigquery --project {PROJECT}
SELECT *
FROM `stock_src.price_history`
LIMIT 10
def query_stock(symbol):
return bq.query('''
SELECT *
FROM `stock_src.price_history`
WHERE symbol="{0}"
ORDER BY Date
'''.format(symbol)).to_dataframe()
df_stock = query_stock('GOOG')
df_stock.Date ... | courses/machine_learning/deepdive2/time_series_prediction/solutions/optional_1_data_exploration.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Stock splits can also impact our data - causing a stock price to rapidly drop. In practice, we would need to clean all of our stock data to account for this. This would be a major effort! Fortunately, in the case of IBM, for example, all stock splits occurred before the year 2000.
Learning objective 2 | stock_symbol = 'IBM'
%%with_globals
%%bigquery df --project {PROJECT}
SELECT date, close
FROM `stock_src.price_history`
WHERE symbol='{stock_symbol}'
ORDER BY date
IBM_STOCK_SPLIT_DATE = '1979-05-10'
ax = df.plot(x='date', y='close')
ax.vlines(pd.to_datetime(IBM_STOCK_SPLIT_DATE),
0, 500, linestyle='dashed'... | courses/machine_learning/deepdive2/time_series_prediction/solutions/optional_1_data_exploration.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Linear systems
<img src="https://i.ytimg.com/vi/7ujEpq7MWfE/maxresdefault.jpg" width="400" />
Given square matrix $A_{nxn}$, and vector $\mathbf{b}$, find such vector $\mathbf{x}$ that $A \cdot \mathbf{x} = \mathbf{b}$.
Example 1
$$
\begin{bmatrix} 10 & -1 & 2 & 0 \ -1 & 11 & -1 & 3 \ 2 & -1 & 10 & -1 \ 0 & 3 & -1 & 8... | def is_square(a):
return a.shape[0] == a.shape[1]
def has_solutions(a, b):
return np.linalg.matrix_rank(a) == np.linalg.matrix_rank(np.append(a, b[np.newaxis].T, axis=1)) | num_methods/first/lab2.ipynb | lionell/laboratories | mit |
Diagonally dominance
We say that matrix $A_{nxn}$ is diagonally dominant iff
$$ |a_{ii}| \geq \sum_{j\neq i} |a_{ij}|, \quad \forall i=1, n \, $$
equivalent
$$ 2 \cdot |a_{ii}| \geq \sum_{j = 1, n} |a_{ij}|, \quad \forall i=1, n \, $$
Also we say that matrix $A_{nxn}$ is strictly diagonally dominant iff it's diagonally... | def is_dominant(a):
return np.all(np.abs(a).sum(axis=1) <= 2 * np.abs(a).diagonal()) and \
np.any(np.abs(a).sum(axis=1) < 2 * np.abs(a).diagonal())
def make_dominant(a):
for i in range(a.shape[0]):
a[i][i] = max(abs(a[i][i]), np.abs(a[i]).sum() - abs(a[i][i]) + 1)
return a | num_methods/first/lab2.ipynb | lionell/laboratories | mit |
NOTE! All generate functions will return already strictly diagonally dominant matrices | def generate_random(n):
return make_dominant(np.random.rand(n, n) * n), np.random.rand(n) * n
def generate_hilbert(n):
return make_dominant(sp.linalg.hilbert(n)), np.arange(1, n + 1, dtype=np.float)
def linalg(a, b, debug=False):
return np.linalg.solve(a, b), | num_methods/first/lab2.ipynb | lionell/laboratories | mit |
Gauss method
To perform row reduction on a matrix, one uses a sequence of elementary row operations to modify the matrix until the lower left-hand corner of the matrix is filled with zeros, as much as possible. There are three types of elementary row operations:
Swapping two rows
Multiplying a row by a non-zero numbe... | def gauss(a, b, debug=False):
assert is_square(a) and has_solutions(a, b)
a = np.append(a.copy(), b[np.newaxis].T, axis=1)
i = 0
k = 0
while i < a.shape[0]:
r = np.argmax(a[i:, i]) + i
a[[i, r]] = a[[r, i]]
if a[i][i] == 0:
break
for... | num_methods/first/lab2.ipynb | lionell/laboratories | mit |
Gauss-Seidel method
The Gauss–Seidel method is an iterative technique for solving a square system of $n$ linear equations with unknown $x$:
$$ A \mathbf{x} = \mathbf{b} $$
It is defined by the iteration
$$ L_* \mathbf{x}^{(k+1)} = \mathbf{b} - U \mathbf{x}^{(k)}, $$
where $\mathbf{x}^{(k)}$ is the $k$-th approximation ... | def seidel(a, b, x0 = None, limit=20000, debug=False):
assert is_square(a) and is_dominant(a) and has_solutions(a, b)
if x0 is None:
x0 = np.zeros_like(b, dtype=np.float)
x = x0.copy()
while limit > 0:
tx = x.copy()
for i in range(a.shape[0]):
x[i] = (b[i] - a[i,... | num_methods/first/lab2.ipynb | lionell/laboratories | mit |
Jacobi method
The Jacobi method is an iterative technique for solving a square system of $n$ linear equations with unknown $x$:
$$ A \mathbf{x} = \mathbf{b} $$
where
$$A=\begin{bmatrix} a_{11} & a_{12} & \cdots & a_{1n} \ a_{21} & a_{22} & \cdots & a_{2n} \ \vdots & \vdots & \ddots & \vdots \a_{n1} & a_{n2} & \cdots & ... | def jacobi(a, b, x0 = None, limit=20000, debug=False):
assert is_square(a) and is_dominant(a) and has_solutions(a, b)
if x0 is None:
x0 = np.zeros_like(b, dtype=np.float)
x = x0.copy()
while limit > 0:
tx = x.copy()
for i in range(a.shape[0]):
x[i] = (b[i] - a[i,... | num_methods/first/lab2.ipynb | lionell/laboratories | mit |
Evaluation
To evaluate algorithm we are going to calculate
$$ score = || A \cdot \mathbf{x^*} - \mathbf{b} || $$
where $\mathbf{x}^*$ is a result of algorithm. | def norm(a, b, res):
return np.linalg.norm(a.dot(res) - b)
def run(method, a, b, verbose=False, **kwargs):
if not verbose:
print("-" * 100)
print(method.__name__.upper())
res = method(a, b, **kwargs)
score = norm(a, b, res[0])
if not verbose:
print("res =", res)
prin... | num_methods/first/lab2.ipynb | lionell/laboratories | mit |
Back to examples
Example 1
Do you remember example from the problem statement? Now, we are going to see how iterative algorithms converges for that example. | a4 = np.array([[10., -1., 2., 0.],
[-1., 11., -1., 3.],
[2., -1., 10., -1.],
[0., 3., -1., 8.]])
print(a4)
b = np.array([6., 25., -11., 15.])
print("b =", b)
_ = run(linalg, a4, b)
_ = run(gauss, a4, b)
_ = run(seidel, a4, b)
_ = run(jacobi, a4, b) | num_methods/first/lab2.ipynb | lionell/laboratories | mit |
Seidel vs Jacobi
Here is tricky example of linear system, when Jacobi method converges faster than Gauss-Seidel.
As you will see, Jacobi needs only 1 iteration to find an answer, while Gauss-Seidel needs over 10 iterations to find approximate solution. | a4 = np.array([[1., -1/8, 1/32, 1/64],
[-1/2, 2., 1/16, 1/32],
[-1., 1/4, 4., 1/16],
[-1., 1/4, 1/8, 8.]])
print(a4)
b = np.array([1., 4., 16., 64.])
print("b =", b)
_ = run(linalg, a4, b)
_ = run(gauss, a4, b)
_ = run(seidel, a4, b)
_ = run(jacobi, a4, b) | num_methods/first/lab2.ipynb | lionell/laboratories | mit |
Hilbert matrices
Now, let's have a look at Hilbert matrix. It's said that non-iterative methods should do bad here. Proof? | a, b = generate_hilbert(1000)
print("LINALG =", run(linalg, a, b, verbose=True))
print("GAUSS =", run(gauss, a, b, verbose=True))
print("SEIDEL =", run(seidel, a, b, x0=np.zeros_like(b, dtype=np.float), verbose=True))
print("JACOBI =", run(jacobi, a, b, x0=np.zeros_like(b, dtype=np.float), verbose=True)) | num_methods/first/lab2.ipynb | lionell/laboratories | mit |
As we can see, it's true for huge $n>1000$, that direct methods works bad on Hilbert matrices. But how about the size of matrix? Is $n=500$ enough? | def plot_hilbert_score_by_matrix_size(method, sizes):
scores = np.zeros_like(sizes, dtype=np.float)
for i in range(len(sizes)):
a, b = generate_hilbert(sizes[i])
scores[i] = run(method, a, b, verbose=True)
plt.plot(sizes, scores, label=method.__name__)
sizes = np.linspace(1, 600, num=50, dt... | num_methods/first/lab2.ipynb | lionell/laboratories | mit |
Random matrices
It's time to test our methods on random generated matrices.
To be deterministic, we are going to set seed equals to $17$ every time, we call generate_random(...) | a, b = generate_random(20)
_ = run(linalg, a, b)
_ = run(gauss, a, b)
_ = run(seidel, a, b)
_ = run(jacobi, a, b) | num_methods/first/lab2.ipynb | lionell/laboratories | mit |
Runtime
Now, let's compare our methods by actual time running.
To have more accurate results, we need to run them on large matrix(eg. random $200x200$). | a, b = generate_random(200)
%timeit run(linalg, a, b, verbose=True)
%timeit run(gauss, a, b, verbose=True)
%timeit run(seidel, a, b, verbose=True)
%timeit run(jacobi, a, b, verbose=True) | num_methods/first/lab2.ipynb | lionell/laboratories | mit |
Convergence speed
We already have compared methods by accuracy and time, but how about speed.
Now we are going to show what will be the error of method after some number of iterations. To be more clear we use logarithmic x-scale. | def plot_convergence(method, a, b, limits):
scores = np.zeros_like(limits, dtype=np.float)
for i in range(len(limits)):
scores[i] = run(method, a, b, x0 = np.zeros_like(b, dtype=np.float), limit=limits[i], verbose=True)
plt.plot(limits, scores, label=method.__name__)
a, b = generate_random(15)
limi... | num_methods/first/lab2.ipynb | lionell/laboratories | mit |
← Back to Index
Neural Networks
Neural networks are a category of machine learning models which have seen a resurgence since 2006. Deep learning is the recent area of machine learning which combines many neuron layers (e.g. 20, 50, or more) to form a "deep" neural network. In doing so, a deep neural network can ac... | from keras.models import Sequential
from keras.layers.core import Dense
import keras.optimizers | neural_networks.ipynb | stevetjoa/stanford-mir | mit |
Create a neural network architecture by layering neurons. Define the number of neurons in each layer and their activation functions: | model = Sequential()
model.add(Dense(4, activation='relu', input_dim=2))
model.add(Dense(4, activation='relu'))
model.add(Dense(2, activation='softmax')) | neural_networks.ipynb | stevetjoa/stanford-mir | mit |
Choose the optimizer, i.e. the update rule that the neural network will use to train: | optimizer = keras.optimizers.SGD(decay=0.001, momentum=0.99) | neural_networks.ipynb | stevetjoa/stanford-mir | mit |
Compile the model, i.e. create the low-level code that the CPU or GPU will actually use for its calculations during training and testing: | model.compile(loss='binary_crossentropy', optimizer=optimizer) | neural_networks.ipynb | stevetjoa/stanford-mir | mit |
Example: XOR
The operation XOR is defined as: XOR(x, y) = 1 if x != y else 0
Synthesize training data for the XOR problem. | X_train = numpy.random.randn(10000, 2)
print(X_train.shape)
print(X_train[:5]) | neural_networks.ipynb | stevetjoa/stanford-mir | mit |
Create target labels for the training data. | y_train = numpy.array([
[float(x[0]*x[1] > 0), float(x[0]*x[1] <= 0)]
for x in X_train
])
print(y_train.shape)
y_train[:5] | neural_networks.ipynb | stevetjoa/stanford-mir | mit |
Plot the training data: | plt.figure(figsize=(9, 5))
plt.scatter(X_train[y_train[:,0]>0.5,0], X_train[y_train[:,0]>0.5,1], c='r', s=1)
plt.scatter(X_train[y_train[:,1]>0.5,0], X_train[y_train[:,1]>0.5,1], c='b', s=1) | neural_networks.ipynb | stevetjoa/stanford-mir | mit |
Finally, train the model! | results = model.fit(X_train, y_train, epochs=200, batch_size=100) | neural_networks.ipynb | stevetjoa/stanford-mir | mit |
Plot the loss function as a function of the training iteration number: | plt.plot(results.history['loss']) | neural_networks.ipynb | stevetjoa/stanford-mir | mit |
Create test data: | X_test = numpy.random.randn(5000, 2) | neural_networks.ipynb | stevetjoa/stanford-mir | mit |
Use the trained neural network to make predictions from the test data: | y_test = model.predict(X_test)
y_test.shape | neural_networks.ipynb | stevetjoa/stanford-mir | mit |
Let's see if it worked: | plt.figure(figsize=(9, 5))
plt.scatter(X_test[y_test[:, 0] > 0.5,0], X_test[y_test[:, 0] > 0.5,1], c='r', s=1)
plt.scatter(X_test[y_test[:, 1] > 0.5,0], X_test[y_test[:, 1] > 0.5,1], c='b', s=1) | neural_networks.ipynb | stevetjoa/stanford-mir | mit |
Binary vector generator
Version 2 - via Itertool | # def binary_vector_2(rows_n = [2,4,6,8,10], columns_n = 10):
# rows = how_many(rows_n, 10)
# index = 0
# locations = np.zeros((rows, columns_n))
# for i in rows_n:
# for bin_string in kbits(10,i):
# bin_array = np.fromstring(bin_string,'u1') - ord('0')
# locations[index... | Input_utils.ipynb | bramacchino/numberSense | mit |
Accumulator Inputs ## | import numpy as np
class accumulatorMatrix(object):
"""
Generate a matrix which row vectors correspond to accumulated numerosity, where each number
is coded by repeating 1 times times. If zero = true, the zero vector is included.
Args:
max_number (int): the greatest number to be represen... | Input_utils.ipynb | bramacchino/numberSense | mit |
Label the data | def find_labels(inputs, multiple=1, one_hot=False):
"""
Generate the labels corresponding to binary vectors. If one_hot = true, the label are
on hot encoded, otherwise integers.
Args:
inputs (int, ndarray): ndarray row samples
multiple (int): lenght of unity representation
... | Input_utils.ipynb | bramacchino/numberSense | mit |
Create dataset
Namedtuple | from collections import namedtuple
def Dataset(inputs, labels):
"""Creates dataset
Args:
inputs (array):
labels (array): corresponding labels
Returns:
Datasets: named tuple
"""
Dataset = namedtuple('Dataset', ['data', 'labels'])
Datasets = Dataset(inputs, labels)
... | Input_utils.ipynb | bramacchino/numberSense | mit |
Pickling | from collections import namedtuple
Dataset = namedtuple('Dataset', ['data', 'labels'])
#data_verguts = Dataset(inputs, labels)
import pickle
def pickle_test(Data, name):
f = open(name+'.pickle', 'ab')
pickle.dump(Data, f)
f.close()
#pickle_test(data_verguts, "verguts")
# # Test opening the pickle
# pi... | Input_utils.ipynb | bramacchino/numberSense | mit |
We now pickle the named_tuple
cfr. When to pickle
See http://localhost:8888/notebooks/Dropbox/Programming/Jupyter/Competitive-Unsupervised/NNTf.ipynb
for creating a panda dataframe out of the namedtuple
http://stackoverflow.com/questions/16377215/how-to-pickle-a-namedtuple-instance-correctly
https://blog.hartleybrody... | rows_n = [2,4,6,8,10]
#comb(10, rows_n)
inputs = binary_vector_2(distribution = comb(10, rows_n))
labels = find_labels(inputs, multiple=2, one_hot=True)
count = 0
for i in inputs:
print(count, i, int(np.sum(i)/2), labels[count])
count +=1 | Input_utils.ipynb | bramacchino/numberSense | mit |
Accumulator inputs - Verguts& Fias##
Numerosity from 1 to 5, where unity is represented by 3 repeated ones. (e.g. 2 is represented as
[1,1,1,1,1,1,0,0,0,0,0,0,0,0,0]).
No zero vector. | inputs = accumulatorMatrix(5, times=2).outputs
labels = find_labels(inputs, multiple=2, one_hot=True)
Dataset = namedtuple('Dataset', ['data', 'labels'])
verguts2004 = Dataset(inputs, labels)
pickle_test(verguts2004, "verguts_accumulator")
verguts2004.labels | Input_utils.ipynb | bramacchino/numberSense | mit |
Import libraries | # Import Python libraries
import logging
import os
import sys
import gc
import pandas as pd
from IPython.display import display, HTML
from collections import OrderedDict
import numpy as np
import statistics
from scipy.stats import stats
# Import local Python modules
from Configs.CONSTANTS import CONSTANTS
from Configs... | TCARER_Basic.ipynb | mesgarpour/T-CARER | apache-2.0 |
<br/><br/>
1.1. Initialise General Settings
<font style="font-weight:bold;color:red">Main configuration Settings: </font>
- Specify the full path of the configuration file
<br/>	 → config_path
- Specify the full path of the output folder
<br/>	 → io_path
- Specify the application name (the suffix o... | config_path = os.path.abspath("ConfigInputs/CONFIGURATIONS.ini")
io_path = os.path.abspath("../../tmp/TCARER/Basic_prototype")
app_name = "T-CARER"
submodel_name = "hesIp"
submodel_input_name = "tcarer_model_features_ip"
print("\n The full path of the configuration file: \n\t", config_path,
"\n The full path of ... | TCARER_Basic.ipynb | mesgarpour/T-CARER | apache-2.0 |
<br/><br/>
Initialise logs | if not os.path.exists(io_path):
os.makedirs(io_path, exist_ok=True)
logger = Logger(path=io_path, app_name=app_name, ext="log")
logger = logging.getLogger(app_name) | TCARER_Basic.ipynb | mesgarpour/T-CARER | apache-2.0 |
Initialise constants and some of classes | # Initialise constants
CONSTANTS.set(io_path, app_name)
# Initialise other classes
readers_writers = ReadersWriters()
preprocess = PreProcess(io_path)
feature_selection = FeatureSelection()
plts = Plots()
# Set print settings
pd.set_option('display.width', 1600, 'display.max_colwidth', 800) | TCARER_Basic.ipynb | mesgarpour/T-CARER | apache-2.0 |
1.2. Initialise Features Metadata
Read the input features' confugration file & store the features metadata | # variables settings
features_metadata = dict()
features_metadata_all = readers_writers.load_csv(path=CONSTANTS.io_path, title=CONSTANTS.config_features_path, dataframing=True)
features_metadata = features_metadata_all.loc[(features_metadata_all["Selected"] == 1) &
(featu... | TCARER_Basic.ipynb | mesgarpour/T-CARER | apache-2.0 |
Set input features' metadata dictionaries | # Dictionary of features types, dtypes, & max-states
features_types = dict()
features_dtypes = dict()
features_states_values = dict()
features_names_group = dict()
for _, row in features_metadata.iterrows():
if not pd.isnull(row["Variable_Max_States"]):
states_values = str(row["Variable_Max_States"]).split... | TCARER_Basic.ipynb | mesgarpour/T-CARER | apache-2.0 |
<br/><br/>
<font style="font-weight:bold;color:red">2. Generate Features</font>
<font style="font-weight:bold;color:red">Notes:</font>
- It generates the final spell-wise & temporal features from the MySQL table(s), & converts it into CSV(s);
- It generates the CSV(s) based on the configuration file of the feat... | skip = True
# settings
csv_schema = ["my_db_schema"]
csv_input_tables = ["tcarer_features"]
csv_history_tables = ["hesIp"]
csv_column_index = "localID"
csv_output_table = "tcarer_model_features_ip"
csv_query_batch_size = 100000
if skip is False:
# generate the csv file
variables = Variables(submodel_name,
... | TCARER_Basic.ipynb | mesgarpour/T-CARER | apache-2.0 |
<br/><br/>
3. Read Data
Read the input features from the CSV input file | features_input = readers_writers.load_csv(path=CONSTANTS.io_path, title=submodel_input_name, dataframing=True)
features_input.astype(dtype=features_dtypes)
print("Number of columns: ", len(features_input.columns), "; Total records: ", len(features_input.index)) | TCARER_Basic.ipynb | mesgarpour/T-CARER | apache-2.0 |
Verify features visually | display(features_input.head()) | TCARER_Basic.ipynb | mesgarpour/T-CARER | apache-2.0 |
<br/><br/>
4. Filter Features
4.1. Descriptive Statsistics
Produce a descriptive stat report of 'Categorical', 'Continuous', & 'TARGET' features | file_name = "Step_04_Data_ColumnNames"
readers_writers.save_csv(path=CONSTANTS.io_path, title=file_name, data=list(features_input.columns.values), append=False)
file_name = "Step_04_Stats_Categorical"
o_stats = preprocess.stats_discrete_df(df=features_input, includes=features_types_group["CATEGORICAL"],
... | TCARER_Basic.ipynb | mesgarpour/T-CARER | apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.