markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
Let's view the data, plots and HTML we produced | show_html('data/throughput.html')
display(select_to_dataframe('select * from data')) | _____no_output_____ | MIT | setbench/setbench/microbench_experiments/tutorial/tutorial.ipynb | cmuparlay/flock |
Plots and HTML for data with 7+ dimensionsif we had MORE than one extra dimension of data (7+ dimensions in total), we could list additional fields in the keyword argument `page_field_list`, which would cause additional HTML pages to be rendered (one for each combination of values for fields in `page_field_list`), and... | def define_experiment(exp_dict, args):
set_dir_tools (exp_dict, os.getcwd() + '/../../tools') ## path to tools library
set_dir_compile (exp_dict, os.getcwd() + '/../../microbench')
set_dir_run (exp_dict, os.getcwd() + '/../../microbench/bin')
set_cmd_compile (exp_dict, 'make bin_dir={__dir_run... | _____no_output_____ | MIT | setbench/setbench/microbench_experiments/tutorial/tutorial.ipynb | cmuparlay/flock |
Let's view the data, plots and HTML we produced | show_html('data/index.html')
display(select_to_dataframe('select * from data')) | _____no_output_____ | MIT | setbench/setbench/microbench_experiments/tutorial/tutorial.ipynb | cmuparlay/flock |
It's easy to plot *many* value fields vs your `run_params`Let's go back to our 5-dimensional data example to demonstrate how to easily produce plots from *many different value fields* (not just `total_throughput`). First let's run a quick shell command to check what kinds of fields exist in our data(This command uses ... | shell_to_list('grep -E "^[^ =]+=[0-9.]+$" data/data000001.txt', sep='\n') | _____no_output_____ | MIT | setbench/setbench/microbench_experiments/tutorial/tutorial.ipynb | cmuparlay/flock |
Let's focus on the following fields from that list:- `tree_stats_numNodes`- `tree_stats_height`- `tree_stats_avgKeyDepth`- `global_epoch_counter`- `PAPI_L2_TCM`- `PAPI_L3_TCM`- `PAPI_TOT_CYC`- `PAPI_TOT_INS`- `total_throughput` | def define_experiment(exp_dict, args):
set_dir_tools (exp_dict, os.getcwd() + '/../../tools')
set_dir_compile (exp_dict, os.getcwd() + '/../../microbench')
set_dir_run (exp_dict, os.getcwd() + '/../../microbench/bin')
set_cmd_compile (exp_dict, 'make -j6')
add_run_param (exp_dict, '__t... | _____no_output_____ | MIT | setbench/setbench/microbench_experiments/tutorial/tutorial.ipynb | cmuparlay/flock |
Viewing the results | import sys ; sys.path.append('../../tools/data_framework') ; from run_experiment import *
show_html('data/index.html') | _____no_output_____ | MIT | setbench/setbench/microbench_experiments/tutorial/tutorial.ipynb | cmuparlay/flock |
Rendering *many data fields* on a *single* HTML pagein the previous example, we build one page for each data field extracted. however, you might want, for example, to build a single page with many data fields, each appearing as a *row* of plots.if you take a moment to think about *how* you would accomplish this using ... | def define_experiment(exp_dict, args):
set_dir_tools (exp_dict, os.getcwd() + '/../../tools')
set_dir_compile (exp_dict, os.getcwd() + '/../../microbench')
set_dir_run (exp_dict, os.getcwd() + '/../../microbench/bin')
set_cmd_compile (exp_dict, 'make -j6')
add_run_param (exp_dict, '__t... | _____no_output_____ | MIT | setbench/setbench/microbench_experiments/tutorial/tutorial.ipynb | cmuparlay/flock |
Viewing the results | import sys ; sys.path.append('../../tools/data_framework') ; from run_experiment import *
show_html('data/index.html') | _____no_output_____ | MIT | setbench/setbench/microbench_experiments/tutorial/tutorial.ipynb | cmuparlay/flock |
Separating `tables` into different `pages`if you prefer, you can eliminate the `table_field` argument to `add_page_set` and instead use `page_field_list`. this produces a slightly different effect. | def define_experiment(exp_dict, args):
set_dir_tools (exp_dict, os.getcwd() + '/../../tools')
set_dir_compile (exp_dict, os.getcwd() + '/../../microbench')
set_dir_run (exp_dict, os.getcwd() + '/../../microbench/bin')
set_cmd_compile (exp_dict, 'make -j6')
add_run_param (exp_dict, '__t... | _____no_output_____ | MIT | setbench/setbench/microbench_experiments/tutorial/tutorial.ipynb | cmuparlay/flock |
Viewing the results | import sys ; sys.path.append('../../tools/data_framework') ; from run_experiment import *
show_html('data/index.html') | _____no_output_____ | MIT | setbench/setbench/microbench_experiments/tutorial/tutorial.ipynb | cmuparlay/flock |
Defining a `--testing` mode Briefly running each configuration *BEFORE* doing a full runi often find it useful to have a `testing` mode (enabled with argument `--testing`), that runs for less time, but still explores all (important) configurations of run parameters, to make sure nothing simple will fail when i run for... | def define_experiment(exp_dict, args):
set_dir_tools (exp_dict, os.getcwd() + '/../../tools')
set_dir_compile (exp_dict, os.getcwd() + '/../../microbench')
set_dir_run (exp_dict, os.getcwd() + '/../../microbench/bin')
set_cmd_compile (exp_dict, 'make -j6')
add_run_param (exp_dict, '__t... | _____no_output_____ | MIT | setbench/setbench/microbench_experiments/tutorial/tutorial.ipynb | cmuparlay/flock |
Viewing the `--testing` mode results | import sys ; sys.path.append('../../tools/data_framework') ; from run_experiment import *
show_html('data/index.html') | _____no_output_____ | MIT | setbench/setbench/microbench_experiments/tutorial/tutorial.ipynb | cmuparlay/flock |
Custom output filename patternsin the experiments above, we have always used the default filename for output files: `dataXXXXXX.txt`.if you want a different file naming scheme, it's easy to specify a pattern for this using `set_file_data(exp_dict, pattern)`.let's see an example of this, where we include the current va... | def define_experiment(exp_dict, args):
set_dir_tools (exp_dict, os.getcwd() + '/../../tools')
set_dir_compile (exp_dict, os.getcwd() + '/../../microbench')
set_dir_run (exp_dict, os.getcwd() + '/../../microbench/bin')
set_cmd_compile (exp_dict, 'make -j6')
add_run_param (exp_dict, '__t... | _____no_output_____ | MIT | setbench/setbench/microbench_experiments/tutorial/tutorial.ipynb | cmuparlay/flock |
Automatic best-effort sanity checksthe data framework does its best to identify some basic mistakes that are common when running repeated experiments over a large configuration space. we describe some of them here, and show how they work.for example, observe that the following `define_experiment` function attempts to ... | def define_experiment(exp_dict, args):
set_dir_tools (exp_dict, os.getcwd() + '/../../tools')
set_dir_compile (exp_dict, os.getcwd() + '/../../microbench')
set_dir_run (exp_dict, os.getcwd() + '/../../microbench/bin')
set_cmd_compile (exp_dict, 'make -j6')
add_run_param (exp_dict, '__t... | _____no_output_____ | MIT | setbench/setbench/microbench_experiments/tutorial/tutorial.ipynb | cmuparlay/flock |
Automatic archival features (data zip, git commit hash fetch, git diff file archive)activated with command line arg: `-z` (which stands for `zip creation`)the data framework offers a powerful convenience for archiving your experiments: it can automatically ZIP *as little data as is needed* to guarantee you won't lose ... | def define_experiment(exp_dict, args):
set_dir_tools (exp_dict, os.getcwd() + '/../../tools')
set_dir_compile (exp_dict, os.getcwd() + '/../../microbench')
set_dir_run (exp_dict, os.getcwd() + '/../../microbench/bin')
set_cmd_compile (exp_dict, 'make -j6')
add_run_param (exp_dict, '__t... | _____no_output_____ | MIT | setbench/setbench/microbench_experiments/tutorial/tutorial.ipynb | cmuparlay/flock |
Copyright 2019 Google LLC | #@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under... | _____no_output_____ | Apache-2.0 | site/en-snapshot/neural_structured_learning/tutorials/graph_keras_lstm_imdb.ipynb | ilyaspiridonov/docs-l10n |
Graph regularization for sentiment classification using synthesized graphs View on TensorFlow.org Run in Google Colab View source on GitHub Overview This notebook classifies movie reviews as *positive* or *negative* using thetext of the review. This is an example of *binary* classification, an im... | !pip install --quiet neural-structured-learning
!pip install --quiet tensorflow-hub | _____no_output_____ | Apache-2.0 | site/en-snapshot/neural_structured_learning/tutorials/graph_keras_lstm_imdb.ipynb | ilyaspiridonov/docs-l10n |
Dependencies and imports | import matplotlib.pyplot as plt
import numpy as np
import neural_structured_learning as nsl
import tensorflow as tf
import tensorflow_hub as hub
# Resets notebook state
tf.keras.backend.clear_session()
print("Version: ", tf.__version__)
print("Eager mode: ", tf.executing_eagerly())
print("Hub version: ", hub.__vers... | _____no_output_____ | Apache-2.0 | site/en-snapshot/neural_structured_learning/tutorials/graph_keras_lstm_imdb.ipynb | ilyaspiridonov/docs-l10n |
IMDB datasetThe[IMDB dataset](https://www.tensorflow.org/api_docs/python/tf/keras/datasets/imdb)contains the text of 50,000 movie reviews from the[Internet Movie Database](https://www.imdb.com/). These are split into 25,000reviews for training and 25,000 reviews for testing. The training and testingsets are *balanced*... | imdb = tf.keras.datasets.imdb
(pp_train_data, pp_train_labels), (pp_test_data, pp_test_labels) = (
imdb.load_data(num_words=10000)) | _____no_output_____ | Apache-2.0 | site/en-snapshot/neural_structured_learning/tutorials/graph_keras_lstm_imdb.ipynb | ilyaspiridonov/docs-l10n |
The argument `num_words=10000` keeps the top 10,000 most frequently occurring words in the training data. The rare words are discarded to keep the size of the vocabulary manageable. Explore the dataLet's take a moment to understand the format of the data. The dataset comes preprocessed: each example is an array of int... | print('Training entries: {}, labels: {}'.format(
len(pp_train_data), len(pp_train_labels)))
training_samples_count = len(pp_train_data) | _____no_output_____ | Apache-2.0 | site/en-snapshot/neural_structured_learning/tutorials/graph_keras_lstm_imdb.ipynb | ilyaspiridonov/docs-l10n |
The text of reviews have been converted to integers, where each integer represents a specific word in a dictionary. Here's what the first review looks like: | print(pp_train_data[0]) | _____no_output_____ | Apache-2.0 | site/en-snapshot/neural_structured_learning/tutorials/graph_keras_lstm_imdb.ipynb | ilyaspiridonov/docs-l10n |
Movie reviews may be different lengths. The below code shows the number of words in the first and second reviews. Since inputs to a neural network must be the same length, we'll need to resolve this later. | len(pp_train_data[0]), len(pp_train_data[1]) | _____no_output_____ | Apache-2.0 | site/en-snapshot/neural_structured_learning/tutorials/graph_keras_lstm_imdb.ipynb | ilyaspiridonov/docs-l10n |
Convert the integers back to wordsIt may be useful to know how to convert integers back to the corresponding text.Here, we'll create a helper function to query a dictionary object that containsthe integer to string mapping: | def build_reverse_word_index():
# A dictionary mapping words to an integer index
word_index = imdb.get_word_index()
# The first indices are reserved
word_index = {k: (v + 3) for k, v in word_index.items()}
word_index['<PAD>'] = 0
word_index['<START>'] = 1
word_index['<UNK>'] = 2 # unknown
word_index['... | _____no_output_____ | Apache-2.0 | site/en-snapshot/neural_structured_learning/tutorials/graph_keras_lstm_imdb.ipynb | ilyaspiridonov/docs-l10n |
Now we can use the `decode_review` function to display the text for the first review: | decode_review(pp_train_data[0]) | _____no_output_____ | Apache-2.0 | site/en-snapshot/neural_structured_learning/tutorials/graph_keras_lstm_imdb.ipynb | ilyaspiridonov/docs-l10n |
Graph constructionGraph construction involves creating embeddings for text samples and then usinga similarity function to compare the embeddings.Before proceeding further, we first create a directory to store artifactscreated by this tutorial. | !mkdir -p /tmp/imdb | _____no_output_____ | Apache-2.0 | site/en-snapshot/neural_structured_learning/tutorials/graph_keras_lstm_imdb.ipynb | ilyaspiridonov/docs-l10n |
Create sample embeddings We will use pretrained Swivel embeddings to create embeddings in the`tf.train.Example` format for each sample in the input. We will store theresulting embeddings in the `TFRecord` format along with an additional featurethat represents the ID of each sample. This is important and will allow us ... | pretrained_embedding = 'https://tfhub.dev/google/tf2-preview/gnews-swivel-20dim/1'
hub_layer = hub.KerasLayer(
pretrained_embedding, input_shape=[], dtype=tf.string, trainable=True)
def _int64_feature(value):
"""Returns int64 tf.train.Feature."""
return tf.train.Feature(int64_list=tf.train.Int64List(value=valu... | _____no_output_____ | Apache-2.0 | site/en-snapshot/neural_structured_learning/tutorials/graph_keras_lstm_imdb.ipynb | ilyaspiridonov/docs-l10n |
Build a graphNow that we have the sample embeddings, we will use them to build a similaritygraph, i.e, nodes in this graph will correspond to samples and edges in thisgraph will correspond to similarity between pairs of nodes.Neural Structured Learning provides a graph building library to build a graphbased on sample ... | nsl.tools.build_graph(['/tmp/imdb/embeddings.tfr'],
'/tmp/imdb/graph_99.tsv',
similarity_threshold=0.99) | _____no_output_____ | Apache-2.0 | site/en-snapshot/neural_structured_learning/tutorials/graph_keras_lstm_imdb.ipynb | ilyaspiridonov/docs-l10n |
**Note:** Graph quality and by extension, embedding quality, are very importantfor graph regularization. While we have used Swivel embeddings in this notebook,using BERT embeddings for instance, will likely capture review semantics moreaccurately. We encourage users to use embeddings of their choice and asappropriate t... | def create_example(word_vector, label, record_id):
"""Create tf.Example containing the sample's word vector, label, and ID."""
features = {
'id': _bytes_feature(str(record_id)),
'words': _int64_feature(np.asarray(word_vector)),
'label': _int64_feature(np.asarray([label])),
}
return tf.train.Ex... | _____no_output_____ | Apache-2.0 | site/en-snapshot/neural_structured_learning/tutorials/graph_keras_lstm_imdb.ipynb | ilyaspiridonov/docs-l10n |
Augment training data with graph neighborsSince we have the sample features and the synthesized graph, we can generate theaugmented training data for Neural Structured Learning. The NSL frameworkprovides a library to combine the graph and the sample features to producethe final training data for graph regularization. ... | nsl.tools.pack_nbrs(
'/tmp/imdb/train_data.tfr',
'',
'/tmp/imdb/graph_99.tsv',
'/tmp/imdb/nsl_train_data.tfr',
add_undirected_edges=True,
max_nbrs=3) | _____no_output_____ | Apache-2.0 | site/en-snapshot/neural_structured_learning/tutorials/graph_keras_lstm_imdb.ipynb | ilyaspiridonov/docs-l10n |
Base modelWe are now ready to build a base model without graph regularization. In order tobuild this model, we can either use embeddings that were used in building thegraph, or we can learn new embeddings jointly along with the classificationtask. For the purpose of this notebook, we will do the latter. Global variab... | NBR_FEATURE_PREFIX = 'NL_nbr_'
NBR_WEIGHT_SUFFIX = '_weight' | _____no_output_____ | Apache-2.0 | site/en-snapshot/neural_structured_learning/tutorials/graph_keras_lstm_imdb.ipynb | ilyaspiridonov/docs-l10n |
HyperparametersWe will use an instance of `HParams` to inclue various hyperparameters andconstants used for training and evaluation. We briefly describe each of thembelow:- **num_classes**: There are 2 classes -- *positive* and *negative*.- **max_seq_length**: This is the maximum number of words considered from ea... | class HParams(object):
"""Hyperparameters used for training."""
def __init__(self):
### dataset parameters
self.num_classes = 2
self.max_seq_length = 256
self.vocab_size = 10000
### neural graph learning parameters
self.distance_type = nsl.configs.DistanceType.L2
self.graph_regularizatio... | _____no_output_____ | Apache-2.0 | site/en-snapshot/neural_structured_learning/tutorials/graph_keras_lstm_imdb.ipynb | ilyaspiridonov/docs-l10n |
Prepare the dataThe reviews—the arrays of integers—must be converted to tensors before being fedinto the neural network. This conversion can be done a couple of ways:* Convert the arrays into vectors of `0`s and `1`s indicating word occurrence, similar to a one-hot encoding. For example, the sequence `[3, 5]` wou... | def make_dataset(file_path, training=False):
"""Creates a `tf.data.TFRecordDataset`.
Args:
file_path: Name of the file in the `.tfrecord` format containing
`tf.train.Example` objects.
training: Boolean indicating if we are in training mode.
Returns:
An instance of `tf.data.TFRecordDataset` con... | _____no_output_____ | Apache-2.0 | site/en-snapshot/neural_structured_learning/tutorials/graph_keras_lstm_imdb.ipynb | ilyaspiridonov/docs-l10n |
Build the modelA neural network is created by stacking layers—this requires two main architectural decisions:* How many layers to use in the model?* How many *hidden units* to use for each layer?In this example, the input data consists of an array of word-indices. The labels to predict are either 0 or 1.We will use a ... | # This function exists as an alternative to the bi-LSTM model used in this
# notebook.
def make_feed_forward_model():
"""Builds a simple 2 layer feed forward neural network."""
inputs = tf.keras.Input(
shape=(HPARAMS.max_seq_length,), dtype='int64', name='words')
embedding_layer = tf.keras.layers.Embedding(... | _____no_output_____ | Apache-2.0 | site/en-snapshot/neural_structured_learning/tutorials/graph_keras_lstm_imdb.ipynb | ilyaspiridonov/docs-l10n |
The layers are effectively stacked sequentially to build the classifier:1. The first layer is an `Input` layer which takes the integer-encoded vocabulary.2. The next layer is an `Embedding` layer, which takes the integer-encoded vocabulary and looks up the embedding vector for each word-index. These vectors ... | model.compile(
optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) | _____no_output_____ | Apache-2.0 | site/en-snapshot/neural_structured_learning/tutorials/graph_keras_lstm_imdb.ipynb | ilyaspiridonov/docs-l10n |
Create a validation setWhen training, we want to check the accuracy of the model on data it hasn't seenbefore. Create a *validation set* by setting apart a fraction of the originaltraining data. (Why not use the testing set now? Our goal is to develop and tuneour model using only the training data, then use the test d... | validation_fraction = 0.9
validation_size = int(validation_fraction *
int(training_samples_count / HPARAMS.batch_size))
print(validation_size)
validation_dataset = train_dataset.take(validation_size)
train_dataset = train_dataset.skip(validation_size) | _____no_output_____ | Apache-2.0 | site/en-snapshot/neural_structured_learning/tutorials/graph_keras_lstm_imdb.ipynb | ilyaspiridonov/docs-l10n |
Train the modelTrain the model in mini-batches. While training, monitor the model's loss and accuracy on the validation set: | history = model.fit(
train_dataset,
validation_data=validation_dataset,
epochs=HPARAMS.train_epochs,
verbose=1) | _____no_output_____ | Apache-2.0 | site/en-snapshot/neural_structured_learning/tutorials/graph_keras_lstm_imdb.ipynb | ilyaspiridonov/docs-l10n |
Evaluate the modelNow, let's see how the model performs. Two values will be returned. Loss (a number which represents our error, lower values are better), and accuracy. | results = model.evaluate(test_dataset, steps=HPARAMS.eval_steps)
print(results) | _____no_output_____ | Apache-2.0 | site/en-snapshot/neural_structured_learning/tutorials/graph_keras_lstm_imdb.ipynb | ilyaspiridonov/docs-l10n |
Create a graph of accuracy/loss over time`model.fit()` returns a `History` object that contains a dictionary with everything that happened during training: | history_dict = history.history
history_dict.keys() | _____no_output_____ | Apache-2.0 | site/en-snapshot/neural_structured_learning/tutorials/graph_keras_lstm_imdb.ipynb | ilyaspiridonov/docs-l10n |
There are four entries: one for each monitored metric during training and validation. We can use these to plot the training and validation loss for comparison, as well as the training and validation accuracy: | acc = history_dict['accuracy']
val_acc = history_dict['val_accuracy']
loss = history_dict['loss']
val_loss = history_dict['val_loss']
epochs = range(1, len(acc) + 1)
# "-r^" is for solid red line with triangle markers.
plt.plot(epochs, loss, '-r^', label='Training loss')
# "-b0" is for solid blue line with circle mar... | _____no_output_____ | Apache-2.0 | site/en-snapshot/neural_structured_learning/tutorials/graph_keras_lstm_imdb.ipynb | ilyaspiridonov/docs-l10n |
Notice the training loss *decreases* with each epoch and the training accuracy*increases* with each epoch. This is expected when using a gradient descentoptimization—it should minimize the desired quantity on every iteration. Graph regularizationWe are now ready to try graph regularization using the base model that we... | # Build a new base LSTM model.
base_reg_model = make_bilstm_model()
# Wrap the base model with graph regularization.
graph_reg_config = nsl.configs.make_graph_reg_config(
max_neighbors=HPARAMS.num_neighbors,
multiplier=HPARAMS.graph_regularization_multiplier,
distance_type=HPARAMS.distance_type,
sum_ove... | _____no_output_____ | Apache-2.0 | site/en-snapshot/neural_structured_learning/tutorials/graph_keras_lstm_imdb.ipynb | ilyaspiridonov/docs-l10n |
Train the model | graph_reg_history = graph_reg_model.fit(
train_dataset,
validation_data=validation_dataset,
epochs=HPARAMS.train_epochs,
verbose=1) | _____no_output_____ | Apache-2.0 | site/en-snapshot/neural_structured_learning/tutorials/graph_keras_lstm_imdb.ipynb | ilyaspiridonov/docs-l10n |
Evaluate the model | graph_reg_results = graph_reg_model.evaluate(test_dataset, steps=HPARAMS.eval_steps)
print(graph_reg_results) | _____no_output_____ | Apache-2.0 | site/en-snapshot/neural_structured_learning/tutorials/graph_keras_lstm_imdb.ipynb | ilyaspiridonov/docs-l10n |
Create a graph of accuracy/loss over time | graph_reg_history_dict = graph_reg_history.history
graph_reg_history_dict.keys() | _____no_output_____ | Apache-2.0 | site/en-snapshot/neural_structured_learning/tutorials/graph_keras_lstm_imdb.ipynb | ilyaspiridonov/docs-l10n |
There are five entries in total in the dictionary: training loss, trainingaccuracy, training graph loss, validation loss, and validation accuracy. We canplot them all together for comparison. Note that the graph loss is only computedduring training. | acc = graph_reg_history_dict['accuracy']
val_acc = graph_reg_history_dict['val_accuracy']
loss = graph_reg_history_dict['loss']
graph_loss = graph_reg_history_dict['graph_loss']
val_loss = graph_reg_history_dict['val_loss']
epochs = range(1, len(acc) + 1)
plt.clf() # clear figure
# "-r^" is for solid red line with... | _____no_output_____ | Apache-2.0 | site/en-snapshot/neural_structured_learning/tutorials/graph_keras_lstm_imdb.ipynb | ilyaspiridonov/docs-l10n |
The power of semi-supervised learningSemi-supervised learning and more specifically, graph regularization in thecontext of this tutorial, can be really powerful when the amount of trainingdata is small. The lack of training data is compensated by leveraging similarityamong the training samples, which is not possible i... | # Accuracy values for both the Bi-LSTM model and the feed forward NN model have
# been precomputed for the following supervision ratios.
supervision_ratios = [0.3, 0.15, 0.05, 0.03, 0.02, 0.01, 0.005]
model_tags = ['Bi-LSTM model', 'Feed Forward NN model']
base_model_accs = [[84, 84, 83, 80, 65, 52, 50], [87, 86, 76,... | _____no_output_____ | Apache-2.0 | site/en-snapshot/neural_structured_learning/tutorials/graph_keras_lstm_imdb.ipynb | ilyaspiridonov/docs-l10n |
DAT210x - Programming with Python for DS Module5- Lab6 | import random, math
import pandas as pd
import numpy as np
import scipy.io
from sklearn.model_selection import train_test_split
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn import manifold
from sklearn.neighbors import KNeighborsClassifier
... | _____no_output_____ | MIT | Module5/.ipynb_checkpoints/Module5 - Lab6-checkpoint.ipynb | 3point14thon/DAT210x-master |
A Convenience Function This method is for your visualization convenience only. You aren't expected to know how to put this together yourself, although you should be able to follow the code by now: | def Plot2DBoundary(DTrain, LTrain, DTest, LTest):
# The dots are training samples (img not drawn), and the pics are testing samples (images drawn)
# Play around with the K values. This is very controlled dataset so it should be able to get perfect classification on testing entries
# Play with the K for isom... | _____no_output_____ | MIT | Module5/.ipynb_checkpoints/Module5 - Lab6-checkpoint.ipynb | 3point14thon/DAT210x-master |
The Assignment Use the same code from Module4/assignment4.ipynb to load up the `face_data.mat` file into a dataframe called `df`. Be sure to calculate the `num_pixels` value, and to rotate the images to being right-side-up instead of sideways. This was demonstrated in the [Lab Assignment 4](https://github.com/authman/... | mat = scipy.io.loadmat('Datasets/face_data.mat')
df = pd.DataFrame(mat['images']).T
num_images, num_pixels = df.shape
num_pixels = int(math.sqrt(num_pixels))
# Rotate the pictures, so we don't have to crane our necks:
for i in range(num_images):
df.loc[i,:] = df.loc[i,:].values.reshape(num_pixels, num_pixels).T.re... | _____no_output_____ | MIT | Module5/.ipynb_checkpoints/Module5 - Lab6-checkpoint.ipynb | 3point14thon/DAT210x-master |
Load up your face_labels dataset. It only has a single column, and you're only interested in that single column. You will have to slice the column out so that you have access to it as a "Series" rather than as a "Dataframe". This was discussed in the the "Slicin'" lecture of the "Manipulating Data" reading on the cou... | y = pd.read_csv('Datasets/face_labels.csv',header=None)
y = y.iloc[:,0] | _____no_output_____ | MIT | Module5/.ipynb_checkpoints/Module5 - Lab6-checkpoint.ipynb | 3point14thon/DAT210x-master |
Do `train_test_split`. Use the same code as on the EdX platform in the reading material, but set the random_state=7 for reproducibility, and the test_size to 0.15 (150%). Your labels are actually passed in as a series (instead of as an NDArray) so that you can access their underlying indices later on. This is necessary... | x_train, x_test, y_train, y_test = train_test_split(df, y, test_size=.2, random_state=7) | _____no_output_____ | MIT | Module5/.ipynb_checkpoints/Module5 - Lab6-checkpoint.ipynb | 3point14thon/DAT210x-master |
Dimensionality Reduction | if Test_PCA:
# INFO: PCA is used *before* KNeighbors to simplify your high dimensionality
# image samples down to just 2 principal components! A lot of information
# (variance) is lost during the process, as I'm sure you can imagine. But
# you have to drop the dimension down to two, otherwise you wouldn... | _____no_output_____ | MIT | Module5/.ipynb_checkpoints/Module5 - Lab6-checkpoint.ipynb | 3point14thon/DAT210x-master |
Implement `KNeighborsClassifier` here. You can use any K value from 1 through 20, so play around with it and attempt to get good accuracy. Fit the classifier against your training data and labels. | model = KNeighborsClassifier(n_neighbors=5)
model.fit(x_train, y_train) | _____no_output_____ | MIT | Module5/.ipynb_checkpoints/Module5 - Lab6-checkpoint.ipynb | 3point14thon/DAT210x-master |
Calculate and display the accuracy of the testing set (data_test and label_test): | score = model.score(x_test,y_test)
print(score) | 0.964285714286
| MIT | Module5/.ipynb_checkpoints/Module5 - Lab6-checkpoint.ipynb | 3point14thon/DAT210x-master |
Let's chart the combined decision boundary, the training data as 2D plots, and the testing data as small images so we can visually validate performance: | Plot2DBoundary(x_train, y_train, x_test, y_test) | C:\Users\Chris\Anaconda3\lib\site-packages\ipykernel_launcher.py:64: FutureWarning: reshape is deprecated and will raise in a subsequent release. Please use .values.reshape(...) instead
| MIT | Module5/.ipynb_checkpoints/Module5 - Lab6-checkpoint.ipynb | 3point14thon/DAT210x-master |
After submitting your answers, experiment with using using PCA instead of ISOMap. Are the results what you expected? Also try tinkering around with the test/train split percentage from 10-20%. Notice anything? | # .. your code changes above .. | _____no_output_____ | MIT | Module5/.ipynb_checkpoints/Module5 - Lab6-checkpoint.ipynb | 3point14thon/DAT210x-master |
Working With The CIFAR10 Dataset This is it. You've seen how to define a simple convolutional neural network, compute loss w.r.t. the graph Variables, and make gradient updates manually and with `torch.nn.optim` package.Now you might be thinking: What about the data?Generally, when you have to deal with image, text, a... | %matplotlib inline
# file manipulation
import os.path
# arrays and visualization
import numpy as np
import matplotlib.pyplot as plt
# pytorch imports
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.autograd import Variable
# Special package provided by pytor... | _____no_output_____ | MIT | 04 - Training a classifier/Working with CIFAR10 dataset.ipynb | victor-iyi/pytorch-examples |
Let's define some *Hyperparameters* we're gonna need later on. | ## Hyperparameters.
# image channel 3=RGB, 1=Grayscale
img_channels = 3
# Class labels.
classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
num_classes = len(classes)
# Data directory.
data_dir = '../datasets' # Dataset directory.
download = True # Download dataset ... | _____no_output_____ | MIT | 04 - Training a classifier/Working with CIFAR10 dataset.ipynb | victor-iyi/pytorch-examples |
The output of the `torchvision` dataset are PILImage images of range [0, 1]. We transform them to Tensors of normalized range [-1, 1].Define the data directory, i.e. where the data should be downloaded to. With the use of `os.path` module.**NOTE:** `data_dir` could be modified to fit your use. | # Should normalize images or not.
# Normalization helps convergence.
if normalize:
# Transform rule: Convert to Tensor, Normalize images in range -1 to 1.
transform = transforms.Compose([transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5),
... | _____no_output_____ | MIT | 04 - Training a classifier/Working with CIFAR10 dataset.ipynb | victor-iyi/pytorch-examples |
2. Define a Convolution Neural NetworkIt's time to define our neural network. You've already seen how to define a simple convolutional neural network in the last section. But this time, instead of a single color channel, we have 3-color channels, because the CIFAR10 dataset contains colored images. | class Network(nn.Module):
def __init__(self, **kwargs):
super(Network, self).__init__()
# Hyper-parameters
self._img_channels = kwargs.get('img_channels')
self._num_classes = kwargs.get('num_classes')
# 2 convolutional & 3 fully connected layers
... | _____no_output_____ | MIT | 04 - Training a classifier/Working with CIFAR10 dataset.ipynb | victor-iyi/pytorch-examples |
3. Define a Loss function and optimizerLet’s use a Classification Cross-Entropy loss and Adam optimizer. | # Loss function criterion
loss_func = nn.CrossEntropyLoss()
# Adam optimizer
optimizer = optim.Adam(net.parameters(), lr=lr) | _____no_output_____ | MIT | 04 - Training a classifier/Working with CIFAR10 dataset.ipynb | victor-iyi/pytorch-examples |
4. Train the NetworkThis is when things start to get interesting. We simply have to loop over our data iterator, and feed the inputs to the network and optimize it. | # Loop over the data multiple times.
for epoch in range(epochs):
# Loop through the training dataset (batch by batch).
for i, data in enumerate(trainset):
# Get the inputs and labels.
inputs, labels = data
# Wrap them in Variable (explained in section 2).
input... | Epoch: 1 Iter: 3,125 Loss: 1.7392
Epoch: 2 Iter: 3,125 Loss: 1.8330
Epoch: 3 Iter: 3,125 Loss: 2.0041
Epoch: 4 Iter: 3,125 Loss: 1.7069
Epoch: 5 Iter: 3,125 Loss: 1.5338
Finished training!
| MIT | 04 - Training a classifier/Working with CIFAR10 dataset.ipynb | victor-iyi/pytorch-examples |
5. Test the network on the test dataWe have trained the network for 5 epochs (passes over the training data). Let's check if the network has learnt anything.How we check this is by comparing the ground-truth labels over the one the network predicted. We'll keep track of the ones predicted correctly by creating a list,... | # Look at some test data.
visualize(testset) | _____no_output_____ | MIT | 04 - Training a classifier/Working with CIFAR10 dataset.ipynb | victor-iyi/pytorch-examples |
Okay, now let's make some predictions with our network. | # Let's make some predictions on the testset.
test_iter = iter(testset)
images, labels = test_iter.next()
# Convert images to `autograd.Variable`
# before passing through the network.
output = net(Variable(images)) | _____no_output_____ | MIT | 04 - Training a classifier/Working with CIFAR10 dataset.ipynb | victor-iyi/pytorch-examples |
The outputs are "energies" for the 10 classes. *Higher the energy for a class, the more the network thinks that the image is of the particular class*. So, let’s get the index of the highest energy: | # torch.max returns a tuple: (value, index)
# Take the argmax of the predicted output.
_, predictions = torch.max(output.data, dim=1)
# Visualize the predictions.
imshow(images, labels=labels, pred=predictions, smooth=True) | _____no_output_____ | MIT | 04 - Training a classifier/Working with CIFAR10 dataset.ipynb | victor-iyi/pytorch-examples |
Maybe not so bad, huh? Let's see how the result performs on the entire dataset. | # Keep track of correct prediction and total.
correct, total = 0, 0
# Looping through the testset.
for data in testset:
# Unpack the images and labels
# from each mini-batch.
images, labels = data
# Pass image through the network
# to make predictions.
outputs = net(Variable(images))
... | Accuracy on testset = 46.46%
| MIT | 04 - Training a classifier/Working with CIFAR10 dataset.ipynb | victor-iyi/pytorch-examples |
Well, that's slightly better than random guessing, which is 10% accuracy (randomly picking a class out of 10 classes). Seems like the network learnt something.Hmmm, what are the classes that performed well, and the classes that did not perform well: | # Each index in the `correct_class` stores
# the correct classification for that class;
# while `total_class` stores the total number
# of times we go through the class.
correct_class = torch.zeros(10)
total_class = torch.zeros(10)
# Loop through all dataset
# one batch at a time.
for data in testset:
# Get the cu... | Accuracy of plane = 73.20%
Accuracy of car = 62.40%
Accuracy of bird = 61.30%
Accuracy of cat = 58.40%
Accuracy of deer = 49.80%
Accuracy of dog = 47.10%
Accuracy of frog = 35.60%
Accuracy of horse = 31.50%
Accuracy of ship = 23.50%
Accuracy of truck = 21.80%
| MIT | 04 - Training a classifier/Working with CIFAR10 dataset.ipynb | victor-iyi/pytorch-examples |
Your first neural networkIn this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of the code, but left the implementation of the neural network up to you (for the most part). After you've submitted this project, feel free to explore the data and th... | %matplotlib inline
%config InlineBackend.figure_format = 'retina'
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt | _____no_output_____ | MIT | bike rental prediction/Binesh Kumar's First Neural Network.ipynb | TechieBIN/graphdef |
Load and prepare the dataA critical step in working with neural networks is preparing the data correctly. Variables on different scales make it difficult for the network to efficiently learn the correct weights. Below, we've written the code to load and prepare the data. You'll learn more about this soon! | data_path = 'Bike-Sharing-Dataset/hour.csv'
rides = pd.read_csv(data_path)
rides.head() | _____no_output_____ | MIT | bike rental prediction/Binesh Kumar's First Neural Network.ipynb | TechieBIN/graphdef |
Checking out the dataThis dataset has the number of riders for each hour of each day from January 1 2011 to December 31 2012. The number of riders is split between casual and registered, summed up in the `cnt` column. You can see the first few rows of the data above.Below is a plot showing the number of bike riders ov... | rides[:24*10].plot(x='dteday', y='cnt') | _____no_output_____ | MIT | bike rental prediction/Binesh Kumar's First Neural Network.ipynb | TechieBIN/graphdef |
Dummy variablesHere we have some categorical variables like season, weather, month. To include these in our model, we'll need to make binary dummy variables. This is simple to do with Pandas thanks to `get_dummies()`. | dummy_fields = ['season', 'weathersit', 'mnth', 'hr', 'weekday']
for each in dummy_fields:
dummies = pd.get_dummies(rides[each], prefix=each, drop_first=False)
rides = pd.concat([rides, dummies], axis=1)
fields_to_drop = ['instant', 'dteday', 'season', 'weathersit',
'weekday', 'atemp', 'mnth... | _____no_output_____ | MIT | bike rental prediction/Binesh Kumar's First Neural Network.ipynb | TechieBIN/graphdef |
Scaling target variablesTo make training the network easier, we'll standardize each of the continuous variables. That is, we'll shift and scale the variables such that they have zero mean and a standard deviation of 1.The scaling factors are saved so we can go backwards when we use the network for predictions. | quant_features = ['casual', 'registered', 'cnt', 'temp', 'hum', 'windspeed']
# Store scalings in a dictionary so we can convert back later
scaled_features = {}
for each in quant_features:
mean, std = data[each].mean(), data[each].std()
scaled_features[each] = [mean, std]
data.loc[:, each] = (data[each] - me... | _____no_output_____ | MIT | bike rental prediction/Binesh Kumar's First Neural Network.ipynb | TechieBIN/graphdef |
Splitting the data into training, testing, and validation setsWe'll save the data for the last approximately 21 days to use as a test set after we've trained the network. We'll use this set to make predictions and compare them with the actual number of riders. | # Save data for approximately the last 21 days
test_data = data[-21*24:]
# Now remove the test data from the data set
data = data[:-21*24]
# Separate the data into features and targets
target_fields = ['cnt', 'casual', 'registered']
features, targets = data.drop(target_fields, axis=1), data[target_fields]
test_feat... | _____no_output_____ | MIT | bike rental prediction/Binesh Kumar's First Neural Network.ipynb | TechieBIN/graphdef |
We'll split the data into two sets, one for training and one for validating as the network is being trained. Since this is time series data, we'll train on historical data, then try to predict on future data (the validation set). | # Hold out the last 60 days or so of the remaining data as a validation set
train_features, train_targets = features[:-60*24], targets[:-60*24]
val_features, val_targets = features[-60*24:], targets[-60*24:] | _____no_output_____ | MIT | bike rental prediction/Binesh Kumar's First Neural Network.ipynb | TechieBIN/graphdef |
Time to build the networkBelow you'll build your network. We've built out the structure and the backwards pass. You'll implement the forward pass through the network. You'll also set the hyperparameters: the learning rate, the number of hidden units, and the number of training passes.The network has two layers, a hidd... | class NeuralNetwork(object):
def __init__(self, input_nodes, hidden_nodes, output_nodes, learning_rate):
# Set number of nodes in input, hidden and output layers.
self.input_nodes = input_nodes
self.hidden_nodes = hidden_nodes
self.output_nodes = output_nodes
# Initialize we... | _____no_output_____ | MIT | bike rental prediction/Binesh Kumar's First Neural Network.ipynb | TechieBIN/graphdef |
Unit testsRun these unit tests to check the correctness of your network implementation. This will help you be sure your network was implemented correctly befor you starting trying to train it. These tests must all be successful to pass the project. | import unittest
inputs = np.array([[0.5, -0.2, 0.1]])
targets = np.array([[0.4]])
test_w_i_h = np.array([[0.1, -0.2],
[0.4, 0.5],
[-0.3, 0.2]])
test_w_h_o = np.array([[0.3],
[-0.1]])
class TestMethods(unittest.TestCase):
##########
# Un... | .....
----------------------------------------------------------------------
Ran 5 tests in 0.007s
OK
| MIT | bike rental prediction/Binesh Kumar's First Neural Network.ipynb | TechieBIN/graphdef |
Training the networkHere you'll set the hyperparameters for the network. The strategy here is to find hyperparameters such that the error on the training set is low, but you're not overfitting to the data. If you train the network too long or have too many hidden nodes, it can become overly specific to the training se... | import sys
### Set the hyperparameters here ###
iterations = 4000
learning_rate = 0.785
hidden_nodes = 16
output_nodes = 1
N_i = train_features.shape[1]
network = NeuralNetwork(N_i, hidden_nodes, output_nodes, learning_rate)
losses = {'train':[], 'validation':[]}
for ii in range(iterations):
# Go through a rando... | _____no_output_____ | MIT | bike rental prediction/Binesh Kumar's First Neural Network.ipynb | TechieBIN/graphdef |
Check out your predictionsHere, use the test data to view how well your network is modeling the data. If something is completely wrong here, make sure each step in your network is implemented correctly. | fig, ax = plt.subplots(figsize=(8,4))
mean, std = scaled_features['cnt']
predictions = network.run(test_features).T*std + mean
ax.plot(predictions[0], label='Prediction')
ax.plot((test_targets['cnt']*std + mean).values, label='Data')
ax.set_xlim(right=len(predictions))
ax.legend()
dates = pd.to_datetime(rides.ix[test... | _____no_output_____ | MIT | bike rental prediction/Binesh Kumar's First Neural Network.ipynb | TechieBIN/graphdef |
Tensil TCU Demo - ResNet-20 CIFAR Import the TCU driver | import sys
sys.path.append('/home/xilinx')
# Needed to run inference on TCU
import time
import numpy as np
import pynq
from pynq import Overlay
from tcu_pynq.driver import Driver
from tcu_pynq.architecture import zcu104
# Needed for unpacking and displaying image data
%matplotlib inline
import matplotlib.pyplot as pl... | _____no_output_____ | Apache-2.0 | notebooks/zcu104/Tensil TCU Demo - ResNet-20 CIFAR.ipynb | tensil-ai/tensil |
Configure the fabric and driver | overlay = Overlay('/home/xilinx/tensil_zcu104.bit')
tcu = Driver(zcu104, overlay.axi_dma_0) | _____no_output_____ | Apache-2.0 | notebooks/zcu104/Tensil TCU Demo - ResNet-20 CIFAR.ipynb | tensil-ai/tensil |
Read CIFAR-10 images | def unpickle(file):
with open(file, 'rb') as fo:
d = pickle.load(fo, encoding='bytes')
return d
cifar = unpickle('/home/xilinx/cifar-10-batches-py/test_batch')
data = cifar[b'data']
labels = cifar[b'labels']
data = data[10:20]
labels = labels[10:20]
data_norm = data.astype('float32') / 255
data_mean ... | _____no_output_____ | Apache-2.0 | notebooks/zcu104/Tensil TCU Demo - ResNet-20 CIFAR.ipynb | tensil-ai/tensil |
Demo: ResNet-20 inference Load the model | tcu.load_model('/home/xilinx/resnet20v2_cifar_onnx_zcu104.tmodel') | _____no_output_____ | Apache-2.0 | notebooks/zcu104/Tensil TCU Demo - ResNet-20 CIFAR.ipynb | tensil-ai/tensil |
Run inference | inputs = {'x:0': img}
start = time.time()
outputs = tcu.run(inputs)
end = time.time()
print("Ran inference in {:.4}s".format(end - start))
print()
classes = outputs['Identity:0'][:10]
result_idx = np.argmax(classes)
result = label_names[result_idx]
print("Output activations:")
print(classes)
print()
print("Result: {... | Ran inference in 0.01865s
Output activations:
[-13.69140625 -12.359375 -7.90625 -6.30859375 -8.296875
-12.2421875 15.17578125 -15.0390625 -10.5703125 -9.12109375]
Result: frog (idx = 6)
Actual: frog (idx = 6)
| Apache-2.0 | notebooks/zcu104/Tensil TCU Demo - ResNet-20 CIFAR.ipynb | tensil-ai/tensil |
 Librería NumPy.*** [*NumPy*](https://docs.scipy.org/doc/numpy/user/index.html) (*Numerical Python*) es una librería para el cómputo científico. Esta librería contiene muchas funciones matemáticas que permiten realizar operaciones de álgebra lineal, manejar matrices y vectores, generar n... | import numpy as np | _____no_output_____ | MIT | 01_numpy.ipynb | ejdecena/herramientas |
Arreglos (arrays). *NumPy* usa una estructura de datos llamada *array* (arreglos). Los arreglos de *NumPy* son similares a las listas de *Python*, pero son más eficientes para realizar tareas numéricas. La eficiencia deriva de las siguientes características:* Las listas de *Python* son muy generales, pudiendo contener... | v = np.array([1, 2, 3, 4 , 5, 6])
v
M = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
M | _____no_output_____ | MIT | 01_numpy.ipynb | ejdecena/herramientas |
El atributo *`shape`* de los objetos *array* retorna la *forma* de los arreglos; esto es el número de dimensiones y número de elementos del *array* en forma de tupla: | v.shape, M.shape | _____no_output_____ | MIT | 01_numpy.ipynb | ejdecena/herramientas |
A partir de un rango numérico: Una forma de crear arreglos en *NumPy* desde cero es usando *rangos*. Por ejemplo podemos crear un arreglo conteniendo números igualmente espaciados en el intervalo \[desde, hasta) usando la función *`arange`*: | np.arange(0, 10, 2) # desde, hasta(sin incluir), paso. | _____no_output_____ | MIT | 01_numpy.ipynb | ejdecena/herramientas |
Otra función para crear rangos es *`linspace`* que devuelve números igualmente espaciados en el intervalo \[*desde*, *hasta*, *elementos*\] (es decir incluyendo el *hasta*). Otra diferencia de la función *`linspace`* con *`arange`* es que no se especifica el paso sino la **cantidad total** de números que contendrá el a... | np.linspace(1, 10, 5) # desde, hasta, elementos (elementos es opcional). | _____no_output_____ | MIT | 01_numpy.ipynb | ejdecena/herramientas |
A partir de números aleatorios: Los números aleatorios son usados en muchos problemas científicos. En la práctica las computadoras son capaces solo de generar números *pseudo-aleatorios*; es decir, números que para los fines prácticos *lucen* como números aleatorios.Todas las rutinas para generar números aleatorios vi... | np.random.rand(2, 5) # arreglo con forma (2, 5). | _____no_output_____ | MIT | 01_numpy.ipynb | ejdecena/herramientas |
De forma similar, la función *`randn`* devuelve muestras a partir de la *distribución normal estándar* (media = 0, desviación estándard = 1): | np.random.randn(10) # Muestra de 10 elementos de la distribución normal estándar. | _____no_output_____ | MIT | 01_numpy.ipynb | ejdecena/herramientas |
Más general, la función *`normal`* devuelve una muestra de una *distribución normal* dada una media, una desviación estándar y el tamaño de la muestra: | media = 5
desv = 2
muestra = 5
np.random.normal(media, desv, muestra) | _____no_output_____ | MIT | 01_numpy.ipynb | ejdecena/herramientas |
A partir de ceros y unos: Las funciones *`zeros`* y *`ones`* retornan arreglos de *ceros* y *unos* dados el número de elementos: | np.zeros(5) # Arreglo de 5 elementos cero.
np.ones(7) # Arreglo de 7 elementos uno.
np.zeros(shape = (2, 3)) # Arreglo de ceros especificando el shape.
np.ones(shape = (3, 3)) # Arreglo de unos especificando el shape. | _____no_output_____ | MIT | 01_numpy.ipynb | ejdecena/herramientas |
Indexado y rebanado de arreglos. Los arreglos de *NumPy*, al igual que las listas se pueden *indexar* y se pueden tomar rebanadas (slices). La sintaxis es una generalización de la usada para las listas de *Python*. Una de las diferencias es que podemos indexar de acuerdo a las distintas dimensiones de un arreglo. | M[0] # El primer elemento de M.
M[0, 1] # El primer elemento de M y obtenemos el segundo elemento.
M[0][1] # Forma alternativa.
M[1:] # A partir de la fila 1, todo.
M[1,:] # Fila 1, todas las columnas.
M[1] # Forma equivalente.
M[:, 1] # Todas las dilas de la columna 1.
M[:, 1:] # Todas las columnas a partir de ... | _____no_output_____ | MIT | 01_numpy.ipynb | ejdecena/herramientas |
Es importante acotar que al tomar *rebanadas* (*slices*) *NumPy* NO genera un nuevo arreglo; sino una **vista** (*view*) del arreglo original. Por lo tanto, si a una rebanada le asignamos un número, se lo estaremos asignando al arreglo original, como se puede ver en el siguiente ejemplo: | M[0, 0] = 0
M | _____no_output_____ | MIT | 01_numpy.ipynb | ejdecena/herramientas |
Para crear copias se puede usar la función *`np.copy()`* o el método *`.copy()`* de los objetos *`array`*. Funciones Universales (Ufunc). *NumPy* provee de varias funciones matemáticas. Esto puede parecer redundante ya que la librería estandard de *Python* ya provee de este tipo de funciones. La **diferencia**, es que... | np.sqrt(M) | _____no_output_____ | MIT | 01_numpy.ipynb | ejdecena/herramientas |
Funciones como *`sqrt`*, que operan sobre arreglos *elemento-a-elemento* se conocen como [***funciones universales***](http://docs.scipy.org/doc/numpy/reference/ufuncs.html) (usualmente abreviadas como *ufunc*).Una de las ventajas de usar *ufuncs* es que permiten escribir código más breve. Otra ventaja es que los cómpu... | np.sum(M) | _____no_output_____ | MIT | 01_numpy.ipynb | ejdecena/herramientas |
En el ejemplo anterior la suma se hizo sobre el arreglo "aplanado". Hay veces que esto no es lo que queremos, si no que necesitamos sumar sobre alguna de las dimensiones del arreglo: | np.sum(M, axis = 0) # Sumariza por columnas.
np.sum(M, axis = 1) # Sumariza por filas. | _____no_output_____ | MIT | 01_numpy.ipynb | ejdecena/herramientas |
Broadcasting. Otro elemento que facilita vectorizar código es la capacidad de operar sobre arreglos que no tienen las mismas dimensiones. Esto se llama *broadcasting* y no es más que un conjunto de reglas que permiten aplicar operaciones binarias (suma, multiplicación etc.) a arreglos de distinto tamaño.Consideremos e... | a = np.array([0, 1, 2])
b = np.array([2, 2, 2])
a + b | _____no_output_____ | MIT | 01_numpy.ipynb | ejdecena/herramientas |
Esto no es nada sorprendente, lo que hemos hecho es sumar elemento-a-elemento. Fíjese que el arreglo `b` contiene 3 veces el número 2. Gracias al *broadcasting* es posible obtener el mismo resultado al hacer: | a + 2 | _____no_output_____ | MIT | 01_numpy.ipynb | ejdecena/herramientas |
Esto no sólo funciona para arreglos y números, también funciona para dos arreglos: | M + b | _____no_output_____ | MIT | 01_numpy.ipynb | ejdecena/herramientas |
En ambos casos lo que está sucediendo es como si antes de realizar la suma extendieramos una de las partes para que las dimensiones conincidan, por ejemplo repetir 3 veces el número 2 o tres veces el vector b. En realidad tal repetición no se realiza, pero es una forma útil de pensar la operación.Es claro que el *broad... | M[1:, :] + b | _____no_output_____ | MIT | 01_numpy.ipynb | ejdecena/herramientas |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.