markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Reducing overfitting
Now that we've gotten the model to overfit, we can take a number of steps to reduce this.
Approaches to reducing overfitting
We do not necessarily need to rely on dropout or other regularization approaches to reduce overfitting. There are other techniques we should try first, since regularlization,... | # dim_ordering='tf' uses tensorflow dimension ordering,
# which is the same order as matplotlib uses for display.
# Therefore when just using for display purposes, this is more convenient
gen = image.ImageDataGenerator(rotation_range=10, width_shift_range=0.1,
height_shift_range=0.1, width_zoom_range=0.2, she... | Overfitting.ipynb | sysid/nbs | mit |
Let's take a look at how this generator changes a single image (the details of this code don't matter much, but feel free to read the comments and keras docs to understand the details if you're interested). | # Create a 'batch' of a single image
img = np.expand_dims(ndimage.imread('cat.jpg'),0)
# Request the generator to create batches from this image
aug_iter = gen.flow(img)
# Get eight examples of these augmented images
aug_imgs = [next(aug_iter)[0].astype(np.uint8) for i in range(8)]
# The original
plt.imshow(img[0]) | Overfitting.ipynb | sysid/nbs | mit |
As you can see below, there's no magic to data augmentation - it's a very intuitive approach to generating richer input data. Generally speaking, your intuition should be a good guide to appropriate data augmentation, although it's a good idea to test your intuition by checking the results of different augmentation app... | # Augmented data
plots(aug_imgs, (20,7), 2)
# Ensure that we return to theano dimension ordering
K.set_image_dim_ordering('th') | Overfitting.ipynb | sysid/nbs | mit |
Adding data augmentation
Let's try adding a small amount of data augmentation, and see if we reduce overfitting as a result. The approach will be identical to the method we used to finetune the dense layers in lesson 2, except that we will use a generator with augmentation configured. Here's how we set up the generator... | gen = image.ImageDataGenerator(rotation_range=15, width_shift_range=0.1,
height_shift_range=0.1, zoom_range=0.1, horizontal_flip=True)
batches = get_batches(path+'train', gen, batch_size=batch_size)
# NB: We don't want to augment or shuffle the validation set
val_batches = get_batches(p... | Overfitting.ipynb | sysid/nbs | mit |
When using data augmentation, we can't pre-compute our convolutional layer features, since randomized changes are being made to every input image. That is, even if the training process sees the same image multiple times, each time it will have undergone different data augmentation, so the results of the convolutional l... | fc_model = get_fc_model()
for layer in conv_model.layers: layer.trainable = False
# Look how easy it is to connect two models together!
conv_model.add(fc_model) | Overfitting.ipynb | sysid/nbs | mit |
Now we can compile, train, and save our model as usual - note that we use fit_generator() since we want to pull random images from the directories on every batch. | conv_model.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy'])
conv_model.fit_generator(batches, samples_per_epoch=batches.nb_sample, nb_epoch=8,
validation_data=val_batches, nb_val_samples=val_batches.nb_sample)
conv_model.fit_generator(batches, samples_per_epoch=ba... | Overfitting.ipynb | sysid/nbs | mit |
Batch normalization
About batch normalization
Batch normalization (batchnorm) is a way to ensure that activations don't become too high or too low at any point in the model. Adjusting activations so they are of similar scales is called normalization. Normalization is very helpful for fast training - if some activations... | conv_layers[-1].output_shape[1:]
def get_bn_layers(p):
return [
MaxPooling2D(input_shape=conv_layers[-1].output_shape[1:]),
Flatten(),
Dense(4096, activation='relu'),
Dropout(p),
BatchNormalization(),
Dense(4096, activation='relu'),
Dropout(p),
BatchN... | Overfitting.ipynb | sysid/nbs | mit |
1. Calculate an average spectrum to ID peaks | averagespectrum = PCAsynthetic.get_hyper_peaks(spectralmatrix, threshold = 0.01)
plt.plot(averagespectrum) | Notebooks/PCAonSyntheticData.ipynb | kongjy/hyperAFM | mit |
2. Make a feature matrix, n x p, where n = number of samples, p = number of features | featurematrix = PCAsynthetic.makefeaturematrix(spectralmatrix, averagespectrum)
featurematrix[10:13,:] | Notebooks/PCAonSyntheticData.ipynb | kongjy/hyperAFM | mit |
3. Standardize: zero mean, unit variance. (and check!) | featurematrix_std = PCAsynthetic.stdfeature(featurematrix, axis = 0)
#along axis 0 = running vertically downwards, across rows; 1 = columns
mean = featurematrix_std.mean(axis=0)
variance = featurematrix_std.std(axis=0)
print(mean, variance) | Notebooks/PCAonSyntheticData.ipynb | kongjy/hyperAFM | mit |
4. Sklearn PCA | #define number of principal components
sklearn_pca = sklearnPCA(n_components=9)
#matrix with each sample in terms of the PCs
SkPC = sklearn_pca.fit_transform(featurematrix_std)
#covariance matrix
Skcov = sklearn_pca.get_covariance()
#score matrix
#Skscore = sklearn_pca.score_samples(featurematrix_std)
#explained... | Notebooks/PCAonSyntheticData.ipynb | kongjy/hyperAFM | mit |
5. Matrix decomposition (see A User's Guide to Principal Components by Jackson, 1991.)
U’SU = L
U = orthonormal matrix, characteristic vectors
S = covariance matrix
L = diagonal matrix, characteristic roots
Get characteristic roots: |𝑺−𝒍𝑰|=𝟎
Get characteristic vector: |𝑺−𝒍𝑰|𝒕𝒊=𝟎
The projection of sample n... | mean_vec = np.mean(featurematrix_std, axis=0)
#need to take transpose, since rowvar = true by default
cov_mat = np.cov(featurematrix_std.T)
#solve for characteristic roots and vectors
eig_vals, eig_vecs = np.linalg.eig(cov_mat)
#check that the loadings squared sum to 1:
Lsquared = sum(eig_vecs**2) | Notebooks/PCAonSyntheticData.ipynb | kongjy/hyperAFM | mit |
6. Matlab's PCA | mlPCA = PCA(featurematrix_std)
#get projections of samples into PCA space
mltrans = mlPCA.Y
#reshape
mltransreshape = mltrans.reshape((256,256,9))
mlloadings = mlPCA.Wt
#mltrans[513,:] should be the same as mltransreshape[2,1,:]
mlloadings.shape | Notebooks/PCAonSyntheticData.ipynb | kongjy/hyperAFM | mit |
Check that all three give similar results | #projection of first sample, on to the first PC
P11 = np.dot(eig_vecs[:,0], featurematrix_std[0,:]-mean_vec)
mlP11 = mlPCA.Y[0,0]
SkP11 = SkPC[0,0]
P12 = np.dot(eig_vecs[:,1], featurematrix_std[0,:]-mean_vec)
mlP12 = mlPCA.Y[0,1]
SkP12 = SkPC[0,1]
P152 = np.dot(eig_vecs[:,1], featurematrix_std[15,:]-mean_vec)
mlP... | Notebooks/PCAonSyntheticData.ipynb | kongjy/hyperAFM | mit |
PCA with the entire IR spectrum. | #Reshape spectral matrix
IRmatrix=spectralmatrix.reshape(65536,559)
print(IRmatrix[1,:].shape)
#make sure we've reshaped correctly
plt.plot(reshapespect[555,:]) | Notebooks/PCAonSyntheticData.ipynb | kongjy/hyperAFM | mit |
Standardize matrix | IRmatrix=np.concatenate((IRmatrix[:,20:60], IRmatrix[:,230:270], IRmatrix[:,420:460], IRmatrix[:,100:140],IRmatrix[:,305:345], IRmatrix[:,470:510], IRmatrix[:,158:198], IRmatrix[:,354:394], IRmatrix[:,512:552] ), axis=1)
#IRmatrix=np.concatenate((IRmatrix[:,30:40], IRmatrix[:,240:260], IRmatrix[:,430:450], IRmatrix[:,9... | Notebooks/PCAonSyntheticData.ipynb | kongjy/hyperAFM | mit |
Model Inputs
First we need to create the inputs for our graph. We need two inputs, one for the discriminator and one for the generator. Here we'll call the discriminator input inputs_real and the generator input inputs_z. We'll assign them the appropriate sizes for each of the networks.
Exercise: Finish the model_inpu... | def model_inputs(real_dim, z_dim):
#(Batch_size, Dim)
inputs_real = tf.placeholder(tf.float32, (None, real_dim), name='input_real')
inputs_z = tf.placeholder(tf.float32, (None, z_dim), name='input_z')
return inputs_real, inputs_z | gan_mnist/Intro_to_GANs_Exercises.ipynb | Luke035/dlnd-lessons | mit |
Generator network
Here we'll build the generator network. To make this network a universal function approximator, we'll need at least one hidden layer. We should use a leaky ReLU to allow gradients to flow backwards through the layer unimpeded. A leaky ReLU is like a normal ReLU, except that there is a small non-zero ... | def generator(z, out_dim, n_units=128, reuse=False, alpha=0.01):
''' Build the generator network.
Arguments
---------
z : Input tensor for the generator
out_dim : Shape of the generator output
n_units : Number of units in hidden layer
reuse : Reuse the variables... | gan_mnist/Intro_to_GANs_Exercises.ipynb | Luke035/dlnd-lessons | mit |
Discriminator
The discriminator network is almost exactly the same as the generator network, except that we're using a sigmoid output layer.
Exercise: Implement the discriminator network in the function below. Same as above, you'll need to return both the logits and the sigmoid output. Make sure to wrap your code in a... | def discriminator(x, n_units=128, reuse=False, alpha=0.01):
''' Build the discriminator network.
Arguments
---------
x : Input tensor for the discriminator
n_units: Number of units in hidden layer
reuse : Reuse the variables with tf.variable_scope
alpha : leak pa... | gan_mnist/Intro_to_GANs_Exercises.ipynb | Luke035/dlnd-lessons | mit |
Build network
Now we're building the network from the functions defined above.
First is to get our inputs, input_real, input_z from model_inputs using the sizes of the input and z.
Then, we'll create the generator, generator(input_z, input_size). This builds the generator with the appropriate input and output sizes.
Th... | tf.reset_default_graph()
# Create our input placeholders
input_real, input_z = model_inputs(real_dim=input_size, z_dim=z_size)
# Generator network here
#Output dim for generator is the same as real input dim
g_model = generator(z=input_z, alpha=alpha, n_units=g_hidden_size, out_dim=input_size)
# g_model is the generat... | gan_mnist/Intro_to_GANs_Exercises.ipynb | Luke035/dlnd-lessons | mit |
Discriminator and Generator Losses
Now we need to calculate the losses, which is a little tricky. For the discriminator, the total loss is the sum of the losses for real and fake images, d_loss = d_loss_real + d_loss_fake. The losses will by sigmoid cross-entropies, which we can get with tf.nn.sigmoid_cross_entropy_wit... | # Calculate losses
#Cross entropy tra logits e label sempre a 1 (sono le immagini vere)
real_labels = tf.ones_like(d_logits_real) * (1 - smooth) #Smoothed labels
d_loss_real = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_real, labels=real_labels))
#Fake uguale ma con label a 0
fake_labels = tf... | gan_mnist/Intro_to_GANs_Exercises.ipynb | Luke035/dlnd-lessons | mit |
Optimizers
We want to update the generator and discriminator variables separately. So we need to get the variables for each part and build optimizers for the two parts. To get all the trainable variables, we use tf.trainable_variables(). This creates a list of all the variables we've defined in our graph.
For the gener... | for var in tf.trainable_variables():
if 'generator' in var.name:
print(var.name)
# Optimizers
learning_rate = 0.002
# Get the trainable_variables, split into G and D parts
t_vars = tf.trainable_variables()
g_vars = [var for var in t_vars if var.name.startswith('generator')]
d_vars = [var for var in t_vars... | gan_mnist/Intro_to_GANs_Exercises.ipynb | Luke035/dlnd-lessons | mit |
Transforming Text into Numbers | from IPython.display import Image
review = "This was a horrible, terrible movie."
Image(filename='sentiment_network.png')
review = "The movie was excellent"
Image(filename='sentiment_network_pos.png')
vocab = set(total_counts.keys())
vocab_size = len(vocab)
print(vocab_size)
layer_0 = np.zeros((1, vocab_size))
la... | sentiment_network/Sentiment Classification - Mini Project 2.ipynb | mdiaz236/DeepLearningFoundations | mit |
Create stochastic policy
This time our policy should be a probability distribution.
policy[s,a] = P(take action a | in state s)
Since we still use integer state and action representations, you can use a 2-dimensional array to represent the policy.
Please initialize policy uniformly, that is, probabililities of all acti... | policy = np.ones(shape=(n_states, n_actions)) * 1 / n_actions
assert type(policy) in (np.ndarray, np.matrix)
assert np.allclose(policy, 1./n_actions)
assert np.allclose(np.sum(policy, axis=1), 1)
| reinforcement_learning/crossentropy_method.ipynb | trangel/Data-Science | gpl-3.0 |
Play the game
Just like before, but we also record all states and actions we took. | def generate_session(policy, t_max=10**4):
"""
Play game until end or for t_max ticks.
:param policy: an array of shape [n_states,n_actions] with action probabilities
:returns: list of states, list of actions and sum of rewards
"""
states, actions = [], []
total_reward = 0.
s = env.rese... | reinforcement_learning/crossentropy_method.ipynb | trangel/Data-Science | gpl-3.0 |
Crossentropy method steps | def select_elites(states_batch, actions_batch, rewards_batch, percentile=50):
"""
Select states and actions from games that have rewards >= percentile
:param states_batch: list of lists of states, states_batch[session_i][t]
:param actions_batch: list of lists of actions, actions_batch[session_i][t]
... | reinforcement_learning/crossentropy_method.ipynb | trangel/Data-Science | gpl-3.0 |
Training loop
Generate sessions, select N best and fit to those. | from IPython.display import clear_output
def show_progress(rewards_batch, log, percentile, reward_range=[-990, +10]):
"""
A convenience function that displays training progress.
No cool math here, just charts.
"""
mean_reward = np.mean(rewards_batch)
threshold = np.percentile(rewards_batch, p... | reinforcement_learning/crossentropy_method.ipynb | trangel/Data-Science | gpl-3.0 |
Reflecting on results
You may have noticed that the taxi problem quickly converges from <-1000 to a near-optimal score and then descends back into -50/-100. This is in part because the environment has some innate randomness. Namely, the starting points of passenger/driver change from episode to episode.
In case CEM fai... | from submit import submit_taxi
submit_taxi(generate_session, policy, 'tonatiuh_rangel@hotmail.com', '7uvgN7bBzpJzVw9f') | reinforcement_learning/crossentropy_method.ipynb | trangel/Data-Science | gpl-3.0 |
Data
load corpus vocab and wordidx | corpus_vocab_list, corpus_vocab_wordidx = None, None
with open('processed/stage1/vocab_words_wordidx.pkl', 'rb') as f:
(corpus_vocab_list, corpus_wordidx) = pickle.load(f)
print(len(corpus_vocab_list), len(corpus_wordidx)) | data_prep/word_vectors.ipynb | bicepjai/Deep-Survey-Text-Classification | mit |
load data | store = pd.HDFStore('processed/stage1/data_frames.h5')
train_df = store['train_df']
test_df = store['test_df'] | data_prep/word_vectors.ipynb | bicepjai/Deep-Survey-Text-Classification | mit |
Word Vectors Pre Trained
collecting biolab words | from gensim.models.keyedvectors import KeyedVectors
biolab_keyed_vectors_pubmed_pmc_wiki = KeyedVectors.load_word2vec_format('external/biolab_wvs/wikipedia-pubmed-and-PMC-w2v.bin', binary=True)
biolab_words_pubmed_pmc_wiki = biolab_keyed_vectors_pubmed_pmc_wiki.vocab.keys()
biolab_words = set(biolab_words_pubmed_pmc_w... | data_prep/word_vectors.ipynb | bicepjai/Deep-Survey-Text-Classification | mit |
dont need word to id dict since this is indexed with words
using biolab words for missing corpus words | undesirable_ascii_characters = list(range(32))
undesirable_ascii_characters.remove(10) #keep new line since this might be used for sentence tokenizer
undesirable_charmap = dict.fromkeys(undesirable_ascii_characters)
from nltk import word_tokenize
from utils import custom_word_tokenizer, apply_custom_regx
custom_token... | data_prep/word_vectors.ipynb | bicepjai/Deep-Survey-Text-Classification | mit |
for tensorboard | tb_vocab_size=5000
tb_vocab_biolab = list(vocab_biolab)[:tb_vocab_size]
with open("view_wvs_tb/tb_vocab.tsv", "w") as fp:
wr = csv.writer(fp, delimiter='\n')
wr.writerow(tb_vocab_biolab)
tb_word_vectors = np.random.randn(tb_vocab_size, 200)
for i,word in enumerate(tb_vocab_biolab):
tb_word_vectors[i] = cu... | data_prep/word_vectors.ipynb | bicepjai/Deep-Survey-Text-Classification | mit |
building word vectors of 200d for model | corpus_word_vectors = np.random.randn(len(vocab_words), 200)
corpus_word_vectors.shape | data_prep/word_vectors.ipynb | bicepjai/Deep-Survey-Text-Classification | mit |
fill in biolab vectors available | for word in vocab_biolab:
dataset_corpus_word_index = vocab_wordidx[word]
corpus_word_vectors[dataset_corpus_word_index] = custom_tokenized_biolab_pubmed_pmc_wiki_wv[word] | data_prep/word_vectors.ipynb | bicepjai/Deep-Survey-Text-Classification | mit |
total words not updated with training from biolab | words_not_updated = set(vocab_words) - vocab_biolab
len(words_not_updated)
words_not_updated
np.save("processed/stage1/biolab_updated_wvs.npy", corpus_word_vectors) | data_prep/word_vectors.ipynb | bicepjai/Deep-Survey-Text-Classification | mit |
gcloud tensorboard serving | dataset_corpus_words_list = np.load("dataset_corpus_words_list.npy")
corpus_word_vectors = np.load("corpus_word_vectors.npy")
tb_vocab_size = 10000
local_tb_dir = "/home/bicepjai/Projects/ml-compete/kaggle/mskrct/data_prep_2_ft/model_wv_visualize/gcloud/"
with open(local_tb_dir+"/vocab.tsv", "wb") as fp:
wr = cs... | data_prep/word_vectors.ipynb | bicepjai/Deep-Survey-Text-Classification | mit |
for http://projector.tensorflow.org/ vectors need to be in tsv form | # np.savetxt("model_wv_visualize/word_vectors.tsv",corpus_word_vectors[:tb_vocab_size], delimiter='\t') | data_prep/word_vectors.ipynb | bicepjai/Deep-Survey-Text-Classification | mit |
write to checkpoint file | !rm $local_tb_dir/checkpoint
!ls $local_tb_dir
from word2vec import visualize_embeddings_in_tensorboard
visualize_this_embedding = corpus_word_vectors[:tb_vocab_size]
print visualize_this_embedding.shape
# path for gcloud tensorboard
metadata_path = "/home/bicepjai/projects/tb_visual/vocab.tsv"
# metadata_path = "/hom... | data_prep/word_vectors.ipynb | bicepjai/Deep-Survey-Text-Classification | mit |
FastText Vectors
fasttext commands used
fasttext skipgram -minCount 1 -dim 200 -epoch 10 -input corpus_text_for_fast_text.txt -output ft_wvs_200d_10e
fasttext cbow -minCount 1 -dim 200 -epoch 10 -input corpus_text_for_fast_text.txt -output ft_wvs_200d_10e
reading ft vectors | fasttext_vec_file = "processed/stage2/pretrained_word_vectors/ft_sg_200d_10e.vec"
ft_lines = None
with open(fasttext_vec_file,"r") as f:
ft_lines = f.readlines()
print(ft_lines[0])
print(type(ft_lines), len(ft_lines))
ft_shape = tuple([int(i.strip()) for i in ft_lines[0].split()])
ft_shape
print(len(ft_lines[1].... | data_prep/word_vectors.ipynb | bicepjai/Deep-Survey-Text-Classification | mit |
saving all trained fast text vectors | %ll /home/bicepjai/Projects/dsotc/data_prep/processed/stage1/pretrained_word_vectors
len(vocab_words)
%autoreload
import global_utils
ft_vector_files = [
(100,"ft_cbow_100d_20e"),(200,"ft_cbow_200d_20e"),(200,"ft_cbow_300d_20e"),
(100,"ft_sg_100d_20e"),(200,"ft_sg_200d_20e"),(200... | data_prep/word_vectors.ipynb | bicepjai/Deep-Survey-Text-Classification | mit |
Viewing word vectors | %autoreload
import global_utils
WORD_EMB_SIZE=200
ft_file_path = "/home/bicepjai/Projects/Deep-Survey-Text-Classification/data_prep/processed/stage1/pretrained_word_vectors/ft_sg_200d_50e.vec"
trained_embeddings = global_utils.get_embeddings_from_ft(ft_file_path, WORD_EMB_SIZE, corpus_vocab_list)
trained_embeddings.sh... | data_prep/word_vectors.ipynb | bicepjai/Deep-Survey-Text-Classification | mit |
Resampling data
When performing experiments where timing is critical, a signal with a high
sampling rate is desired. However, having a signal with a much higher sampling
rate than is necessary needlessly consumes memory and slows down computations
operating on the data.
This example downsamples from 600 Hz to 100 Hz. T... | # Authors: Marijn van Vliet <w.m.vanvliet@gmail.com>
#
# License: BSD (3-clause)
#
from __future__ import print_function
from matplotlib import pyplot as plt
import mne
from mne.datasets import sample | 0.12/_downloads/plot_resample.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Setting up data paths and loading raw data (skip some data for speed) | data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif'
raw = mne.io.read_raw_fif(raw_fname).crop(120, 240).load_data() | 0.12/_downloads/plot_resample.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Since downsampling reduces the timing precision of events, we recommend
first extracting epochs and downsampling the Epochs object: | events = mne.find_events(raw)
epochs = mne.Epochs(raw, events, event_id=2, tmin=-0.1, tmax=0.8, preload=True)
# Downsample to 100 Hz
print('Original sampling rate:', epochs.info['sfreq'], 'Hz')
epochs_resampled = epochs.copy().resample(100, npad='auto')
print('New sampling rate:', epochs_resampled.info['sfreq'], 'Hz')... | 0.12/_downloads/plot_resample.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
When resampling epochs is unwanted or impossible, for example when the data
doesn't fit into memory or your analysis pipeline doesn't involve epochs at
all, the alternative approach is to resample the continuous data. This
can also be done on non-preloaded data. | # Resample to 300 Hz
raw_resampled = raw.copy().resample(300, npad='auto') | 0.12/_downloads/plot_resample.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Because resampling also affects the stim channels, some trigger onsets might
be lost in this case. While MNE attempts to downsample the stim channels in
an intelligent manner to avoid this, the recommended approach is to find
events on the original data before downsampling. | print('Number of events before resampling:', len(mne.find_events(raw)))
# Resample to 100 Hz (generates warning)
raw_resampled = raw.copy().resample(100, npad='auto')
print('Number of events after resampling:',
len(mne.find_events(raw_resampled)))
# To avoid losing events, jointly resample the data and event ma... | 0.12/_downloads/plot_resample.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
The function above can be used to generate three-dimensional datasets with the shape of a Swiss roll, the letter S, or an helix. These are three examples of datasets which have been extensively used to compare different dimension reduction algorithms. As an illustrative exercise of what dimensionality reduction can do,... | %matplotlib inline
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
%matplotlib inline
def plot(data, embedded_data, colors='m'):
fig = plt.figure()
fig.set_facecolor('white')
ax = fig.add_subplot(121,projection='3d')
ax.scatter(data[0],data[1],data[2],c=colors,cmap=plt.cm.Spectral)
plt.ax... | doc/ipython-notebooks/converter/Tapkee.ipynb | geektoni/shogun | bsd-3-clause |
As it can be seen from the figure above, Isomap has been able to "unroll" the data, reducing its dimension from three to two. At the same time, points with similar colours in the input space are close to points with similar colours in the output space. This is, a new representation of the data has been obtained; this n... | # wrap data into Shogun features
data, colors = generate_data('helix')
features = sg.create_features(data)
# create MDS instance
converter = sg.create_transformer('StochasticProximityEmbedding', target_dim=2)
# embed helix data
embedded_features = converter.transform(features)
embedded_data = embedded_features.get('f... | doc/ipython-notebooks/converter/Tapkee.ipynb | geektoni/shogun | bsd-3-clause |
Writer Pointer
In order to use RAM memory, we must employ memory pointers which are values stored in the FIFO that tell the FIFO where the memory is stored. The write pointer (wptr) is an incremental counter that is increased for each data entry that is added to the memory. Thus the write_pointer is simply a counter wi... | @block
def write_pointer(wr, fifo_full, wptr, fifo_we, clk, rst_n):
"""
Input:
wr(bool):write signal
fifo_full(bool): fifo full signal
clk(bool): clock
rst_n(bool): negtive reset signal
Ouput:
wptr(5bit): the write in memory pointer
fifo_we(bool): the... | myHDL_ComputerFundamentals/Memorys/FirstInFirstOutMemory.ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
myHDL Testing | Peeker.clear()
wr=Signal(bool(0)); Peeker(wr, 'wr')
fifo_full=Signal(bool(0)); Peeker(fifo_full, 'fifo_full')
wptr=Signal(intbv(0)[5:]); Peeker(wptr, 'wptr')
fifo_we=Signal(bool(0)); Peeker(fifo_we, 'fifo_we')
clk=Signal(bool(0)); Peeker(clk, 'clk')
rst_n=Signal(bool(0)); Peeker(rst_n, 'rst_n')
DUT=write_pointer(wr, f... | myHDL_ComputerFundamentals/Memorys/FirstInFirstOutMemory.ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
Verilog Code | DUT.convert()
VerilogTextReader('write_pointer'); | myHDL_ComputerFundamentals/Memorys/FirstInFirstOutMemory.ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
\begin{figure}
\centerline{\includegraphics[width=10cm]{write_pointerRTL.png}}
\caption{\label{fig:WPRTL} write_pointer RTL schematic; Xilinx Vivado 2017.4}
\end{figure}
\begin{figure}
\centerline{\includegraphics[width=10cm]{write_pointerSyn.png}}
\caption{\label{fig:WPSYN} write_pointer Synthesized schematic; Xilinx ... | @block
def write_pointerTBV():
"""
myHDL->Verilog Testbench for `write_pointer module`
"""
wr=Signal(bool(0))
fifo_full=Signal(bool(0))
wptr=Signal(intbv(0)[5:])
fifo_we=Signal(bool(0))
clk=Signal(bool(0))
rst_n=Signal(bool(0))
@always_comb
def print_data():
pri... | myHDL_ComputerFundamentals/Memorys/FirstInFirstOutMemory.ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
Read Pointer
The Read pointer serves the same function as the write_pointer but increments the read pointer that calls up sequentially the memory location to read from.
\begin{figure}
\centerline{\includegraphics[width=10cm]{ReadPointer.png}}
\caption{\label{fig:RP} Read Pointer Functianl Digram }
\end{figure} | @block
def read_pointer(rd, fifo_empty, rptr, fifo_rd, clk, rst_n):
"""
Input:
rd(bool):write signal
fifo_empty(bool): fifo empty signal
clk(bool): clock
rst_n(bool): negtive reset signal
Ouput:
rptr(5bit): the read out memory pointer
fifo_rd(bool): t... | myHDL_ComputerFundamentals/Memorys/FirstInFirstOutMemory.ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
myHDL testing | Peeker.clear()
rd=Signal(bool(0)); Peeker(rd, 'rd')
fifo_empty=Signal(bool(0)); Peeker(fifo_empty, 'fifo_empty')
rptr=Signal(intbv(0)[5:]); Peeker(rptr, 'rptr')
fifo_rd=Signal(bool(0)); Peeker(fifo_rd, 'fifo_rd')
clk=Signal(bool(0)); Peeker(clk, 'clk')
rst_n=Signal(bool(0)); Peeker(rst_n, 'rst_n')
DUT=read_pointer(rd,... | myHDL_ComputerFundamentals/Memorys/FirstInFirstOutMemory.ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
Verilog Code | DUT.convert()
VerilogTextReader('read_pointer'); | myHDL_ComputerFundamentals/Memorys/FirstInFirstOutMemory.ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
\begin{figure}
\centerline{\includegraphics[width=10cm]{read_pointerRTL.png}}
\caption{\label{fig:RPRTL} read_pointer RTL Schematic; Xilinx Vivado 2017.4}
\end{figure}
\begin{figure}
\centerline{\includegraphics[width=10cm]{read_pointerSYN.png}}
\caption{\label{fig:RPRTL} read_pointer Synthesized schematic; Xilinx Viva... | @block
def read_pointerTBV():
"""
myHDL -> Verilog Testbench for `read_pointer` module
"""
rd=Signal(bool(0))
fifo_empty=Signal(bool(0))
rptr=Signal(intbv(0)[5:])
fifo_rd=Signal(bool(0))
clk=Signal(bool(0))
rst_n=Signal(bool(0))
@always_comb
def print_data():
pr... | myHDL_ComputerFundamentals/Memorys/FirstInFirstOutMemory.ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
Memory Array
The memory array is a simple RAM memory that uses the wptr to assign the data_in location in the RAM and the rptr to pull the memory to output to data_out
\begin{figure}
\centerline{\includegraphics[width=10cm]{Memory_array.png}}
\caption{\label{fig:WP} Memory Array Functional Diagram}
\end{figure} | @block
def memory_array(data_in, fifo_we, wptr, rptr, data_out, clk, clear):
"""
Input:
data_in(8bit): data to be writen
fifo_we(bool): write enable
wptr(5bit): write memory address pointer
rptr(5bit): read memory address pointer
clk(bool): clock
clear(bool): sig... | myHDL_ComputerFundamentals/Memorys/FirstInFirstOutMemory.ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
myHDL Testing | Peeker.clear()
data_in=Signal(intbv(0)[8:]); Peeker(data_in, 'data_in')
fifo_we=Signal(bool(0)); Peeker(fifo_we, 'fifo_we')
wptr=Signal(intbv(0)[5:]); Peeker(wptr, 'wptr')
rptr=Signal(intbv(0)[5:]); Peeker(rptr, 'rptr')
data_out=Signal(intbv(0)[8:]); Peeker(data_out, 'data_out')
clk=Signal(bool(0)); Peeker(clk, 'clk'... | myHDL_ComputerFundamentals/Memorys/FirstInFirstOutMemory.ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
Verilog Code | DUT.convert()
VerilogTextReader('memory_array'); | myHDL_ComputerFundamentals/Memorys/FirstInFirstOutMemory.ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
\begin{figure}
\centerline{\includegraphics[width=10cm]{memory_arrayRTL.png}}
\caption{\label{fig:MARTL} memory_array RTL Schematic; Xilinx Vivado 2017.4}
\end{figure}
\begin{figure}
\centerline{\includegraphics[width=10cm]{memory_arraySYN.png}}
\caption{\label{fig:MASYN} memory_array Synthesized schematic; Xilinx Viva... | @block
def memory_arrayTBV():
"""
myHDL -> verilog testbench for `memory_array` module
"""
data_in=Signal(intbv(0)[8:])
fifo_we=Signal(bool(0))
wptr=Signal(intbv(0)[5:])
rptr=Signal(intbv(0)[5:])
data_out=Signal(intbv(0)[8:])
clk=Signal(bool(0))
clear=Signal(bool(0))
Tes... | myHDL_ComputerFundamentals/Memorys/FirstInFirstOutMemory.ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
Status Signal
The status signal module is a internal check module that checks for impending overflow, overflow, and underflow of the FIFO memory
\begin{figure}
\centerline{\includegraphics[width=10cm]{fifoStatus.png}}
\caption{\label{fig:WP} fifoStatus Functional Diagram}
\end{figure} | @block
def fifoStatus(wr, rd, fifo_we, fifo_rd, wptr, rptr,
fifo_full, fifo_empty, fifo_threshold, fifo_overflow, fifo_underflow,
clk, rst_n):
"""
Input:
wr(bool): write signal
rd(bool): read signal
fifo_we(bool): write enable signal
fifo_rd(b... | myHDL_ComputerFundamentals/Memorys/FirstInFirstOutMemory.ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
myHDL Testing | Peeker.clear()
wr=Signal(bool(0)); Peeker(wr, 'wr')
rd=Signal(bool(0)); Peeker(rd, 'rd')
fifo_we=Signal(bool(0)); Peeker(fifo_we, 'fifo_we')
fifo_rd=Signal(bool(0)); Peeker(fifo_rd, 'fifo_rd')
wptr=Signal(intbv(0)[5:]); Peeker(wptr, 'wptr')
rptr=Signal(intbv(0)[5:]); Peeker(rptr, 'rptr')
fifo_full=Signal(bool(0)); Pe... | myHDL_ComputerFundamentals/Memorys/FirstInFirstOutMemory.ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
Verilog Code | DUT.convert()
VerilogTextReader('fifoStatus'); | myHDL_ComputerFundamentals/Memorys/FirstInFirstOutMemory.ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
\begin{figure}
\centerline{\includegraphics[width=10cm]{fifoStatusRTL.png}}
\caption{\label{fig:FIFOStatusRTL} fifoStatus RTL Schematic; Xilinx Vivado 2017.4}
\end{figure}
\begin{figure}
\centerline{\includegraphics[width=10cm]{fifoStatusSYN.png}}
\caption{\label{fig:MASYN} fifoStatus Synthesized Schematic; Xilinx Viva... | @block
def fifoStatusTBV():
"""
myHDL -> verilog test bench for `fifoStatus` module
Note:
Not a complet testbench, could be better
"""
wr=Signal(bool(0)); Peeker(wr, 'wr')
rd=Signal(bool(0)); Peeker(rd, 'rd')
fifo_we=Signal(bool(0)); Peeker(fifo_we, 'fifo_we')
fifo_rd=Signa... | myHDL_ComputerFundamentals/Memorys/FirstInFirstOutMemory.ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
FIFO
\begin{figure}
\centerline{\includegraphics[width=10cm]{FIFO.png}}
\caption{\label{fig:WP} FIFO Functional Diagram}
\end{figure} | @block
def fifo_mem(wr, rd, data_in,
fifo_full, fifo_empty, fifo_threshold, fifo_overflow, fifo_underflow,
data_out, clk, rst_n, clear):
"""
Input:
wr(bool):write signal
rd(bool):write signal
data_in(8bit): data to be writen
clk(bool): clock
rst... | myHDL_ComputerFundamentals/Memorys/FirstInFirstOutMemory.ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
myHDL Testing | Peeker.clear()
wr=Signal(bool(0)); Peeker(wr, 'wr')
rd=Signal(bool(0)); Peeker(rd, 'rd')
data_in=Signal(intbv(0)[8:]); Peeker(data_in, 'data_in')
fifo_full=Signal(bool(0)); Peeker(fifo_full, 'fifo_full')
fifo_empty=Signal(bool(0)); Peeker(fifo_empty, 'fifo_empty')
fifo_threshold=Signal(bool(0)); Peeker(fifo_threshol... | myHDL_ComputerFundamentals/Memorys/FirstInFirstOutMemory.ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
Verilog Code | DUT.convert()
VerilogTextReader('fifo_mem'); | myHDL_ComputerFundamentals/Memorys/FirstInFirstOutMemory.ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
\begin{figure}
\centerline{\includegraphics[width=10cm]{fifo_memRTL.png}}
\caption{\label{fig:FIFORTL} fifo_mem RTL Schematic; Xilinx Vivado 2017.4}
\end{figure}
\begin{figure}
\centerline{\includegraphics[width=10cm]{fifo_memSYN.png}}
\caption{\label{fig:fifo_memSYN} fifo_mem Synthesized schematic; Xilinx Vivado 2017.... | @block
def fifo_memTBV():
"""
myHDL ->Verilog test bench for `fifo_mem` module
Note:
Not a complet testbench, could be better
"""
wr=Signal(bool(0))
rd=Signal(bool(0))
data_in=Signal(intbv(0)[8:])
TestData_i=[Signal(intbv(int(i))[8:]) for i in TestData]
fifo_full=Sig... | myHDL_ComputerFundamentals/Memorys/FirstInFirstOutMemory.ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
Example: bitcoin
Here we read in the bitcoin exchange rate data and plot it. We take only the most recent data because the version of python IEtools used here could only look at two shocks. | filename='C:/econdata/btcUSDtimeseries_recent.xls'
book = xlrd.open_workbook(filename)
sheet = book.sheet_by_index(0)
outputList = []
outputName = 'USD/btc'
for rowIndex in range(sheet.nrows):
outputList.append([sheet.cell(rowIndex,0).value, sheet.cell(rowIndex,1).value])
dataOutput = np.array(outputList)
output... | Dynamic Equilibrium Example-Bitcoin.ipynb | infotranecon/IEtools | mit |
Dynamic equilibrium model
This applies the entropy minimization method of finding the dynamic equilibrium. | forecastDuration = 0.25
forecastResolution = 100
forecastTime = np.array(list(range(int(output['data'][-1,0]*forecastResolution),int((output['data'][-1,0]+forecastDuration)*forecastResolution),1)))/forecastResolution
temp = dynamic_equilibrium_optimize(output['data'],alphaRange=(-2.9,-2.4),binWidth=0.5,alphaDelta=0.00... | Dynamic Equilibrium Example-Bitcoin.ipynb | infotranecon/IEtools | mit |
After doing a pip install, restart your kernel by selecting kernel from the menu and clicking Restart Kernel before proceeding further | import tensorflow as tf
import apache_beam as beam
import shutil
print(tf.__version__) | courses/machine_learning/feateng/feateng.ipynb | turbomanage/training-data-analyst | apache-2.0 |
<h2> 1. Environment variables for project and bucket </h2>
<li> Your project id is the *unique* string that identifies your project (not the project name). You can find this from the GCP Console dashboard's Home page. My dashboard reads: <b>Project ID:</b> cloud-training-demos </li>
<li> Cloud training often involve... | import os
PROJECT = 'cloud-training-demos' # CHANGE THIS
BUCKET = 'cloud-training-demos' # REPLACE WITH YOUR BUCKET NAME. Use a regional bucket in the region you selected.
REGION = 'us-central1' # Choose an available region for Cloud AI Platform
# for bash
os.environ['PROJECT'] = PROJECT
os.environ['BUCKET'] = BUCK... | courses/machine_learning/feateng/feateng.ipynb | turbomanage/training-data-analyst | apache-2.0 |
<h2> 2. Specifying query to pull the data </h2>
Let's pull out a few extra columns from the timestamp. | def create_query(phase, EVERY_N):
if EVERY_N == None:
EVERY_N = 4 #use full dataset
#select and pre-process fields
base_query = """
SELECT
(tolls_amount + fare_amount) AS fare_amount,
DAYOFWEEK(pickup_datetime) AS dayofweek,
HOUR(pickup_datetime) AS hourofday,
pickup_longitude AS pickuplon,
pic... | courses/machine_learning/feateng/feateng.ipynb | turbomanage/training-data-analyst | apache-2.0 |
First, let's define a function for preprocessing the data | import datetime
####
# Arguments:
# -rowdict: Dictionary. The beam bigquery reader returns a PCollection in
# which each row is represented as a python dictionary
# Returns:
# -rowstring: a comma separated string representation of the record with dayofweek
# converted from int to string (e.g. 3 --> Tue)
##... | courses/machine_learning/feateng/feateng.ipynb | turbomanage/training-data-analyst | apache-2.0 |
The following step will take <b>15-20 minutes.</b> Monitor job progress on the Cloud Console, in the Dataflow section | preprocess(50*100, 'DataflowRunner')
| courses/machine_learning/feateng/feateng.ipynb | turbomanage/training-data-analyst | apache-2.0 |
6. Train on cloud
This will take <b> 10-15 minutes </b> even though the prompt immediately returns after the job is submitted. Monitor job progress on the Cloud Console, in the AI Platform section and wait for the training job to complete. | %%bash
OUTDIR=gs://${BUCKET}/taxifare/ch4/taxi_trained
JOBNAME=lab4a_$(date -u +%y%m%d_%H%M%S)
echo $OUTDIR $REGION $JOBNAME
gsutil -m rm -rf $OUTDIR
gcloud ai-platform jobs submit training $JOBNAME \
--region=$REGION \
--module-name=trainer.task \
--package-path=${PWD}/taxifare/trainer \
--job-dir=$OUTDIR \
... | courses/machine_learning/feateng/feateng.ipynb | turbomanage/training-data-analyst | apache-2.0 |
The RMSE is now 8.33249, an improvement over the 9.3 that we were getting ... of course, we won't know until we train/validate on a larger dataset. Still, this is promising. But before we do that, let's do hyper-parameter tuning.
<b>Use the Cloud Console link to monitor the job and do NOT proceed until the job is done.... | %%bash
gsutil ls gs://${BUCKET}/taxifare/ch4/taxi_trained/export/exporter | tail -1
%%bash
model_dir=$(gsutil ls gs://${BUCKET}/taxifare/ch4/taxi_trained/export/exporter | tail -1)
saved_model_cli show --dir ${model_dir} --all
%%bash
model_dir=$(gsutil ls gs://${BUCKET}/taxifare/ch4/taxi_trained/export/exporter | tai... | courses/machine_learning/feateng/feateng.ipynb | turbomanage/training-data-analyst | apache-2.0 |
Optional: deploy model to cloud | %%bash
MODEL_NAME="feateng"
MODEL_VERSION="v1"
MODEL_LOCATION=$(gsutil ls gs://${BUCKET}/taxifare/ch4/taxi_trained/export/exporter | tail -1)
echo "Run these commands one-by-one (the very first time, you'll create a model and then create a version)"
#gcloud ai-platform versions delete ${MODEL_VERSION} --model ${MODEL_N... | courses/machine_learning/feateng/feateng.ipynb | turbomanage/training-data-analyst | apache-2.0 |
...and you want to filter it on some criteria. Pandas makes that easy with Boolean Indexing | criteria = df['Number']>300
criteria
#Keep only rows which correspond to 'Number'>300 ('True' in the 'criteria' vector above)
df[criteria] | jupyter_notebooks/Pandas_View_vs_Copy.ipynb | MaxPowerWasTaken/MaxPowerWasTaken.github.io | gpl-3.0 |
This works great right? Unfortunately not, because once we:
1. Use that filtering code to create a new Pandas DataFrame, and
2. Assign a new column or change an existing column in that DataFrame
like so... | #Create a new DataFrame based on filtering criteria
df_2 = df[criteria]
#Assign a new column and print output
df_2['new column'] = 'new value'
df_2 | jupyter_notebooks/Pandas_View_vs_Copy.ipynb | MaxPowerWasTaken/MaxPowerWasTaken.github.io | gpl-3.0 |
There's the warning.
So what should we have done differently? The warning suggests using ".loc[row_indexer, col_indexer]". So let's try subsetting the DataFrame the same way as before, but this time using the df.loc[ ] method.
Re-Creating Our New Dataframe Using .loc[] | df.loc[criteria, :]
#Create New DataFrame Based on Filtering Criteria
df_2 = df.loc[criteria, :]
#Add a New Column to the DataFrame
df_2.loc[:, 'new column'] = 'new value'
df_2 | jupyter_notebooks/Pandas_View_vs_Copy.ipynb | MaxPowerWasTaken/MaxPowerWasTaken.github.io | gpl-3.0 |
Two warnings this time!
OK, So What's Going On?
Recall that our "criteria" variable is a Pandas Series of Boolean True/False values, corresponding to whether a row of 'df' meets our Number>300 criteria. | criteria | jupyter_notebooks/Pandas_View_vs_Copy.ipynb | MaxPowerWasTaken/MaxPowerWasTaken.github.io | gpl-3.0 |
The Pandas Docs say a "common operation is the use of boolean vectors to filter the data" as we've done here. But apparently a boolean vector is not the "row_indexer" the warning advises us to use with .loc[] for creating new dataframes. Instead, Pandas wants us to use .loc[] with a vector of row-numbers (technically, ... | df_2 = df[criteria] | jupyter_notebooks/Pandas_View_vs_Copy.ipynb | MaxPowerWasTaken/MaxPowerWasTaken.github.io | gpl-3.0 |
We first grab the indices of that filtered dataframe using .index... | criteria_row_indices = df[criteria].index
criteria_row_indices | jupyter_notebooks/Pandas_View_vs_Copy.ipynb | MaxPowerWasTaken/MaxPowerWasTaken.github.io | gpl-3.0 |
And pass that list of indices to .loc[ ] to create our new dataframe | new_df = df.loc[criteria_row_indices, :]
new_df | jupyter_notebooks/Pandas_View_vs_Copy.ipynb | MaxPowerWasTaken/MaxPowerWasTaken.github.io | gpl-3.0 |
Now we can add a new column without throwing The Warning <sup>(tm)</sup> | new_df['New Column'] = 'New Value'
new_df | jupyter_notebooks/Pandas_View_vs_Copy.ipynb | MaxPowerWasTaken/MaxPowerWasTaken.github.io | gpl-3.0 |
Sparse weights using structural pruning
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/model_optimization/guide/pruning/pruning_with_sparsity_2_by_4"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a>
</td>
<td... | ! pip install -q tensorflow
! pip install -q tensorflow-model-optimization
! pip install -q matplotlib
import tensorflow as tf
from tensorflow import keras
import tensorflow_model_optimization as tfmot
prune_low_magnitude = tfmot.sparsity.keras.prune_low_magnitude | site/en-snapshot/model_optimization/guide/pruning/pruning_with_sparsity_2_by_4.ipynb | tensorflow/docs-l10n | apache-2.0 |
Download and normalize image data from the MNIST dataset | # Load MNIST dataset.
mnist = keras.datasets.mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
# Normalize the input image so that each pixel value is between 0 and 1.
train_images = train_images / 255.0
test_images = test_images / 255.0 | site/en-snapshot/model_optimization/guide/pruning/pruning_with_sparsity_2_by_4.ipynb | tensorflow/docs-l10n | apache-2.0 |
Define structural pruning parameters
Define parameters for pruning and specify the type of structural pruning. Set the parameters for pruning to (2, 4).
These settings mean that in a block of four elements, at least two with the lowest magnitude are set to zero.
You don't have to set the pruning_schedule parameter. By ... | pruning_params_2_by_4 = {
'sparsity_m_by_n': (2, 4),
} | site/en-snapshot/model_optimization/guide/pruning/pruning_with_sparsity_2_by_4.ipynb | tensorflow/docs-l10n | apache-2.0 |
Define parameters for random pruning with the target sparsity of 50%. | pruning_params_sparsity_0_5 = {
'pruning_schedule': tfmot.sparsity.keras.ConstantSparsity(target_sparsity=0.5,
begin_step=0,
frequency=100)
} | site/en-snapshot/model_optimization/guide/pruning/pruning_with_sparsity_2_by_4.ipynb | tensorflow/docs-l10n | apache-2.0 |
Define the model architecture and specify which layers to prune. Structural pruning is applied based on the layers of the model you select.
In the example below, we prune only some of the layers. We prune the second Conv2D layer and the first Dense layer.
Notice that the first Conv2D layer cannot be pruned structurally... | model = keras.Sequential([
prune_low_magnitude(
keras.layers.Conv2D(
32, 5, padding='same', activation='relu',
input_shape=(28, 28, 1),
name="pruning_sparsity_0_5"),
**pruning_params_sparsity_0_5),
keras.layers.MaxPooling2D((2, 2), (2, 2), padding='same'),
... | site/en-snapshot/model_optimization/guide/pruning/pruning_with_sparsity_2_by_4.ipynb | tensorflow/docs-l10n | apache-2.0 |
Train and evaluate the model. | batch_size = 128
epochs = 2
model.fit(
train_images,
train_labels,
batch_size=batch_size,
epochs=epochs,
verbose=0,
callbacks=tfmot.sparsity.keras.UpdatePruningStep(),
validation_split=0.1)
_, pruned_model_accuracy = model.evaluate(test_images, test_labels, verbose=0)
print('Pruned test ac... | site/en-snapshot/model_optimization/guide/pruning/pruning_with_sparsity_2_by_4.ipynb | tensorflow/docs-l10n | apache-2.0 |
Remove the pruning wrapper so that it is not included in the model when you convert it to TensorFlow Lite format. | model = tfmot.sparsity.keras.strip_pruning(model) | site/en-snapshot/model_optimization/guide/pruning/pruning_with_sparsity_2_by_4.ipynb | tensorflow/docs-l10n | apache-2.0 |
Convert model to tflite format | import tempfile
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
_, tflite_file = tempfile.mkstemp('.tflite')
print('Saved converted pruned model to:', tflite_file)
with open(tflite_file, 'wb') as f:
f.write(tflite_model) | site/en-snapshot/model_optimization/guide/pruning/pruning_with_sparsity_2_by_4.ipynb | tensorflow/docs-l10n | apache-2.0 |
Visualize and check weights
Now visualize the structure of weights in the Dense layer pruned with 2 by 4 sparsity. Extract the weights from the tflite file. | # Load tflite file with the created pruned model
interpreter = tf.lite.Interpreter(model_path=tflite_file)
interpreter.allocate_tensors()
details = interpreter.get_tensor_details()
# Weights of the dense layer that has been pruned.
tensor_name = 'structural_pruning_dense/MatMul'
detail = [x for x in details if tensor... | site/en-snapshot/model_optimization/guide/pruning/pruning_with_sparsity_2_by_4.ipynb | tensorflow/docs-l10n | apache-2.0 |
To verify that we selected the correct layer that has been pruned, print the shape of the weight tensor. | print(f"Shape of Dense layer is {tensor_data.shape}") | site/en-snapshot/model_optimization/guide/pruning/pruning_with_sparsity_2_by_4.ipynb | tensorflow/docs-l10n | apache-2.0 |
Now we visualize the structure for a small subset of the weight tensor. The structure of the weight tensor is sparse in the last dimension, using the (2,4) pattern: two elements out of four are zeros. To make the visualization more clear, we replace all non-zero values with ones. | import matplotlib.pyplot as plt
import numpy as np
# The value 24 is chosen for convenience.
width = height = 24
subset_values_to_display = tensor_data[0:height, 0:width]
val_ones = np.ones([height, width])
val_zeros = np.zeros([height, width])
subset_values_to_display = np.where(abs(subset_values_to_display) > 0, v... | site/en-snapshot/model_optimization/guide/pruning/pruning_with_sparsity_2_by_4.ipynb | tensorflow/docs-l10n | apache-2.0 |
Define the auxiliary function to draw separation lines to see the structure clearly. | def plot_separation_lines(height, width):
block_size = [1, 4]
# Add separation lines to the figure.
num_hlines = int((height - 1) / block_size[0])
num_vlines = int((width - 1) / block_size[1])
line_y_pos = [y * block_size[0] for y in range(1, num_hlines + 1)]
line_x_pos = [x * block_size[1] fo... | site/en-snapshot/model_optimization/guide/pruning/pruning_with_sparsity_2_by_4.ipynb | tensorflow/docs-l10n | apache-2.0 |
Now visualize the subset of the weight tensor. | plot_separation_lines(height, width)
plt.axis('off')
plt.imshow(subset_values_to_display)
plt.colorbar()
plt.title("Structural pruning for Dense layer")
plt.show() | site/en-snapshot/model_optimization/guide/pruning/pruning_with_sparsity_2_by_4.ipynb | tensorflow/docs-l10n | apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.