markdown
stringlengths 0
37k
| code
stringlengths 1
33.3k
| path
stringlengths 8
215
| repo_name
stringlengths 6
77
| license
stringclasses 15
values |
---|---|---|---|---|
NOTE: This colab has been verified to work with the latest released version of the tensorflow_federated pip package, but the Tensorflow Federated project is still in pre-release development and may not work on main.
Composing Learning Algorithms
The Building Your Own Federated Learning Algorithm Tutorial used TFF's federated core to directly implement a version of the Federated Averaging (FedAvg) algorithm.
In this tutorial, you will use federated learning components in TFF's API to build federated learning algorithms in a modular manner, without having to re-implement everything from scratch.
For the purposes of this tutorial, you will implement a variant of FedAvg that employs gradient clipping through local training.
Learning Algorithm Building Blocks
At a high level, many learning algorithms can be separated into 4 separate components, referred to as building blocks. These are as follows:
Distributor (ie. server-to-client communication)
Client work (ie. local client computation)
Aggregator (ie. client-to-server communication)
Finalizer (ie. server computation using aggregated client outputs)
While the Building Your Own Federated Learning Algorithm Tutorial implemented all of these building blocks from scratch, this is often unnecessary. Instead, you can re-use building blocks from similar algorithms.
In this case, to implement FedAvg with gradient clipping, you only need to modify the client work building block. The remaining blocks can be identical to what is used in "vanilla" FedAvg.
Implementing the Client Work
First, let's write TF logic that does local model training with gradient clipping. For simplicity, gradients will be clipped have norm at most 1.
TF Logic
|
@tf.function
def client_update(model: tff.learning.Model,
dataset: tf.data.Dataset,
server_weights: tff.learning.ModelWeights,
client_optimizer: tf.keras.optimizers.Optimizer):
"""Performs training (using the server model weights) on the client's dataset."""
# Initialize the client model with the current server weights.
client_weights = tff.learning.ModelWeights.from_model(model)
tf.nest.map_structure(lambda x, y: x.assign(y),
client_weights, server_weights)
# Use the client_optimizer to update the local model.
# Keep track of the number of examples as well.
num_examples = 0.0
for batch in dataset:
with tf.GradientTape() as tape:
# Compute a forward pass on the batch of data
outputs = model.forward_pass(batch)
num_examples += tf.cast(outputs.num_examples, tf.float32)
# Compute the corresponding gradient
grads = tape.gradient(outputs.loss, client_weights.trainable)
# Compute the gradient norm and clip
gradient_norm = tf.linalg.global_norm(grads)
if gradient_norm > 1:
grads = tf.nest.map_structure(lambda x: x/gradient_norm, grads)
grads_and_vars = zip(grads, client_weights.trainable)
# Apply the gradient using a client optimizer.
client_optimizer.apply_gradients(grads_and_vars)
# Compute the difference between the server weights and the client weights
client_update = tf.nest.map_structure(tf.subtract,
client_weights.trainable,
server_weights.trainable)
return tff.learning.templates.ClientResult(
update=client_update, update_weight=num_examples)
|
docs/tutorials/composing_learning_algorithms.ipynb
|
tensorflow/federated
|
apache-2.0
|
There are a few important points about the code above. First, it keeps track of the number of examples seen, as this will constitute the weight of the client update (when computing an average across clients).
Second, it uses tff.learning.templates.ClientResult to package the output. This return type is used to standardize client work building blocks in tff.learning.
Creating a ClientWorkProcess
While the TF logic above will do local training with clipping, it still needs to be wrapped in TFF code in order to create the necessary building block.
Specifically, the 4 building blocks are represented as a tff.templates.MeasuredProcess. This means that all 4 blocks have both an initialize and next function used to instantiate and run the computation.
This allows each building block to keep track of its own state (stored at the server) as needed to perform its operations. While it will not be used in this tutorial, it can be used for things like tracking how many iterations have occurred, or keeping track of optimizer states.
Client work TF logic should generally be wrapped as a tff.learning.templates.ClientWorkProcess, which codifies the expected types going into and out of the client's local training. It can be parameterized by a model and optimizer, as below.
|
def build_gradient_clipping_client_work(
model_fn: Callable[[], tff.learning.Model],
optimizer_fn: Callable[[], tf.keras.optimizers.Optimizer],
) -> tff.learning.templates.ClientWorkProcess:
"""Creates a client work process that uses gradient clipping."""
with tf.Graph().as_default():
# Wrap model construction in a graph to avoid polluting the global context
# with variables created for this model.
model = model_fn()
data_type = tff.SequenceType(model.input_spec)
model_weights_type = tff.learning.framework.weights_type_from_model(model)
@tff.federated_computation
def initialize_fn():
return tff.federated_value((), tff.SERVER)
@tff.tf_computation(model_weights_type, data_type)
def client_update_computation(model_weights, dataset):
model = model_fn()
optimizer = optimizer_fn()
return client_update(model, dataset, model_weights, optimizer)
@tff.federated_computation(
initialize_fn.type_signature.result,
tff.type_at_clients(model_weights_type),
tff.type_at_clients(data_type)
)
def next_fn(state, model_weights, client_dataset):
client_result = tff.federated_map(
client_update_computation, (model_weights, client_dataset))
# Return empty measurements, though a more complete algorithm might
# measure something here.
measurements = tff.federated_value((), tff.SERVER)
return tff.templates.MeasuredProcessOutput(state, client_result,
measurements)
return tff.learning.templates.ClientWorkProcess(
initialize_fn, next_fn)
|
docs/tutorials/composing_learning_algorithms.ipynb
|
tensorflow/federated
|
apache-2.0
|
Composing a Learning Algorithm
Let's put the client work above into a full-fledged algorithm. First, let's set up our data and model.
Preparing the input data
Load and preprocess the EMNIST dataset included in TFF. For more details, see the image classification tutorial.
|
emnist_train, emnist_test = tff.simulation.datasets.emnist.load_data()
|
docs/tutorials/composing_learning_algorithms.ipynb
|
tensorflow/federated
|
apache-2.0
|
In order to feed the dataset into our model, the data is flattened and converted into tuples of the form (flattened_image_vector, label).
Let's select a small number of clients, and apply the preprocessing above to their datasets.
|
NUM_CLIENTS = 10
BATCH_SIZE = 20
def preprocess(dataset):
def batch_format_fn(element):
"""Flatten a batch of EMNIST data and return a (features, label) tuple."""
return (tf.reshape(element['pixels'], [-1, 784]),
tf.reshape(element['label'], [-1, 1]))
return dataset.batch(BATCH_SIZE).map(batch_format_fn)
client_ids = sorted(emnist_train.client_ids)[:NUM_CLIENTS]
federated_train_data = [preprocess(emnist_train.create_tf_dataset_for_client(x))
for x in client_ids
]
|
docs/tutorials/composing_learning_algorithms.ipynb
|
tensorflow/federated
|
apache-2.0
|
Preparing the model
This uses the same model as in the image classification tutorial. This model (implemented via tf.keras) has a single hidden layer, followed by a softmax layer. In order to use this model in TFF, Keras model is wrapped as a tff.learning.Model. This allows us to perform the model's forward pass within TFF, and extract model outputs. For more details, also see the image classification tutorial.
|
def create_keras_model():
initializer = tf.keras.initializers.GlorotNormal(seed=0)
return tf.keras.models.Sequential([
tf.keras.layers.Input(shape=(784,)),
tf.keras.layers.Dense(10, kernel_initializer=initializer),
tf.keras.layers.Softmax(),
])
def model_fn():
keras_model = create_keras_model()
return tff.learning.from_keras_model(
keras_model,
input_spec=federated_train_data[0].element_spec,
loss=tf.keras.losses.SparseCategoricalCrossentropy(),
metrics=[tf.keras.metrics.SparseCategoricalAccuracy()])
|
docs/tutorials/composing_learning_algorithms.ipynb
|
tensorflow/federated
|
apache-2.0
|
Preparing the optimizers
Just as in tff.learning.build_federated_averaging_process, there are two optimizers here: A client optimizer, and a server optimizer. For simplicity, the optimizers will be SGD with different learning rates.
|
client_optimizer_fn = lambda: tf.keras.optimizers.SGD(learning_rate=0.01)
server_optimizer_fn = lambda: tf.keras.optimizers.SGD(learning_rate=1.0)
|
docs/tutorials/composing_learning_algorithms.ipynb
|
tensorflow/federated
|
apache-2.0
|
Defining the building blocks
Now that the client work building block, data, model, and optimizers are set up, it remains to create building blocks for the distributor, the aggregator, and the finalizer. This can be done just by borrowing some defaults available in TFF and that are used by FedAvg.
|
@tff.tf_computation()
def initial_model_weights_fn():
return tff.learning.ModelWeights.from_model(model_fn())
model_weights_type = initial_model_weights_fn.type_signature.result
distributor = tff.learning.templates.build_broadcast_process(model_weights_type)
client_work = build_gradient_clipping_client_work(model_fn, client_optimizer_fn)
# TFF aggregators use a factory pattern, which create an aggregator
# based on the output type of the client work. This also uses a float (the number
# of examples) to govern the weight in the average being computed.)
aggregator_factory = tff.aggregators.MeanFactory()
aggregator = aggregator_factory.create(model_weights_type.trainable,
tff.TensorType(tf.float32))
finalizer = tff.learning.templates.build_apply_optimizer_finalizer(
server_optimizer_fn, model_weights_type)
|
docs/tutorials/composing_learning_algorithms.ipynb
|
tensorflow/federated
|
apache-2.0
|
Composing the building blocks
Finally, you can use a built-in composer in TFF for putting the building blocks together. This one is a relatively simple composer, which takes the 4 building blocks above and wires their types together.
|
fed_avg_with_clipping = tff.learning.templates.compose_learning_process(
initial_model_weights_fn,
distributor,
client_work,
aggregator,
finalizer
)
|
docs/tutorials/composing_learning_algorithms.ipynb
|
tensorflow/federated
|
apache-2.0
|
Running the algorithm
Now that the algorithm is done, let's run it. First, initialize the algorithm. The state of this algorithm has a component for each building block, along with one for the global model weights.
|
state = fed_avg_with_clipping.initialize()
state.client_work
|
docs/tutorials/composing_learning_algorithms.ipynb
|
tensorflow/federated
|
apache-2.0
|
As expected, the client work has an empty state (remember the client work code above!). However, other building blocks may have non-empty state. For example, the finalizer keeps track of how many iterations have occurred. Since next has not been run yet, it has a state of 0.
|
state.finalizer
|
docs/tutorials/composing_learning_algorithms.ipynb
|
tensorflow/federated
|
apache-2.0
|
Now run a training round.
|
learning_process_output = fed_avg_with_clipping.next(state, federated_train_data)
|
docs/tutorials/composing_learning_algorithms.ipynb
|
tensorflow/federated
|
apache-2.0
|
The output of this (tff.learning.templates.LearningProcessOutput) has both a .state and .metrics output. Let's look at both.
|
learning_process_output.state.finalizer
|
docs/tutorials/composing_learning_algorithms.ipynb
|
tensorflow/federated
|
apache-2.0
|
Clearly, the finalizer state has incremented by one, as one round of .next has been run.
|
learning_process_output.metrics
|
docs/tutorials/composing_learning_algorithms.ipynb
|
tensorflow/federated
|
apache-2.0
|
Loop over the table rows and write to CSV
|
# find all table rows (skip the first one)
# open a file to write to
# create a writer object
# write header row
# loop over the rows
# extract the cells
# offense ID
# link to detail page
# last name
# first name
# dob
# sex
# race
# date received
# county
# offense date
# write out to file
|
exercises/20. Exercise - Web scraping-working.ipynb
|
ireapps/cfj-2017
|
mit
|
Let's write a parsing function
We need a function that will take a URL of a detail page and do these things:
Open the detail page URL using requests
Parse the contents using BeautifulSoup
Isolate the bits of information we're interested in: height, weight, eye color, hair color, native county, native state, link to mugshot
Return those bits of information in a dictionary
A couple things to keep in mind: Not every inmate will have every piece of data. Also, not every inmate has an HTML detail page to parse -- the older ones are a picture. So we'll need to work around those limitations.
We shall call our function fetch_details().
|
"""Fetch details from a death row inmate's page."""
# create a dictionary with some default values
# as we go through, we're going to add stuff to it
# (if you want to explore further, there is actually
# a special kind of dictionary called a "defaultdict" to
# handle this use case) =>
# https://docs.python.org/3/library/collections.html#collections.defaultdict
# partway down the page, the links go to JPEGs instead of HTML pages
# we can't parse images, so we'll just return the empty dictionary
# get the page
# soup the HTML
# find the table of info
# target the mugshot, if it exists
# if there is a mug, grab the src and add it to the dictionary
# get a list of the "label" cells
# on some pages, they're identified by the class 'tabledata_bold_align_right_deathrow'
# on others, they're identified by the class 'tabledata_bold_align_right_unit'
# so we pass it a list of possible classes
# gonna do some fanciness here in the interests of DRY =>
# a list of attributes we're interested in -- should match exactly the text inside the cells of interest
# loop over the list of label cells that we targeted earlier
# check to see if the cell text is in our list of attributes
# if so, find the value -- go up to the tr and search for the other td --
# and add that attribute to our dictionary
# return the dictionary to the script
|
exercises/20. Exercise - Web scraping-working.ipynb
|
ireapps/cfj-2017
|
mit
|
Putting it all together
Now that we have our parsing function, we can:
Open and read the CSV files of summary inmate info (the one we just scraped)
Open and write a new CSV file of detailed inmate info
As we loop over the summary inmate data, we're going to call our new parsing function on the detail URL in each row. Then we'll combine the dictionaries (data from the row of summary data + new detailed data) and write out to the new file.
|
# open the CSV file to read from and the one to write to
# create a reader object
# the output headers are goind to be the headers from the summary file
# plus a list of new attributes
# create the writer object
# write the header row
# loop over the rows in the input file
# print the inmate's name (so we can keep track of where we're at)
# helps with debugging, too
# call our function on the URL in the row
# add the two dicts together by
# unpacking them inside a new one
# and write out to file
|
exercises/20. Exercise - Web scraping-working.ipynb
|
ireapps/cfj-2017
|
mit
|
1. Import dataset
|
#Reading the dataset in a dataframe using Pandas
df = pd.read_csv("data.csv")
#Print first observations
df.head()
df.columns
|
Notebooks/3. Dimensionality Reduction.ipynb
|
nvergos/DAT-ATX-1_Project
|
mit
|
Our first collection of feature vectors will come from the Restaurant_Name column. We are still trying to predict whether a restaurant falls under the "pristine" category (Grade A, score greater than 90) or not. We could also try to see whether we could predict a restaurant's grade (A, B, C or F)
2. Dimensionality Reduction Techniques
Restaurant Names as a Bag-of-words model
|
from sklearn.feature_extraction.text import CountVectorizer
# Turn the text documents into vectors
vectorizer = CountVectorizer(min_df=1, stop_words="english")
X = vectorizer.fit_transform(df['Restaurant_Name']).toarray()
y = df['Letter_Grade']
target_names = y.unique()
# Train/Test split and cross validation:
from sklearn import cross_validation
X_train, X_test, y_train, y_test = cross_validation.train_test_split(X, y, train_size = 0.8)
X_train.shape
|
Notebooks/3. Dimensionality Reduction.ipynb
|
nvergos/DAT-ATX-1_Project
|
mit
|
Even though we do not have more features (3430) than rows of data (14888), we can still attempt to reduce the feature space by using Truncated SVD:
Truncated Singular Value Decomposition for Dimensionality Reduction
Once we have extracted a vector representation of the data, it's a good idea to project the data on the first 2D of a Singular Value Decomposition (i.e.. Principal Component Analysis) to get a feel of the data. Note that the TruncatedSVD class can accept scipy.sparse matrices as input (as an alternative to numpy arrays). We will use it to visualize the first two principal components of the vectorized dataset.
|
from sklearn.decomposition import TruncatedSVD
svd_two = TruncatedSVD(n_components=2, random_state=42)
X_train_svd = svd_two.fit_transform(X_train)
pc_df = pd.DataFrame(X_train_svd) # cast resulting matrix as a data frame
sns.pairplot(pc_df, diag_kind='kde');
# Percentage of variance explained for each component
def pca_summary(pca):
return pd.DataFrame([np.sqrt(pca.explained_variance_),
pca.explained_variance_ratio_,
pca.explained_variance_ratio_.cumsum()],
index = ["Standard deviation", "Proportion of Variance", "Cumulative Proportion"],
columns = (map("PC{}".format, range(1, len(pca.components_)+1))))
pca_summary(svd_two)
# Only 3.5% of the variance is explained in the data
svd_two.explained_variance_ratio_.sum()
from itertools import cycle
def plot_PCA_2D(data, target, target_names):
colors = cycle('rgbcmykw')
target_ids = range(len(target_names))
plt.figure()
for i, c, label in zip(target_ids, colors, target_names):
plt.scatter(data[target == i, 0], data[target == i, 1],
c=c, label=label)
plt.legend()
plot_PCA_2D(X_train_svd, y_train, target_names)
|
Notebooks/3. Dimensionality Reduction.ipynb
|
nvergos/DAT-ATX-1_Project
|
mit
|
This must be the most uninformative plot in the history of plots. Obviously 2 principal components aren't enough. Let's try with 100:
|
# Now, let's try with 100 components to see how much it explains
svd_hundred = TruncatedSVD(n_components=100, random_state=42)
X_train_svd_hundred = svd_hundred.fit_transform(X_train)
# 43.7% of the variance is explained in the data for 100 dimensions
# This is mostly due to the High dimension of data and sparcity of the data
svd_hundred.explained_variance_ratio_.sum()
plt.figure(figsize=(10, 7))
plt.bar(range(100), svd_hundred.explained_variance_)
|
Notebooks/3. Dimensionality Reduction.ipynb
|
nvergos/DAT-ATX-1_Project
|
mit
|
Is it worth it to keep adding dimensions? Recall that we started with a 3430-dimensional feature space which we have already reduced to 100 dimensions, and according to the graph above each dimension over the 100th one will be adding less than 0.5% in our explanation of the variance. Let us try once more with 300 dimensions, to see if we can get something respectably over 50% (so we can be sure we are doing better than a coin toss)
|
svd_sparta = TruncatedSVD(n_components=300, random_state=42)
X_train_svd_sparta = svd_sparta.fit_transform(X_train)
X_test_svd_sparta = svd_sparta.fit_transform(X_test)
svd_sparta.explained_variance_ratio_.sum()
|
Notebooks/3. Dimensionality Reduction.ipynb
|
nvergos/DAT-ATX-1_Project
|
mit
|
66.2% of the variance is explained through our model. This is quite respectable.
|
plt.figure(figsize=(10, 7))
plt.bar(range(300), svd_sparta.explained_variance_)
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_extraction.text import CountVectorizer
from sklearn import cross_validation
from sklearn.naive_bayes import MultinomialNB
# Fit a classifier on the training set
classifier = MultinomialNB().fit(np.absolute(X_train_svd_sparta), y_train)
print("Training score: {0:.1f}%".format(
classifier.score(X_train_svd_sparta, y_train) * 100))
# Evaluate the classifier on the testing set
print("Testing score: {0:.1f}%".format(
classifier.score(X_test_svd_sparta, y_test) * 100))
|
Notebooks/3. Dimensionality Reduction.ipynb
|
nvergos/DAT-ATX-1_Project
|
mit
|
Restaurant Streets as a Bag-of-words model
|
streets = df['Geocode'].apply(pd.Series)
streets = df['Geocode'].tolist()
split_streets = [i.split(' ', 1)[1] for i in streets]
split_streets = [i.split(' ', 1)[1] for i in split_streets]
split_streets = [i.split(' ', 1)[0] for i in split_streets]
split_streets[0]
import re
shortword = re.compile(r'\W*\b\w{1,3}\b')
for i in range(len(split_streets)):
split_streets[i] = shortword.sub('', split_streets[i])
# Create a new column with the street:
df['Street_Words'] = split_streets
from sklearn.feature_extraction.text import CountVectorizer
# Turn the text documents into vectors
vectorizer = CountVectorizer(min_df=1, stop_words="english")
X = vectorizer.fit_transform(df['Street_Words']).toarray()
y = df['Letter_Grade']
target_names = y.unique()
# Train/Test split and cross validation:
from sklearn import cross_validation
X_train, X_test, y_train, y_test = cross_validation.train_test_split(X, y, train_size = 0.8)
X_train.shape
from sklearn.decomposition import TruncatedSVD
svd_two = TruncatedSVD(n_components=2, random_state=42)
X_train_svd = svd_two.fit_transform(X_train)
pc_df = pd.DataFrame(X_train_svd) # cast resulting matrix as a data frame
sns.pairplot(pc_df, diag_kind='kde');
pca_summary(svd_two)
# 25% of the variance is explained in the data when we use only TWO principal components!
svd_two.explained_variance_ratio_.sum()
# Now, let's try with 10 components to see how much it explains
svd_ten = TruncatedSVD(n_components=10, random_state=42)
X_train_svd_ten = svd_ten.fit_transform(X_train)
# 53.9% of the variance is explained in the data for 10 dimensions
# This is mostly due to the High dimension of data and sparcity of the data
svd_ten.explained_variance_ratio_.sum()
|
Notebooks/3. Dimensionality Reduction.ipynb
|
nvergos/DAT-ATX-1_Project
|
mit
|
Eager execution
Note: you can run this notebook, live in Google Colab with zero setup.
TensorFlow Dev Summit, 2018.
This interactive notebook demonstrates eager execution, TensorFlow's imperative, NumPy-like front-end for machine learning.
Table of Contents.
1. Enabling eager execution!
2. A NumPy-like library for numerical computation and machine learning. Case study: Fitting a huber regression.
3. Neural networks. Case study: Training a multi-layer RNN.
4. Exercises: Batching; debugging.
5. Further reading
1. Enabling eager execution!
A single function call is all you need to enable eager execution: tf.enable_eager_execution(). You should invoke this function before calling into any other TensorFlow APIs --- the simplest way to satisfy this requirement is to make tf.enable_eager_execution() the first line of your main function.
|
!pip install -q -U tf-nightly
import tensorflow as tf
tf.enable_eager_execution()
|
v0.5.0/google/cloud_v3.8/resnet-tpuv3-8/code/resnet/model/models/samples/outreach/demos/eager_execution.ipynb
|
mlperf/training_results_v0.5
|
apache-2.0
|
2. A NumPy-like library for numerical computation and machine learning
Enabling eager execution transforms TensorFlow into an imperative library for numerical computation, automatic differentiation, and machine learning. When executing eagerly, TensorFlow no longer behaves like a dataflow graph engine: Tensors are backed by NumPy arrays (goodbye, placeholders!), and TensorFlow operations execute immediately via Python (goodbye, sessions!).
Numpy-like usage
Tensors are backed by numpy arrays, which are accessible via their .numpy()
method.
|
A = tf.constant([[2.0, 0.0], [0.0, 3.0]])
import numpy as np
print("Tensors are backed by NumPy arrays, which are accessible through their "
"`.numpy()` method:\n", A)
assert(type(A.numpy()) == np.ndarray)
print("\nOperations (like `tf.matmul(A, A)`) execute "
"immediately (no more Sessions!):\n", tf.matmul(A, A))
|
v0.5.0/google/cloud_v3.8/resnet-tpuv3-8/code/resnet/model/models/samples/outreach/demos/eager_execution.ipynb
|
mlperf/training_results_v0.5
|
apache-2.0
|
Tensors behave similarly to NumPy arrays, but they don't behave exactly the
same.
For example, the equals operator on Tensors compares objects. Use
tf.equal to compare values.
|
print("\nTensors behave like NumPy arrays: you can iterate over them and "
"supply them as inputs to most functions that expect NumPy arrays:")
for i, row in enumerate(A):
for j, entry in enumerate(row):
print("A[%d, %d]^2 == %d" % (i, j, np.square(entry)))
|
v0.5.0/google/cloud_v3.8/resnet-tpuv3-8/code/resnet/model/models/samples/outreach/demos/eager_execution.ipynb
|
mlperf/training_results_v0.5
|
apache-2.0
|
Variables and Gradients
Create variables with tf.contrib.eager.Variable, and use tf.GradientTape
to compute gradients with respect to them.
|
import tensorflow.contrib.eager as tfe
w = tfe.Variable(3.0)
with tf.GradientTape() as tape:
loss = w ** 2
dw, = tape.gradient(loss, [w])
print("\nYou can use `tf.GradientTape` to compute the gradient of a "
"computation with respect to a list of `tf.contrib.eager.Variable`s;\n"
"for example, `tape.gradient(loss, [w])`, where `loss` = w ** 2 and "
"`w` == 3.0, yields`", dw,"`.")
|
v0.5.0/google/cloud_v3.8/resnet-tpuv3-8/code/resnet/model/models/samples/outreach/demos/eager_execution.ipynb
|
mlperf/training_results_v0.5
|
apache-2.0
|
GPU usage
Eager execution lets you offload computation to hardware accelerators like
GPUs, if you have any available.
|
if tf.test.is_gpu_available():
with tf.device(tf.test.gpu_device_name()):
B = tf.constant([[2.0, 0.0], [0.0, 3.0]])
print(tf.matmul(B, B))
|
v0.5.0/google/cloud_v3.8/resnet-tpuv3-8/code/resnet/model/models/samples/outreach/demos/eager_execution.ipynb
|
mlperf/training_results_v0.5
|
apache-2.0
|
Fitting a Huber regression
If you come from a scientific or numerical computing background, eager execution should feel natural to you. Not only does it stand on its own as an accelerator-compatible library for numerical computation, it also interoperates with popular Python packages like NumPy and Matplotlib. To demonstrate this fact, in this section, we fit and evaluate a regression using a Huber regression, writing our code in a NumPy-like way and making use of Python control flow.
Data generation
Our dataset for this example has many outliers — least-squares would be a poor choice.
|
import matplotlib.pyplot as plt
def gen_regression_data(num_examples=1000, p=0.2):
X = tf.random_uniform(shape=(num_examples,), maxval=50)
w_star = tf.random_uniform(shape=(), maxval=10)
b_star = tf.random_uniform(shape=(), maxval=10)
noise = tf.random_normal(shape=(num_examples,), mean=0.0, stddev=10.0)
# With probability 1 - p, y := y * -1.
sign = 2 * np.random.binomial(1, 1 - p, size=(num_examples,)) - 1
# You can freely mix Tensors and NumPy arrays in your computations:
# `sign` is a NumPy array, but the other symbols below are Tensors.
Y = sign * (w_star * X + b_star + noise)
return X, Y
X, Y = gen_regression_data()
plt.plot(X, Y, "go") # You can plot Tensors!
plt.title("Observed data")
plt.show()
|
v0.5.0/google/cloud_v3.8/resnet-tpuv3-8/code/resnet/model/models/samples/outreach/demos/eager_execution.ipynb
|
mlperf/training_results_v0.5
|
apache-2.0
|
Huber loss
The Huber loss function is piecewise function that is quadratic for small inputs and linear otherwise; for that reason, using a Huber loss gives considerably less weight to outliers than least-squares does. When eager execution is enabled, we can implement the Huber function in the natural way, using Python control flow.
|
def huber_loss(y, y_hat, m=1.0):
# Enabling eager execution lets you use Python control flow.
delta = tf.abs(y - y_hat)
return delta ** 2 if delta <= m else m * (2 * delta - m)
|
v0.5.0/google/cloud_v3.8/resnet-tpuv3-8/code/resnet/model/models/samples/outreach/demos/eager_execution.ipynb
|
mlperf/training_results_v0.5
|
apache-2.0
|
A simple class for regressions
The next cell encapsulates a linear regression model in a Python class and defines a
function that fits the model using a stochastic optimizer.
|
import time
from google.colab import widgets
import tensorflow.contrib.eager as tfe # Needed to create tfe.Variable objects.
class Regression(object):
def __init__(self, loss_fn):
super(Regression, self).__init__()
self.w = tfe.Variable(0.0)
self.b = tfe.Variable(0.0)
self.variables = [self.w, self.b]
self.loss_fn = loss_fn
def predict(self, x):
return x * self.w + self.b
def regress(model, optimizer, dataset, epochs=5, log_every=1, num_examples=1000):
plot = log_every is not None
if plot:
# Colab provides several widgets for interactive visualization.
tb = widgets.TabBar([str(i) for i in range(epochs) if i % log_every == 0])
X, Y = dataset.batch(num_examples).make_one_shot_iterator().get_next()
X = tf.reshape(X, (num_examples,))
Y = tf.reshape(Y, (num_examples,))
for epoch in range(epochs):
iterator = dataset.make_one_shot_iterator()
epoch_loss = 0.0
start = time.time()
for x_i, y_i in iterator:
batch_loss_fn = lambda: model.loss_fn(y_i, model.predict(x_i))
optimizer.minimize(batch_loss_fn, var_list=model.variables)
epoch_loss += batch_loss_fn()
duration = time.time() - start
if plot and epoch % log_every == 0:
with tb.output_to(str(epoch)):
print("Epoch %d took %0.2f seconds, resulting in a loss of %0.4f." % (
epoch, duration, epoch_loss))
plt.plot(X, Y, "go", label="data")
plt.plot(X, model.predict(X), "b", label="regression")
plt.legend()
|
v0.5.0/google/cloud_v3.8/resnet-tpuv3-8/code/resnet/model/models/samples/outreach/demos/eager_execution.ipynb
|
mlperf/training_results_v0.5
|
apache-2.0
|
Run the following cell to fit the model! Note that enabling eager execution makes it
easy to visualize your model while training it, using familiar tools like Matplotlib.
|
huber_regression = Regression(huber_loss)
dataset = tf.data.Dataset.from_tensor_slices((X, Y))
regress(huber_regression,
optimizer=tf.train.GradientDescentOptimizer(learning_rate=0.0001),
dataset=dataset)
|
v0.5.0/google/cloud_v3.8/resnet-tpuv3-8/code/resnet/model/models/samples/outreach/demos/eager_execution.ipynb
|
mlperf/training_results_v0.5
|
apache-2.0
|
Debugging and profiling
Enabling eager execution lets you debug your code on-the-fly; use pdb and print statements to your heart's content.
Check out exercise 2 towards the bottom of this notebook for a hands-on look at how eager simplifies model debugging.
|
import pdb
def buggy_loss(y, y_hat):
pdb.set_trace()
huber_loss(y, y_hat)
print("Type 'exit' to stop the debugger, or 's' to step into `huber_loss` and "
"'n' to step through it.")
try:
buggy_loss(1.0, 2.0)
except:
pass
|
v0.5.0/google/cloud_v3.8/resnet-tpuv3-8/code/resnet/model/models/samples/outreach/demos/eager_execution.ipynb
|
mlperf/training_results_v0.5
|
apache-2.0
|
Leverage the Python profiler to dig into the relative costs of training your model.
If you run the below cell, you'll see that most of the time is spent computing gradients and binary operations, which is sensible considering our loss function.
|
import cProfile
import pstats
huber_regression = Regression(huber_loss)
cProfile.run(
"regress(model=huber_regression, "
"optimizer=tf.train.GradientDescentOptimizer(learning_rate=0.001), "
"dataset=dataset, log_every=None)", "prof")
pstats.Stats("prof").strip_dirs().sort_stats("cumulative").print_stats(10)
print("Most of the time is spent during backpropagation and binary operations.")
|
v0.5.0/google/cloud_v3.8/resnet-tpuv3-8/code/resnet/model/models/samples/outreach/demos/eager_execution.ipynb
|
mlperf/training_results_v0.5
|
apache-2.0
|
3. Neural networks
While eager execution can certainly be used as a library for numerical computation, it shines as a library for deep learning: TensorFlow provides a suite of tools for deep learning research and development, most of which are compatible with eager execution. In this section, we put some of these tools to use to build RNNColorbot, an RNN that takes as input names of colors and predicts their corresponding RGB tuples.
Constructing a data pipeline
tf.data is TensorFlow's canonical API for constructing input pipelines. tf.data lets you easily construct multi-stage pipelines that supply data to your networks during training and inference. The following cells defines methods that download and format the data needed for RNNColorbot; the details aren't important (read them in the privacy of your own home if you so wish), but make sure to run the cells before proceeding.
|
import os
import six
from six.moves import urllib
def parse(line):
"""Parse a line from the colors dataset."""
# `items` is a list [color_name, r, g, b].
items = tf.string_split([line], ",").values
rgb = tf.string_to_number(items[1:], out_type=tf.float32) / 255.
color_name = items[0]
chars = tf.one_hot(tf.decode_raw(color_name, tf.uint8), depth=256)
length = tf.cast(tf.shape(chars)[0], dtype=tf.int64)
return rgb, chars, length
def load_dataset(data_dir, url, batch_size):
"""Loads the colors data at path into a PaddedDataset."""
path = tf.keras.utils.get_file(os.path.basename(url), url, cache_dir=data_dir)
dataset = tf.data.TextLineDataset(path).skip(1).map(parse).shuffle(
buffer_size=10000).padded_batch(batch_size,
padded_shapes=([None], [None, None], []))
return dataset, path
train_url = "https://raw.githubusercontent.com/random-forests/tensorflow-workshop/master/extras/colorbot/data/train.csv"
test_url = "https://raw.githubusercontent.com/random-forests/tensorflow-workshop/master/extras/colorbot/data/test.csv"
data_dir = "/tmp/rnn/data"
train_data, train_path = load_dataset(data_dir, train_url, batch_size=64)
eval_data, _ = load_dataset(data_dir, test_url, batch_size=64)
import pandas
pandas.read_csv(train_path).head(10)
colors, one_hot_chars, lengths = tfe.Iterator(train_data).next()
colors[:10].numpy()
|
v0.5.0/google/cloud_v3.8/resnet-tpuv3-8/code/resnet/model/models/samples/outreach/demos/eager_execution.ipynb
|
mlperf/training_results_v0.5
|
apache-2.0
|
Defining and training a neural network
TensorFlow packages several APIs for creating neural networks in a modular fashion. The canonical way to define neural networks in TensorFlow is to encapsulate your model in a class that inherits from tf.keras.Model. You should think of tf.keras.Model as a container of object-oriented layers, TensorFlow's building blocks for constructing neural networks (e.g., tf.layers.Dense, tf.layers.Conv2D). Every Layer object that is set as an attribute of a Model is automatically tracked by the latter, letting you access Layer-contained variables by invoking Model's .variables() method. Most important, inheriting from tf.keras.Model makes it easy to checkpoint your model and to subsequently restore it --- more on that later.
The following cell exemplifies our high-level neural network APIs. Note that RNNColorbot encapsulates only the model definition and prediction generation logic. The loss, training, and evaluation functions exist outside the class definition: conceptually, the model doesn't need know how to train and benchmark itself.
|
class RNNColorbot(tf.keras.Model):
"""Multi-layer RNN that predicts RGB tuples given color names.
"""
def __init__(self):
super(RNNColorbot, self).__init__()
self.keep_prob = 0.5
self.lower_cell = tf.contrib.rnn.LSTMBlockCell(256)
self.upper_cell = tf.contrib.rnn.LSTMBlockCell(128)
self.relu = tf.layers.Dense(3, activation=tf.nn.relu, name="relu")
def call(self, inputs, training=False):
"""Generates RGB tuples from `inputs`, a tuple (`chars`, `sequence_length`).
"""
(chars, sequence_length) = inputs
chars = tf.transpose(chars, [1, 0, 2]) # make `chars` time-major
batch_size = int(chars.shape[1])
for cell in [self.lower_cell, self.upper_cell]:
outputs = []
state = cell.zero_state(batch_size, tf.float32)
for ch in chars:
output, state = cell(ch, state)
outputs.append(output)
chars = outputs
if training:
chars = tf.nn.dropout(chars, self.keep_prob)
batch_range = [i for i in range(batch_size)]
indices = tf.stack([sequence_length - 1, batch_range], axis=1)
hidden_states = tf.gather_nd(chars, indices)
return self.relu(hidden_states)
def loss_fn(labels, predictions):
return tf.reduce_mean((predictions - labels) ** 2)
def train_one_epoch(model, optimizer, train_data, log_every=10):
iterator = tfe.Iterator(train_data)
for batch,(labels, chars, sequence_length) in enumerate(iterator):
with tf.GradientTape() as tape:
predictions = model((chars, sequence_length), training=True)
loss = loss_fn(labels, predictions)
variables = model.variables
grad = tape.gradient(loss, variables)
optimizer.apply_gradients([(g, v) for g, v in zip(grad, variables)])
if log_every and batch % log_every == 0:
print("train/batch #%d\tloss: %.6f" % (batch, loss))
batch += 1
def test(model, eval_data):
total_loss = 0.0
iterator = eval_data.make_one_shot_iterator()
for labels, chars, sequence_length in tfe.Iterator(eval_data):
predictions = model((chars, sequence_length), training=False)
total_loss += loss_fn(labels, predictions)
print("eval/loss: %.6f\n" % total_loss)
|
v0.5.0/google/cloud_v3.8/resnet-tpuv3-8/code/resnet/model/models/samples/outreach/demos/eager_execution.ipynb
|
mlperf/training_results_v0.5
|
apache-2.0
|
The next cell trains our RNNColorbot, restoring and saving checkpoints of the learned variables along the way. Thanks to checkpointing, every run of the below cell will resume training from wherever the previous run left off. For more on checkpointing, take a look at our user guide.
|
model = RNNColorbot()
optimizer = tf.train.AdamOptimizer(learning_rate=.01)
# Create a `Checkpoint` for saving and restoring state; the keywords
# supplied `Checkpoint`'s constructor are the names of the objects to be saved
# and restored, and their corresponding values are the actual objects. Note
# that we're saving `optimizer` in addition to `model`, since `AdamOptimizer`
# maintains state.
import tensorflow.contrib.eager as tfe
checkpoint = tfe.Checkpoint(model=model, optimizer=optimizer)
checkpoint_prefix = "/tmp/rnn/ckpt"
# The next line loads the most recent checkpoint, if any.
checkpoint.restore(tf.train.latest_checkpoint("/tmp/rnn"))
for epoch in range(4):
train_one_epoch(model, optimizer, train_data)
test(model, eval_data)
checkpoint.save(checkpoint_prefix)
print("Colorbot is ready to generate colors!")
|
v0.5.0/google/cloud_v3.8/resnet-tpuv3-8/code/resnet/model/models/samples/outreach/demos/eager_execution.ipynb
|
mlperf/training_results_v0.5
|
apache-2.0
|
Paint me a color, Colorbot!
We can interact with RNNColorbot in a natural way; no need to thread NumPy arrays into placeholders through feed dicts.
So go ahead and ask RNNColorbot to paint you some colors. If they're not to your liking, re-run the previous cell to resume training from where we left off, and then re-run the next one for updated results.
|
tb = widgets.TabBar(["RNN Colorbot"])
while True:
with tb.output_to(0):
try:
color_name = six.moves.input(
"Give me a color name (or press 'enter' to exit): ")
except (EOFError, KeyboardInterrupt):
break
if not color_name:
break
_, chars, length = parse(color_name)
preds, = model((np.expand_dims(chars, 0), np.expand_dims(length, 0)),
training=False)
clipped_preds = tuple(min(float(p), 1.0) for p in preds)
rgb = tuple(int(p * 255) for p in clipped_preds)
with tb.output_to(0):
tb.clear_tab()
print("Predicted RGB tuple:", rgb)
plt.imshow([[clipped_preds]])
plt.title(color_name)
plt.show()
|
v0.5.0/google/cloud_v3.8/resnet-tpuv3-8/code/resnet/model/models/samples/outreach/demos/eager_execution.ipynb
|
mlperf/training_results_v0.5
|
apache-2.0
|
4. Exercises
Exercise 1: Batching
Executing operations eagerly incurs small overheads; these overheads become neglible when amortized over batched operations. In this exercise, we explore the relationship between batching and performance by revisiting our Huber regression example.
|
# Our original implementation of `huber_loss` is not compatible with non-scalar
# data. Your task is to fix that. For your convenience, the original
# implementation is reproduced below.
#
# def huber_loss(y, y_hat, m=1.0):
# delta = tf.abs(y - y_hat)
# return delta ** 2 if delta <= m else m * (2 * delta - m)
#
def batched_huber_loss(y, y_hat, m=1.0):
# TODO: Uncomment out the below code and replace `...` with your solution.
# Hint: Tensors are immutable.
# Hint: `tf.where` might be useful.
delta = tf.abs(y - y_hat)
# ...
# ...
# return ...
regression = Regression(batched_huber_loss)
num_epochs = 4
batch_sizes = [1, 10, 20, 100, 200, 500, 1000]
times = []
X, Y = gen_regression_data(num_examples=1000)
dataset = tf.data.Dataset.from_tensor_slices((X, Y))
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.0001)
for size in batch_sizes:
batched_dataset = dataset.batch(size)
start = time.time()
regress(model=regression, optimizer=optimizer, dataset=batched_dataset,
epochs=num_epochs, log_every=None)
end = time.time()
times.append((end - start) / num_epochs)
regression.w.assign(0.0)
regression.b.assign(0.0)
plt.figure()
plt.plot(batch_sizes, times, "bo")
plt.xlabel("batch size")
plt.ylabel("time (seconds)")
plt.semilogx()
plt.semilogy()
plt.title("Time per Epoch vs. Batch Size")
plt.show()
|
v0.5.0/google/cloud_v3.8/resnet-tpuv3-8/code/resnet/model/models/samples/outreach/demos/eager_execution.ipynb
|
mlperf/training_results_v0.5
|
apache-2.0
|
Solution
|
def batched_huber_loss(y, y_hat, m=1.0):
delta = tf.abs(y - y_hat)
quadratic = delta ** 2
linear = m * (2 * delta - m)
return tf.reduce_mean(tf.where(delta <= m, quadratic, linear))
regression = Regression(batched_huber_loss)
num_epochs = 4
batch_sizes = [2, 10, 20, 100, 200, 500, 1000]
times = []
X, Y = gen_regression_data(num_examples=1000)
dataset = tf.data.Dataset.from_tensor_slices((X, Y))
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.0001)
for size in batch_sizes:
batched_dataset = dataset.batch(size)
start = time.time()
regress(model=regression, optimizer=optimizer, dataset=batched_dataset,
epochs=num_epochs, log_every=None)
end = time.time()
times.append((end - start) / num_epochs)
regression.w.assign(0.0)
regression.b.assign(0.0)
plt.figure()
plt.plot(batch_sizes, times, "bo")
plt.xlabel("batch size")
plt.ylabel("time (seconds)")
plt.semilogx()
plt.semilogy()
plt.title("Time per Epoch vs. Batch Size")
plt.show()
|
v0.5.0/google/cloud_v3.8/resnet-tpuv3-8/code/resnet/model/models/samples/outreach/demos/eager_execution.ipynb
|
mlperf/training_results_v0.5
|
apache-2.0
|
Exercise 2: Model Debugging
We've heard you loud and clear: TensorFlow programs that construct and execute graphs are difficult to debug. By design, enabling eager execution vastly simplifies the process of debugging TensorFlow programs. Once eager execution is enabled, you can step through your models using pdb and bisect them with print statements. The best way to understand the extent to which eager execution simplifies debugging is to debug a model yourself. BuggyModel below has two bugs lurking in it. Execute the following cell, read the error message, and go hunt some bugs!
Hint: As is often the case with TensorFlow programs, both bugs are related to the shapes of Tensors.
Hint: You might find tf.layers.flatten useful.
|
class BuggyModel(tf.keras.Model):
def __init__(self):
super(BuggyModel, self).__init__()
self._input_shape = [-1, 28, 28, 1]
self.conv = tf.layers.Conv2D(filters=32, kernel_size=5, padding="same",
data_format="channels_last")
self.fc = tf.layers.Dense(10)
self.max_pool2d = tf.layers.MaxPooling2D(
(2, 2), (2, 2), padding="same", data_format="channels_last")
def call(self, inputs):
y = inputs
y = self.conv(y)
y = self.max_pool2d(y)
return self.fc(y)
buggy_model = BuggyModel()
inputs = tf.random_normal(shape=(100, 28, 28))
outputs = buggy_model(inputs)
assert outputs.shape == (100, 10), "invalid output shape: %s" % outputs.shape
|
v0.5.0/google/cloud_v3.8/resnet-tpuv3-8/code/resnet/model/models/samples/outreach/demos/eager_execution.ipynb
|
mlperf/training_results_v0.5
|
apache-2.0
|
Solution
|
class BuggyModel(tf.keras.Model):
def __init__(self):
super(BuggyModel, self).__init__()
self._input_shape = [-1, 28, 28, 1]
self.conv = tf.layers.Conv2D(filters=32, kernel_size=5, padding="same",
data_format="channels_last")
self.fc = tf.layers.Dense(10)
self.max_pool2d = tf.layers.MaxPooling2D(
(2, 2), (2, 2), padding="same", data_format="channels_last")
def call(self, inputs):
y = tf.reshape(inputs, self._input_shape)
y = self.conv(y)
y = self.max_pool2d(y)
y = tf.layers.flatten(y)
return self.fc(y)
buggy_model = BuggyModel()
inputs = tf.random_normal(shape=(100, 28, 28))
outputs = buggy_model(inputs)
assert outputs.shape == (100, 10), "invalid output shape: %s" % outputs.shape
|
v0.5.0/google/cloud_v3.8/resnet-tpuv3-8/code/resnet/model/models/samples/outreach/demos/eager_execution.ipynb
|
mlperf/training_results_v0.5
|
apache-2.0
|
First, let's create a random graph
We will start with the connected Watts Strogatz random graph, created using the NetworkX package. This graph generator will allow us to create random graphs which are guaranteed to be fully connected, and gives us control over how connected the graph is, and how structured it is. Documentation for the function can be found here https://networkx.github.io/documentation/latest/reference/generated/networkx.generators.random_graphs.connected_watts_strogatz_graph.html#networkx.generators.random_graphs.connected_watts_strogatz_graph
<img src="screenshots/connected_watts_strogatz_graph_nx_docs.png" width="600" height="600">
Control localization
We can control the localization of nodes by seeding the network propagation with a focal node and that focal node's neighbors. This will guarantee that the seed nodes will be very localized in the graph
As a first example, let's create a random network, with two localized sets.
The network contains 100 nodes, with each node first connected to its 5 nearest neighbors.
Once these first edges are connected, each edge is randomly rewired with probability p = 0.12 (so approximately 12 percent of the edges in the graph will be rewired)
With this rewiring probability of 0.12, most of the structure in the graph is maintained, but some randomness has been introduced
|
# Create a random connected-Watts-Strogatz graph
Gsim = nx.connected_watts_strogatz_graph(100,5,.12)
seed1 = [0]
seed1.extend(nx.neighbors(Gsim,seed1[0]))
seed2 = [10]
seed2.extend(nx.neighbors(Gsim,seed2[0]))
#seed = list(np.random.choice(Gsim.nodes(),size=6,replace=False))
pos = nx.spring_layout(Gsim)
nx.draw_networkx_nodes(Gsim,pos=pos,node_size=100,alpha=.5,node_color = 'blue')
nx.draw_networkx_nodes(Gsim,pos=pos,nodelist=seed1,node_size=120,alpha=.9,node_color='orange',linewidths=3)
nx.draw_networkx_nodes(Gsim,pos=pos,nodelist=seed2,node_size=120,alpha=.9,node_color='red',linewidths=3)
nx.draw_networkx_edges(Gsim,pos=pos,alpha=.1)
plt.grid('off')
#plt.savefig('/Users/brin/Google Drive/UCSD/update_16_03/non_colocalization_illustration.png',dpi=300,bbox_inches='tight')
|
notebooks/networkAnalysis/localization_colocalization_example/localization_colocalization_example.ipynb
|
ucsd-ccbb/jupyter-genomics
|
mit
|
In the network shown above, we plot our random connected Watts-Strogatz graph, highlighting two localized seed node sets, shown in red and orange, with bold outlines.
These seed node sets were created by selecting two focal node, and those focal node's neighbors, thus resulting in two node sets which appear highly localized to the eye.
Since the graph is composed of nearest neighbor relations (with some randomness added on), and it was initiated with node ids ranging from 0 to 99 (these are the default node names- they can be changed using nx.relabel_nodes()), we can control the co-localization of these node sets by selecting seed nodes which are close together, for high co-localization (e.g. 0 and 5), or which are far apart, for low co-localization (e.g. 0 and 50).
Below, we will display node sets with both high and low co-localization
Our ability to control the co-localization in this way will become worse as the rewiring probability increases, and the structure in the graph is destroyed.
|
# highly co-localized gene sets
seed1 = [0]
seed1.extend(nx.neighbors(Gsim,seed1[0]))
seed2 = [5]
seed2.extend(nx.neighbors(Gsim,seed2[0]))
#seed = list(np.random.choice(Gsim.nodes(),size=6,replace=False))
plt.figure(figsize=(12,5))
plt.subplot(1,2,1)
nx.draw_networkx_nodes(Gsim,pos=pos,node_size=100,alpha=.5,node_color = 'blue')
nx.draw_networkx_nodes(Gsim,pos=pos,nodelist=seed1,node_size=120,alpha=.9,node_color='orange',linewidths=3)
nx.draw_networkx_nodes(Gsim,pos=pos,nodelist=seed2,node_size=120,alpha=.9,node_color='red',linewidths=3)
nx.draw_networkx_edges(Gsim,pos=pos,alpha=.1)
plt.title('High Co-localization',fontsize=16)
plt.grid('off')
# low co-localized gene sets
seed1 = [5]
seed1.extend(nx.neighbors(Gsim,seed1[0]))
seed2 = [30]
seed2.extend(nx.neighbors(Gsim,seed2[0]))
#seed = list(np.random.choice(Gsim.nodes(),size=6,replace=False))
plt.subplot(1,2,2)
nx.draw_networkx_nodes(Gsim,pos=pos,node_size=100,alpha=.5,node_color = 'blue')
nx.draw_networkx_nodes(Gsim,pos=pos,nodelist=seed1,node_size=120,alpha=.9,node_color='orange',linewidths=3)
nx.draw_networkx_nodes(Gsim,pos=pos,nodelist=seed2,node_size=120,alpha=.9,node_color='red',linewidths=3)
nx.draw_networkx_edges(Gsim,pos=pos,alpha=.1)
plt.title('Low Co-localization',fontsize=16)
plt.grid('off')
|
notebooks/networkAnalysis/localization_colocalization_example/localization_colocalization_example.ipynb
|
ucsd-ccbb/jupyter-genomics
|
mit
|
Can we quantify this concept of localization?
Sometimes it's not easy to tell by eye if a node set is localized.
We can use network propagation simulations to quantify this concept of localization
Network propagation is a tool which initiates a seed node set with high 'heat', and then over the course of a number of iterations spreads this heat around to nearby nodes.
At the end of the simulation, nodes with the highest heat are those which are most closely related to the seed nodes.
We implemented the network propagation method described in Vanunu et. al. 2010 (Vanunu, Oron, et al. "Associating genes and protein complexes with disease via network propagation." PLoS Comput Biol 6.1 (2010): e1000641.)
<img src="screenshots/vanunu_abstracg.png">
Localization using network propagation
We can use network propagation to evaluate how localized a seed node set is in the network.
If the seed node set is highly localized, the 'heat' from the network propagation simulation will be bounced around between seed nodes, and less of it will dissipate to distant parts of the network.
We will evaluate the distribution of the heat from all the nodes, using the kurtosis (the fourth standardized moment), which measures how 'tailed' the distribution is. If our distribution has high kurtosis, this indicates that much of the 'heat' has stayed localized near the seed set. If our distribution has a low kurtosis, this indicates that the 'heat' has not stayed localized, but has diffused to distant parts of the network.
<img src="screenshots/kurtosis.png">
Random baseline for comparison
To evaluate localization in this way, we need a baseline to compare to.
Te establish the baseline we take our original network, and shuffle the edges, while preserving degree (so nodes which originally had 5 neighbors will still have 5 neighbors, although these neighbors will now be spread randomly throughout the graph)
For example, below we show the heat propagation on a non-shuffled graph, from a localized seed set (left), and the heat propagation from the same seed set, on an edge-shuffled graph (right). The nodes on the left and right have the same number of neighbors, but they have different identities.
The total amount of heat in the graph is conserved in both cases, but the heat distributions look very different- the seed nodes retain much less of their original heat in the edge-shuffled case.
<img src="screenshots/L_edge_shuffled.png">
We will calculate the kurtosis of the heat distribution over a large number of different edge-shuffled networks (below- 1000 repetitions), to build up the baseline distribution of kurtosis values.
|
Wprime_ring = network_prop.normalized_adj_matrix(Gsim)
Fnew_ring = network_prop.network_propagation(Gsim,Wprime_ring,seed1)
plt.figure(figsize=(18,5))
plt.subplot(1,3,1)
nx.draw_networkx_nodes(Gsim,pos=pos,node_size=100,alpha=.5,node_color=Fnew_ring[Gsim.nodes()],cmap='jet',
vmin=0,vmax=max(Fnew_ring))
nx.draw_networkx_edges(Gsim,pos=pos,alpha=.2)
var_ring = plotting_results.nsf(np.var(Fnew_ring),3)
kurt_ring = plotting_results.nsf(scipy.stats.kurtosis(Fnew_ring),3)
plt.annotate('kurtosis = ' + str(kurt_ring),
xy=(.08,.1),xycoords='figure fraction')
plt.annotate('Heat: original',xy=(.08,.93),xycoords='figure fraction',fontsize=16)
plt.xticks([],[])
plt.yticks([],[])
plt.grid('off')
num_reps = 1000
var_rand_list,kurt_rand_list = [],[]
for r in range(num_reps):
G_temp = nx.configuration_model(Gsim.degree().values())
G_rand = nx.Graph() # switch from multigraph to digraph
G_rand.add_edges_from(G_temp.edges())
G_rand = nx.relabel_nodes(G_rand,dict(zip(range(len(G_rand.nodes())),Gsim.degree().keys())))
Wprime_rand = network_prop.normalized_adj_matrix(G_rand)
Fnew_rand = network_prop.network_propagation(G_rand,Wprime_rand,seed1)
var_rand_list.append(np.var(Fnew_rand))
kurt_rand_list.append(scipy.stats.kurtosis(Fnew_rand))
plt.subplot(1,3,2)
nx.draw_networkx_nodes(G_rand,pos=pos,node_size=100,alpha=.5,node_color=Fnew_rand[G_rand.nodes()],cmap='jet',
vmin=0,vmax=max(Fnew_ring))
nx.draw_networkx_edges(G_rand,pos=pos,alpha=.2)
var_rand = plotting_results.nsf(np.var(Fnew_rand),3)
kurt_rand = plotting_results.nsf(scipy.stats.kurtosis(Fnew_rand),3)
plt.annotate('kurtosis = ' + str(kurt_rand),
xy=(.40,.1),xycoords='figure fraction')
plt.annotate('Heat: edge-shuffled',xy=(.40,.93),xycoords='figure fraction',fontsize=16)
plt.xticks([],[])
plt.yticks([],[])
plt.grid('off')
plt.subplot(1,3,3)
plt.boxplot(kurt_rand_list)
z_score = (kurt_ring-np.mean(kurt_rand_list))/np.std(kurt_rand_list)
z_score = plotting_results.nsf(z_score,n=2)
plt.plot(1,kurt_ring,'*',color='darkorange',markersize=16,label='original: \nz-score = '+ str(z_score))
plt.annotate('Kurtosis',xy=(.73,.93),xycoords='figure fraction',fontsize=16)
plt.legend(loc='lower left')
#plt.savefig('/Users/brin/Google Drive/UCSD/update_16_03/localization_NWS_p1_variance.png',dpi=300,bbox_inches='tight')
|
notebooks/networkAnalysis/localization_colocalization_example/localization_colocalization_example.ipynb
|
ucsd-ccbb/jupyter-genomics
|
mit
|
Above (right panel) we see that when a node set is highly localized, it has a higher kurtosis value than would be expected from a non-localized gene set (the orange star represents the kurtosis of the heat distribution on the original graph, and the boxplot represents the distribution of 1000 kurtosis values on edge-shuffled networks). The orange star is significantly higher than the baseline distribution.
Co-localization using network propagation
We now build on our understanding of localization using network propagation to establish a measurement of how co-localized two node sets are in a network.
In the first example we discussed (above), we came up with a general understanding of co-localization, where two node sets were co-localized if they were individually localized, and were nearby in network space.
In order to measure this co-localization using network propagation, we will first seed 2 simulations with each node set, then we will take the dot-product (or the sum of the pairwise product) of the resulting heat vectors.
When node sets are co-localized, there will be more nodes which are hot in both heat vectors (again we compare to a distribution of heat dot-products on degree preserving edge-shuffled graphs)
|
seed1 = Gsim.nodes()[0:5] #nx.neighbors(Gsim,Gsim.nodes()[0])
seed2 = Gsim.nodes()[10:15] #nx.neighbors(Gsim,Gsim.nodes()[5]) #Gsim.nodes()[27:32]
seed3 = Gsim.nodes()[20:25]
Fnew1 = network_prop.network_propagation(Gsim,Wprime_ring,seed1,alpha=.9,num_its=20)
Fnew2 = network_prop.network_propagation(Gsim,Wprime_ring,seed2,alpha=.9,num_its=20)
F12 = Fnew1*Fnew2
F12.sort(ascending=False)
#Fnew1.sort(ascending=False)
#Fnew2.sort(ascending=False)
Fnew1_norm = Fnew1/np.linalg.norm(Fnew1)
Fnew2_norm = Fnew2/np.linalg.norm(Fnew2)
dot_12 = np.sum(F12.head(10))
print(dot_12)
plt.figure(figsize=(18,6))
plt.subplot(1,3,1)
nx.draw_networkx_nodes(Gsim,pos=pos,node_size=100,alpha=.5,node_color=Fnew1[Gsim.nodes()],
cmap='jet', vmin=0,vmax=max(Fnew1))
nx.draw_networkx_nodes(Gsim,pos=pos,nodelist=seed1,
node_size=100,alpha=.9,node_color=Fnew1[seed1],
cmap='jet', vmin=0,vmax=max(Fnew1),linewidths=3)
nx.draw_networkx_edges(Gsim,pos=pos,alpha=.2)
plt.grid('off')
plt.xticks([],[])
plt.yticks([],[])
plt.annotate('Heat: nodes A ($H_A$)',xy=(.08,.93),xycoords='figure fraction',fontsize=16)
plt.subplot(1,3,2)
nx.draw_networkx_nodes(Gsim,pos=pos,node_size=100,alpha=.5,node_color=Fnew2[Gsim.nodes()],
cmap='jet', vmin=0,vmax=max(Fnew1))
nx.draw_networkx_nodes(Gsim,pos=pos,nodelist=seed2,
node_size=100,alpha=.9,node_color=Fnew2[seed2],
cmap='jet', vmin=0,vmax=max(Fnew1),linewidths=3)
nx.draw_networkx_edges(Gsim,pos=pos,alpha=.2)
plt.grid('off')
plt.xticks([],[])
plt.yticks([],[])
plt.annotate('Heat: nodes B ($H_B$)',xy=(.4,.93),xycoords='figure fraction',fontsize=16)
plt.subplot(1,3,3)
nx.draw_networkx_nodes(Gsim,pos=pos,node_size=100,alpha=.5,node_color=Fnew1[Gsim.nodes()]*Fnew2[Gsim.nodes()],
cmap='jet', vmin=0,vmax=max(Fnew1*Fnew2))
nx.draw_networkx_nodes(Gsim,pos=pos,nodelist=seed2,
node_size=100,alpha=.9,node_color=Fnew1[seed2]*Fnew2[seed2],
cmap='jet', vmin=0,vmax=max(Fnew1*Fnew2),linewidths=3)
nx.draw_networkx_nodes(Gsim,pos=pos,nodelist=seed1,
node_size=100,alpha=.9,node_color=Fnew1[seed1]*Fnew2[seed1],
cmap='jet', vmin=0,vmax=max(Fnew1*Fnew2),linewidths=3)
nx.draw_networkx_edges(Gsim,pos=pos,alpha=.2)
plt.grid('off')
plt.xticks([],[])
plt.yticks([],[])
plt.annotate('$H_A \cdot H_B$',xy=(.73,.93),xycoords='figure fraction',fontsize=16)
|
notebooks/networkAnalysis/localization_colocalization_example/localization_colocalization_example.ipynb
|
ucsd-ccbb/jupyter-genomics
|
mit
|
In the figure above, we show an example of this co-localization concept.
In the left panel we show the heat vector of the simulation seeded by node set A (warmer colors indicate hotter nodes, and bold outlines indicate seed nodes)
In the middle panel we show the heat vector of the simulation seeded by node set B
The right panel shows the pairwise product of the heat vectors (note color scale is different for this panel). The nodes between the two seed sets are the hottest, meaning that these are the nodes most likely related to both seed gene sets.
If these node sets are truly co-localized, then the sum of the heat product (the dot product) will be higher than random. This is what we will test below.
|
results_dict = network_prop.calc_3way_colocalization(Gsim,seed1,seed2,seed3,num_reps=100,num_genes=5,
replace=False,savefile=False,alpha=.5,print_flag=False,)
import scipy
num_reps = results_dict['num_reps']
dot_sfari_epi=results_dict['sfari_epi']
dot_sfari_epi_rand=results_dict['sfari_epi_rand']
#U,p = scipy.stats.mannwhitneyu(dot_sfari_epi,dot_sfari_epi_rand)
t,p = scipy.stats.ttest_ind(dot_sfari_epi,dot_sfari_epi_rand)
psig_SE = plotting_results.nsf(p,n=2)
plt.figure(figsize=(7,5))
plt.errorbar(-.1,np.mean(dot_sfari_epi_rand),2*np.std(dot_sfari_epi_rand)/np.sqrt(num_reps),fmt='o',
ecolor='gray',markerfacecolor='gray',label='edge-shuffled graph')
plt.errorbar(0,np.mean(dot_sfari_epi),2*np.std(dot_sfari_epi)/np.sqrt(num_reps),fmt='bo',
label='original graph')
plt.xlim(-.8,.5)
plt.legend(loc='lower left',fontsize=12)
plt.xticks([0],['A-B \np='+str(psig_SE)],rotation=45,fontsize=12)
plt.ylabel('$H_{A} \cdot H_{B}$',fontsize=18)
|
notebooks/networkAnalysis/localization_colocalization_example/localization_colocalization_example.ipynb
|
ucsd-ccbb/jupyter-genomics
|
mit
|
In the figure above, we show the heat dot product of node set A and node set B, on the original graph (blue dot), and on 100 edge-shuffled graphs (gray dot with error bars).
Using a two sided independent t-test, we find that the dot product on the original graph is significantly higher than on the edge-shuffled graphs, if node sets A and B are indeed co-localized.
Can we control how co-localized two node sets are?
We can use a parameter in our random graph generator function to control the co-localization of two node sets.
By varying the rewiring probability, we can move from a graph which is highly structured (low p-rewire: mostly nearest neighbor connections), to a graph which is mostly random (high p-rewire: mostly random connections).
In the following section we will sweet through values of p-rewire, ranging from 0 to 1, and measure the co-localization of identical node sets.
|
H12 = []
H12_rand = []
num_G_reps=5
for p_rewire in np.linspace(0,1,5):
print('rewiring probability = ' + str(p_rewire) + '...')
H12_temp = []
H12_temp_rand = []
for r in range(num_G_reps):
Gsim = nx.connected_watts_strogatz_graph(500,5,p_rewire)
seed1 = Gsim.nodes()[0:5]
seed2 = Gsim.nodes()[5:10]
seed3 = Gsim.nodes()[20:30]
results_dict = network_prop.calc_3way_colocalization(Gsim,seed1,seed2,seed3,num_reps=20,num_genes=5,
replace=False,savefile=False,alpha=.5,print_flag=False)
H12_temp.append(np.mean(results_dict['sfari_epi']))
H12_temp_rand.append(np.mean(results_dict['sfari_epi_rand']))
H12.append(np.mean(H12_temp))
H12_rand.append(np.mean(H12_temp_rand))
plt.plot(np.linspace(0,1,5),H12,'r.-',label='original')
plt.plot(np.linspace(0,1,5),H12_rand,'.-',color='gray',label='edge-shuffled')
plt.xlabel('link rewiring probability',fontsize=14)
plt.ylabel('$H_A \cdot H_B$',fontsize=16)
plt.legend(loc='upper right',fontsize=12)
|
notebooks/networkAnalysis/localization_colocalization_example/localization_colocalization_example.ipynb
|
ucsd-ccbb/jupyter-genomics
|
mit
|
We see above, as expected, that as the rewiring probability increases (on the x-axis), and the graph becomes more random, the heat dot-product (co-localization) decreases (on the y-axis), until the co-localization on the original graph matches the edge-shuffled graph.
We expect this to be the case because once p-rewire becomes very high, the original graph becomes essentially random, so not much is changed by shuffling the edges.
Three-way Co-localization
Finally, we will look at how our co-localization using network propagation method applies to three seed node sets instead of two.
This could be useful if the user was interested in establishing if one node set provided a link between two other node sets. For example, one might find that two node sets are individually not co-localized, but each is co-localized with a third node set. This third node set would essentially provide the missing link between the two, as illustrated below, where node sets A and C are far apart, but B is close to A, and B is close to C.
<img src="screenshots/CL_triangle.png">
|
seed1 = Gsim.nodes()[0:5]
seed2 = Gsim.nodes()[5:10]
seed3 = Gsim.nodes()[10:15]
results_dict = network_prop.calc_3way_colocalization(Gsim,seed1,seed2,seed3,num_reps=100,num_genes=5,
replace=False,savefile=False,alpha=.5,print_flag=False,)
import scipy
num_reps = results_dict['num_reps']
dot_sfari_epi=results_dict['sfari_epi']
dot_sfari_epi_rand=results_dict['sfari_epi_rand']
#U,p = scipy.stats.mannwhitneyu(dot_sfari_epi,dot_sfari_epi_rand)
t,p = scipy.stats.ttest_ind(dot_sfari_epi,dot_sfari_epi_rand)
psig_SE = plotting_results.nsf(p,n=2)
dot_sfari_aem=results_dict['sfari_aem']
dot_aem_sfari_rand=results_dict['aem_sfari_rand']
#U,p = scipy.stats.mannwhitneyu(dot_sfari_aem,dot_aem_sfari_rand)
t,p = scipy.stats.ttest_ind(dot_sfari_aem,dot_aem_sfari_rand)
psig_SA = plotting_results.nsf(p,n=2)
dot_aem_epi=results_dict['aem_epi']
dot_aem_epi_rand=results_dict['aem_epi_rand']
#U,p = scipy.stats.mannwhitneyu(dot_aem_epi,dot_aem_epi_rand)
t,p = scipy.stats.ttest_ind(dot_aem_epi,dot_aem_epi_rand)
psig_AE = plotting_results.nsf(p,n=2)
plt.figure(figsize=(7,5))
plt.errorbar(-.1,np.mean(dot_sfari_epi_rand),2*np.std(dot_sfari_epi_rand)/np.sqrt(num_reps),fmt='o',
ecolor='gray',markerfacecolor='gray')
plt.errorbar(0,np.mean(dot_sfari_epi),2*np.std(dot_sfari_epi)/np.sqrt(num_reps),fmt='bo')
plt.errorbar(.9,np.mean(dot_aem_sfari_rand),2*np.std(dot_aem_sfari_rand)/np.sqrt(num_reps),fmt='o',
ecolor='gray',markerfacecolor='gray')
plt.errorbar(1,np.mean(dot_sfari_aem),2*np.std(dot_sfari_aem)/np.sqrt(num_reps),fmt='ro')
plt.errorbar(1.9,np.mean(dot_aem_epi_rand),2*np.std(dot_aem_epi_rand)/np.sqrt(num_reps),fmt='o',
ecolor='gray',markerfacecolor='gray')
plt.errorbar(2,np.mean(dot_aem_epi),2*np.std(dot_aem_epi)/np.sqrt(num_reps),fmt='go')
plt.xticks([0,1,2],['A-B \np='+str(psig_SE),'A-C \np='+str(psig_SA),'B-C\np='+str(psig_AE)],rotation=45,fontsize=12)
plt.xlim(-.5,2.5)
plt.ylabel('$H_{1} \cdot H_{2}$',fontsize=18)
|
notebooks/networkAnalysis/localization_colocalization_example/localization_colocalization_example.ipynb
|
ucsd-ccbb/jupyter-genomics
|
mit
|
Generating synthetic data
First, we will generate the data. We will pick evenly spaced x-values. The y-values will be picked according to the equation $y=-\frac{1}{2}x$ but we will add Gaussian noise to each point. Each y-coordinate will have an associated error. The size of the error bar will be selected randomly.
After we have picked the data, we will plot it to visualize it. It looks like a fairly straight line.
|
n = 50 # number of data points
x = np.linspace(-10, 10, n)
yerr = np.abs(np.random.normal(0, 2, n))
y = np.linspace(5, -5, n) + np.random.normal(0, yerr, n)
plt.scatter(x, y)
|
src/stats_tutorials/Model Selection.ipynb
|
WormLabCaltech/mprsq
|
mit
|
Line fitting using Bayes' theorem
Now that we have generated our data, we would like to find the line of best fit given our data. To do this, we will perform a Bayesian regression. Briefly, Bayes equation is,
$$
P(\alpha~|D, M_1) \propto P(D~|\alpha, M_1)P(\alpha~|M_1).
$$
In other words, the probability of the slope given that Model 1 (a line with unknown slope) and the data is proportional to the probability of the data given the model and alpha times the probability of alpha given the model.
Some necessary nomenclature at this point:
* $P(D~|\alpha, M_1)\cdot P(\alpha|M_1)$ is called the posterior probability
* $P(\alpha~|M_1)$ is called the prior
* $P(D~|\alpha, M_1)$ is called the likelihood
I claim that a functional form that will allow me to fit a line through this data is:
$$
P(X|D) \propto \prod_{Data} \mathrm{exp}(-{\frac{(y_{Obs} - \alpha x)^2}{2\sigma_{Obs}^2}})\cdot (1 + \alpha^2)^{-3/2}
$$
The first term in the equation measures the deviation between the observed y-coordinates and the predicted y-coordinates from a theoretical linear model, where $\alpha$ remains to be determined. We weight the result by the observed error, $\sigma_{Obs}$. Then, we multiply by a prior that tells us what values of $\alpha$ should be considered. How to pick a good prior is somewhat difficult and a bit of an artform. One way is to pick a prior that is uninformative for a given parameter. In this case, we want to make sure that we sample slopes between [0,1] as densely as we sample [1,$\infty$]. For a more thorough derivation and explanation, please see this excellent blog post by Jake Vanderplas.
The likelihood is the first term, and the prior is the second. We code it up in the next functions, with a minor difference. It is often computationally much more tractable to compute the natural logarithm of the posterior, and we do so here.
We can now use this equation to find the model we are looking for. How? Well, the equation above basically tells us what model is most likely given that data and the prior information on the model. If we maximize the probability of the model, whatever parameter combination can satisfy that is a model that we are interested in!
|
# bayes model fitting:
def log_prior(theta):
beta = theta
return -1.5 * np.log(1 + beta ** 2)
def log_likelihood(beta, x, y, yerr):
sigma = yerr
y_model = beta * x
return -0.5 * np.sum(np.log(2 * np.pi * sigma ** 2) + (y - y_model) ** 2 / sigma ** 2)
def log_posterior(theta, x, y, yerr):
return log_prior(theta) + log_likelihood(theta, x, y, yerr)
def neg_log_prob_free(theta, x, y, yerr):
return -log_posterior(theta, x, y, yerr)
|
src/stats_tutorials/Model Selection.ipynb
|
WormLabCaltech/mprsq
|
mit
|
Specificity is necessary for credibility. Let's show that by optimizing the posterior function, we can fit a line.
We optimize the line by using the function scipy.optimize.minimize. However, minimizing the logarithm of the posterior does not achieve anything! We are looking for the place at which the equation we derived above is maximal. That's OK. We will simply multiply the logarithm of the posterior by -1 and minimize that.
|
# calculate probability of free model:
res = scipy.optimize.minimize(neg_log_prob_free, 0, args=(x, y, yerr), method='Powell')
plt.scatter(x, y)
plt.plot(x, x*res.x, '-', color='g')
print('The probability of this model is {0:.2g}'.format(np.exp(log_posterior(res.x, x, y, yerr))))
print('The optimized probability is {0:.4g}x'.format(np.float64(res.x)))
|
src/stats_tutorials/Model Selection.ipynb
|
WormLabCaltech/mprsq
|
mit
|
We can see that the model is very close to the model we drew the data from. It works!
However, the probability of this model is not very large. Why? Well, that's because the posterior probability is spread out over a large number of parameters. Bayesians like to think that a parameter is actually a number plus or minutes some jitter. Therefore, the probability of the parameter being exactly one number is usually smaller the larger the jitter. In thise case, the jitter is not terribly a lot, but the probability of this one parameter being exactly -0.5005 is quite low, even though it is the best guess for the slope given the data.
Quantifying the probability of a fixed model:
Suppose now that we had a powerful theoretical tool that allowed us to make a very, very good guess as to what line the points should fall on. Suppose this powerful theory now tells us that the line should be:
$$
y = -\frac{1}{2}x.
$$
Using Bayes' theorem, we could quantify the probability that the model is correct, given the data. Now, the prior is simply going to be 1 when the slope is -0.5, and 0 otherwise. This makes the equation:
$$
P(X|D) \propto \prod_{Data}\mathrm{exp}({-\frac{(y_{Obs} + 0.5x)^2}{2\sigma_{Obs}}})
$$
Notice that this equation cannot be minimized. It is a fixed statement, and its value depends only on the data.
|
# bayes model fitting:
def log_likelihood_fixed(x, y, yerr):
sigma = yerr
y_model = -1/2*x
return -0.5 * np.sum(np.log(2 * np.pi * sigma ** 2) + (y - y_model) ** 2 / sigma ** 2)
def log_posterior_fixed(x, y, yerr):
return log_likelihood_fixed(x, y, yerr)
plt.scatter(x, y)
plt.plot(x, -0.5*x, '-', color='purple')
print('The probability of this model is {0:.2g}'.format(np.exp(log_posterior_fixed(x, y, yerr))))
|
src/stats_tutorials/Model Selection.ipynb
|
WormLabCaltech/mprsq
|
mit
|
We can see that the probability of this model is very similar to the probability of the alternative model we fit above. How can we pick which one to use?
Selecting between two models
An initial approach to selecting between these two models would be to take the probability of each model given the data and to find the quotient, like so:
$$
OR = \frac{P(M_1~|D)}{P(M_2~|D)} = \frac{P(D~|M_1)P(M_1)}{P(D~|M_2)P(M_1)}
$$
However, this is tricky to evaluate. First of all, the equations we derived above are not solely in terms of $M_1$ and $D$. They also include $\alpha$ for the undetermined slope model. We can get rid of this parameter via a technique known as marginalization (basically, integrating the equations over $\alpha$). Even more philosophically difficult are the terms $P(M_i)$. How is one to evaluate the probability of a model being true? The usual solution to this is to set $P(M_i) \sim 1$ and let those terms cancel out. However, in the case of models that have been tested before or where there is a powerful theoretical reason to believe one is more likely than the other, it may be entirely reasonable to specify that one model is several times more likely than the other. For now, we set the $P(M_i)$ to unity.
We can approximate the odds-ratio for our case as follows:
$$
OR = \frac{P(D|\alpha^)}{P(D|M_2)} \cdot \frac{P(\alpha^|M_1) (2\pi)^{1/2} \sigma_\alpha^*}{1},
$$
where $\alpha^$ is the parameter we found when we minimized the probability function earlier. Here, the second term we added represents the complexity of each model. The denominator in the second term is 1 because the fixed model cannot become any simpler. On the other hand, we penalize the model with free slope by multiplying the probability of the observed slope by the square root of two pi and then multiplying all of this by the uncertainty in the parameter $\alpha$. This is akin to saying that the less likely we think $\alpha$ should be a priori*, or the more uncertain we are that $\alpha$ is actually a given number, then we should give points to the simpler model.
|
def model_selection(X, Y, Yerr, **kwargs):
guess = kwargs.pop('guess', -0.5)
# calculate probability of free model:
res = scipy.optimize.minimize(neg_log_prob_free, guess, args=(X, Y, Yerr), method='Powell')
# Compute error bars
second_derivative = scipy.misc.derivative(log_posterior, res.x, dx=1.0, n=2, args=(X, Y, Yerr), order=3)
cov_free = -1/second_derivative
alpha_free = np.float64(res.x)
log_free = log_posterior(alpha_free, X, Y, Yerr)
# log goodness of fit for fixed models
log_MAP = log_posterior_fixed(X, Y, Yerr)
good_fit = log_free - log_MAP
# occam factor - only the free model has a penalty
log_occam_factor =(-np.log(2 * np.pi) + np.log(cov_free)) / 2 + log_prior(alpha_free)
# give more standing to simpler models. but just a little bit!
lg = log_free - log_MAP + log_occam_factor - 2
return lg
|
src/stats_tutorials/Model Selection.ipynb
|
WormLabCaltech/mprsq
|
mit
|
We performed the Odds Ratio calculation on logarithmic space, so negative values show that the simpler (fixed slope) model is preferred, whereas if the values are positive and large, the free-slope model is preferred.
As a guide, Bayesian statisticians usually suggest that 10^2 or above is a good ratio to abandon one model completely in favor of another.
|
model_selection(x, y, yerr)
|
src/stats_tutorials/Model Selection.ipynb
|
WormLabCaltech/mprsq
|
mit
|
Different datasets will prefer different models
Let's try this again. Maybe the answer will change sign this time.
|
n = 50 # number of data points
x = np.linspace(-10, 10, n)
yerr = np.abs(np.random.normal(0, 2, n))
y = x*-0.55 + np.random.normal(0, yerr, n)
plt.scatter(x, y)
model_selection(x, y, yerr)
|
src/stats_tutorials/Model Selection.ipynb
|
WormLabCaltech/mprsq
|
mit
|
Indeed, the answer changed sign. Odds Ratios, p-values and everything else should always be interpreted conservatively. I prefer odds ratios that are very large, larger than 1,000 before stating that one model is definitively preferred. Otherwise, I tend to prefer the simpler model.
The larger the dataset, the more resolving power
What distribution of answers would you get if you obtained five points? Ten? Fifteen? I've written a couple of short functions to help us find out.
In the functions below, I simulate two datasets. One datasets is being plucked from points that obey the model
$$
y = -\frac{1}{2}x,
$$
whereas the second model is being plucked from
$$
y = -0.46x.
$$
Clearly, the fixed model $y=-0.5x$ should only be preferred for the first dataset, and the free model is the correct one to use for the second model. Now let us find out if this is the case.
By the way, the function below trims odds ratios to keep them from becoming too large. If an odds ratio is bigger than 10, we set it equal to 10 for plotting purposes.
|
def simulate_many_odds_ratios(n):
"""
Given a number `n` of data points, simulate 1,000 data points drawn from a null model and an alternative model and
compare the odds ratio for each.
"""
iters = 1000
lg1 = np.zeros(iters)
lg2 = np.zeros(iters)
for i in range(iters):
x = np.linspace(-10, 10, n)
yerr = np.abs(np.random.normal(0, 2, n))
# simulate two models: only one matches the fixed model
y1 = -0.5*x + np.random.normal(0, yerr, n)
y2 = -0.46*x + np.random.normal(0, yerr, n)
lg1[i] = model_selection(x, y1, yerr)
m2 = model_selection(x, y2, yerr)
# Truncate OR for ease of plotting
if m2 < 10:
lg2[i] = m2
else:
lg2[i] = 10
return lg1, lg2
def make_figures(n):
lg1, lg2 = simulate_many_odds_ratios(n)
lg1 = np.sort(lg1)
lg2 = np.sort(lg2)
fifty_point1 = lg1[int(np.floor(len(lg1)/2))]
fifty_point2 = lg2[int(np.floor(len(lg2)/2))]
fig, ax = plt.subplots(ncols=2, figsize=(15, 7), sharey=True)
fig.suptitle('Log Odds Ratio for n={0} data points'.format(n), fontsize=20)
sns.kdeplot(lg1, label='slope=-0.5', ax=ax[0], cumulative=False)
ax[0].axvline(x=fifty_point1, ls='--', color='k')
ax[0].set_title('Data drawn from null model')
ax[0].set_ylabel('Density')
sns.kdeplot(lg2, label='slope=-0.46', ax=ax[1], cumulative=False)
ax[1].axvline(x=fifty_point2, ls='--', color='k')
ax[1].set_title('Data drawn from alternative model')
fig.text(0.5, 0.04, 'Log Odds Ratio', ha='center', size=18)
return fig, ax
fig, ax = make_figures(n=5)
|
src/stats_tutorials/Model Selection.ipynb
|
WormLabCaltech/mprsq
|
mit
|
Here we can see that with five data points, the odds ratio will tend to prefer the simpler model. We do not have too much information---why request the extra information? Note that for the second dataset in some cases the deviations are great enough that the alternative model is strongly preferred (right panel, extra bump at 10). However, this is rare.
|
fig, ax = make_figures(n=50)
|
src/stats_tutorials/Model Selection.ipynb
|
WormLabCaltech/mprsq
|
mit
|
Load CML example data
Coordinates mimic the real network topology but are fake
|
cml_list = pycml.io.examples.get_75_cmls()
fig, ax = plt.subplots()
for cml in cml_list:
cml.plot_line(ax=ax, color='k')
|
notebooks/outdated_notebooks/Spatial interpolation.ipynb
|
pycomlink/pycomlink
|
bsd-3-clause
|
Do a simple standard processing to get rain rates for each CML
|
for cml in tqdm(cml_list):
window_length = 60
threshold = 1.0
cml.process.wet_dry.std_dev(window_length=window_length, threshold=threshold)
cml.process.baseline.linear()
cml.process.baseline.calc_A()
cml.process.A_R.calc_R()
|
notebooks/outdated_notebooks/Spatial interpolation.ipynb
|
pycomlink/pycomlink
|
bsd-3-clause
|
Do IDW interpolation of CML rain rates
The ComlinkGridInterpolator takes a PointsToGridInterpolator object as argument, which is used for the interpolation of each time step. You can pass config arguments to the initialization of the PointsToGridInterpolator.
Currently only the IDW interpolator IdWKdtreeInterpolator which subclasses PointsToGridInterpolator is available. A Kriging version is already implemented but does not work reliably.
Initialize interpolator
resolution is used to generate a grid using a bounding box aroudn all CMLs if no x- and y-grid are supplied.
Currently CML rain rates are averaged to hourly data before interpolating.
|
cml_interp = pycml.spatial.interpolator.ComlinkGridInterpolator(
cml_list=cml_list,
resolution=0.01,
interpolator=pycml.spatial.interpolator.IdwKdtreeInterpolator())
|
notebooks/outdated_notebooks/Spatial interpolation.ipynb
|
pycomlink/pycomlink
|
bsd-3-clause
|
Perform interpolation for all time steps
|
ds = cml_interp.loop_over_time()
ds
fig, ax = plt.subplots(3, 3, sharex=True, sharey=True, figsize=(12,12))
for i, axi in enumerate(ax.flat):
for cml in cml_list:
cml.plot_line(ax=axi, color='k')
pc = axi.pcolormesh(ds.lon,
ds.lat,
ds.R.isel(time=20+i),
cmap=plt.get_cmap('BuPu', 8),
vmin=0,
vmax=20)
axi.set_title(cml_interp.df_cmls.index[20+i])
fig.subplots_adjust(right=0.9)
cbar_ax = fig.add_axes([0.95, 0.15, 0.02, 0.7])
fig.colorbar(pc, cax=cbar_ax, label='Hourly rainfall sum in mm');
|
notebooks/outdated_notebooks/Spatial interpolation.ipynb
|
pycomlink/pycomlink
|
bsd-3-clause
|
Calculate CML coverage mask
Coverage for 0.05 degree coverage around CMLs.
Note: Calculating coverage using lon-lat and degrees does result in distortions. In the future this will be done using a area preserving reprojection of the lon-lat coordinates before calculating coverage.
|
cml_coverage_mask = pycml.spatial.coverage.calc_coverage_mask(
cml_list=cml_list,
xgrid=ds.lon.values,
ygrid=ds.lat.values,
max_dist_from_cml=0.05)
fig, ax = plt.subplots()
for cml in cml_list:
cml.plot_line(ax=ax, color='k')
ax.pcolormesh(ds.lon, ds.lat, cml_coverage_mask, cmap='gray');
|
notebooks/outdated_notebooks/Spatial interpolation.ipynb
|
pycomlink/pycomlink
|
bsd-3-clause
|
Coverage for 0.1 degree coverage around CMLs.
|
cml_coverage_mask = pycml.spatial.coverage.calc_coverage_mask(
cml_list=cml_list,
xgrid=ds.lon.values,
ygrid=ds.lat.values,
max_dist_from_cml=0.1)
fig, ax = plt.subplots()
for cml in cml_list:
cml.plot_line(ax=ax, color='k')
ax.pcolormesh(ds.lon, ds.lat, cml_coverage_mask, cmap='gray');
|
notebooks/outdated_notebooks/Spatial interpolation.ipynb
|
pycomlink/pycomlink
|
bsd-3-clause
|
Plot CML rainfall sum and apply coverage map
|
fig, ax = plt.subplots()
for cml in cml_list:
cml.plot_line(ax=ax, color='k')
pc = ax.pcolormesh(
ds.lon,
ds.lat,
ds.R.sum(dim='time').where(cml_coverage_mask),
cmap=plt.get_cmap('BuPu', 32))
plt.colorbar(pc, label='rainfall sum in mm');
|
notebooks/outdated_notebooks/Spatial interpolation.ipynb
|
pycomlink/pycomlink
|
bsd-3-clause
|
To define a new class, you need a class keyword, followed by the name (in this case, Car). The parentheses are important, but for now we'll leave them empty. Like loops and functions and conditionals, everything that belongs to the class--variables, methods, etc--are indented underneath.
We can then instantiate this class using the following:
|
my_car = Car()
print(my_car)
|
lectures/L11.ipynb
|
eds-uga/csci1360-fa16
|
mit
|
Now my_car holds an instance of the Car class! It doesn't do much, but it's a valid object.
Constructors
The first step in making an interesting class is by creating a constructor. It's a special kind of function that provides a customized recipe for how an instance of that class is built.
It takes a special form, too:
|
class Car():
def __init__(self):
print("This is the constructor!")
my_car = Car()
|
lectures/L11.ipynb
|
eds-uga/csci1360-fa16
|
mit
|
Let's look at this method in more detail.
|
def __init__(self):
pass
|
lectures/L11.ipynb
|
eds-uga/csci1360-fa16
|
mit
|
The def is normal: the Python keyword we use to identify a function definition.
__init__ is the name of our method. It's an interesting name for sure, and turns out this is a very specific name Python is looking for: whenever you instantiate an object, this is the method that's run. If you don't explicitly write a constructor, Python implicitly supplies a "default" one (where basically nothing really happens).
The method argument is strange; what is this mysterious self, and why--if an argument is required--didn't we supply one when we executed my_car = Car()?
A note on self
This is how the object refers to itself from inside the object. We'll see this in greater detail once we get to attributes.
Every method in a class must have self as the first argument. Even though you don't actually supply this argument yourself when you call the method, it still has to be in the function definition.
Otherwise, you'll get some weird error messages:
Attributes
Attributes are variables contained inside a class, and which take certain values when the class is instantiated.
The most common practice is to define these attributes within the constructor of the class.
|
class Car():
def __init__(self, year, make, model):
# All three of these are class attributes.
self.year = year
self.make = make
self.model = model
my_car = Car(2015, "Honda", "Accord") # Again, note that we don't specify something for "self" here.
print(my_car.year)
|
lectures/L11.ipynb
|
eds-uga/csci1360-fa16
|
mit
|
These attributes are accessible from anywhere inside the class, but direct access to them from outside (as did in the print(my_car.year) statement) is heavily frowned upon.
Instead, good object-oriented design stipulates that these attributes be treated as private variables to the class.
To be modified or otherwise used, the classes should have public methods that expose very specific avenues for interaction with the class attributes.
This is the concept of encapsulation: restricting direct access to attributes, and instead encouraging the use of class methods to interact with the attributes in very specific ways.
Methods
Methods are functions attached to the class, but which are accessible from outside the class, and define the ways in which the instances of the class can interact with the outside world.
Whereas classes are usually nouns, the methods are typically the verbs. For example, what would a Car class do?
|
class Car():
def __init__(self, year, make, model):
self.year = year
self.make = make
self.model = model
self.mileage = 0
def drive(self, mileage = 0):
if mileage == 0:
print("Driving!")
else:
self.mileage += mileage
print("Driven {} miles total.".format(self.mileage))
my_car = Car(2016, "Tesla", "Model S")
my_car.drive(100)
my_car.drive()
my_car.drive(50)
|
lectures/L11.ipynb
|
eds-uga/csci1360-fa16
|
mit
|
Classes can have as many methods as you want, named whatever you'd like (though usually named so they reflect their purpose).
Methods are what are ultimately allowed to edit the class attributes (the self. variables), as per the concept of encapsulation. For example, the self.mileage attribute in the previous example that stores the total mileage driven by that instance.
Like the constructor, all the class methods must have self as the first argument in their headers, even though you don't explicitly supply it when you call the methods.
Inheritance
Inheritance is easily the most complicated aspect of object-oriented programming, but is most certainly where OOP derives its power for modular design.
When considering cars, certainly most are very similar and can be modeled effectively with one class, but eventually there are enough differences to necessitate the creation of a separate class. For example, a class for gas-powered cars and one for EVs.
But considering how much overlap they still share, it'd be highly redundant to make wholly separate classes for both.
|
class GasCar():
def __init__(self, make, model, year, tank_size):
# Set up attributes.
pass
def drive(self, mileage = 0):
# Driving functionality.
pass
class ElectricCar():
def __init__(self, make, model, year, battery_cycles):
# Set up attributes.
pass
def drive(self, mileage = 0):
# Driving functionality, probably identical to GasCar.
pass
|
lectures/L11.ipynb
|
eds-uga/csci1360-fa16
|
mit
|
Enter inheritance: the ability to create subclasses of existing classes that retain all the functionality of the parent, while requiring the implementation only of the things that differentiate the child from the parent.
|
class Car(): # Parent class.
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.mileage = 0
def drive(self, mileage = 0):
self.mileage += mileage
print("Driven {} miles.".format(self.mileage))
class EV(Car): # Child class--explicitly mentions "Car" as the parent!
def __init__(self, make, model, year, charge_range):
Car.__init__(self, make, model, year)
self.charge_range = charge_range
def charge_remaining(self):
if self.mileage < self.charge_range:
print("Still {} miles left.".format(self.charge_range - self.mileage))
else:
print("Battery depleted! Find a SuperCharger station.")
tesla = EV(2016, "Tesla", "Model S", 250)
tesla.drive(100)
tesla.charge_remaining()
tesla.drive(150)
tesla.charge_remaining()
|
lectures/L11.ipynb
|
eds-uga/csci1360-fa16
|
mit
|
Hopefully you noticed--we could call tesla.drive() and it worked as it was defined in the parent Car class, without us having to write it again!
This is the power of inheritance: every child class inherits all the functionality of the parent class.
With ONE exception: if you override a parent attribute or method in the child class, then that takes precedence.
|
class Hybrid(Car):
def drive(self, mileage, mpg):
self.mileage += mileage
print("Driven {} miles at {:.1f} MPG.".format(self.mileage, mpg))
hybrid = Hybrid(2015, "Toyota", "Prius")
hybrid.drive(100, 35.5)
|
lectures/L11.ipynb
|
eds-uga/csci1360-fa16
|
mit
|
Using inheritance, you can build an entire hierarchy of classes and subclasses, inheriting functionality where needed and overriding it where necessary.
This illustrates the concept of polymorphism (meaning "many forms"): all cars are vehicles; therefore, any functions a vehicle has, a car will also have.
All transporters are vehicles--and also cars--and have all the associated functionality defined in those classes.
However, it does NOT work in reverse: not all vehicles are motorcycles! Thus, as you move down the hierarchy, the objects become more specialized.
Multiple Inheritance
Just a quick note on this, for all the Java converts--
Python does support multiple inheritance, meaning a child class can directly inherit from multiple parent classes.
|
class DerivedClassName(EV, Hybrid):
pass
|
lectures/L11.ipynb
|
eds-uga/csci1360-fa16
|
mit
|
First we load the default values of:
- IMF
- SN2, AGB and SNIa feedback
|
a.basic_sfr_name
# Load the IMF
from Chempy.imf import IMF
basic_imf = IMF(a.mmin,a.mmax,a.mass_steps)
getattr(basic_imf, a.imf_type_name)((a.chabrier_para1,a.chabrier_para2,a.high_mass_slope))
# Load the SFR
from Chempy.sfr import SFR
basic_sfr = SFR(a.start, a.end, a.time_steps)
getattr(basic_sfr, a.basic_sfr_name)(S0 = a.S_0 * a.mass_factor,a_parameter = a.a_parameter, loc = a.sfr_beginning, scale = a.sfr_scale)
basic_sfr.sfr = a.total_mass * np.divide(basic_sfr.sfr, sum(basic_sfr.sfr))
# Load the yields of the default yield set
from Chempy.yields import SN2_feedback, AGB_feedback, SN1a_feedback
basic_sn2 = SN2_feedback()
getattr(basic_sn2, "Nomoto2013")()
basic_1a = SN1a_feedback()
getattr(basic_1a, "Seitenzahl")()
basic_agb = AGB_feedback()
getattr(basic_agb, "Karakas_net_yield")()
|
tutorials/4-Simple_stellar_population.ipynb
|
jan-rybizki/Chempy
|
mit
|
We check how many elements are traced by our yield set
|
# Print all supported elements
elements_to_trace = list(np.unique(basic_agb.elements+basic_sn2.elements+basic_1a.elements))
print(elements_to_trace)
|
tutorials/4-Simple_stellar_population.ipynb
|
jan-rybizki/Chempy
|
mit
|
When initialising the SSP class, we have to make the following choices(in brackets our choices are given):
Which metallicity does it have (Solar)
How long will the SSP live and at which timesteps do we want the feedback to be evaluated (Delta t = 0.025 for 13.5 Gyr)
What is the lifetime rroutine (Argast+ 2000)
How should the interpolation in metallicity from the yield tables be (logarithmic)
Do we want to safe the net yields as well (No)
|
# Load solar abundances
from Chempy.solar_abundance import solar_abundances
basic_solar = solar_abundances()
getattr(basic_solar, 'Asplund09')()
# Initialise the SSP class with time-steps
time_steps = np.linspace(0.,13.5,541)
from Chempy.weighted_yield import SSP
basic_ssp = SSP(False, np.copy(basic_solar.z), np.copy(basic_imf.x), np.copy(basic_imf.dm), np.copy(basic_imf.dn), np.copy(time_steps), list(elements_to_trace), 'Argast_2000', 'logarithmic', False)
|
tutorials/4-Simple_stellar_population.ipynb
|
jan-rybizki/Chempy
|
mit
|
This initialises the SSP class. It calculates the inverse IMF (stars of which minimal mass will be dead until each time-step) and it also initialises the feedback table, which need to be filled by the feedback from each subroutine, representing a specific nucleosynthetic process (CC-SN, AGB star, SN Ia). For the inverse IMF's first time-steps we see that only after the first and second time-step CC-SN will contribute (only stars smaller than 8Msun survive longer...).
|
# Plotting the inverse IMF
plt.plot(time_steps[1:],basic_ssp.inverse_imf[1:])
plt.ylabel('Mass of stars dying')
plt.xlabel('Time in Gyr')
plt.ylim((0.7,11))
for i in range(5):
print(time_steps[i], ' Gyr -->', basic_ssp.inverse_imf[i], ' Msun')
|
tutorials/4-Simple_stellar_population.ipynb
|
jan-rybizki/Chempy
|
mit
|
In order to calculate the feedback for the CC-SN and AGB star we will need to provide the elemental abundances at birth, for which we will use solar abundances for now. (This is the case for net yields, gross yields already include the initial stellar abundance that will be expelled.)
|
# Producing the SSP birth elemental fractions (here we use solar)
solar_fractions = []
elements = np.hstack(basic_solar.all_elements)
for item in elements_to_trace:
solar_fractions.append(float(basic_solar.fractions[np.where(elements==item)]))
# Each nucleosynthetic process has its own method on the SSP class and adds its feedback into the final table
basic_ssp.sn2_feedback(list(basic_sn2.elements), dict(basic_sn2.table), np.copy(basic_sn2.metallicities), float(a.sn2mmin), float(a.sn2mmax),list(solar_fractions))
basic_ssp.agb_feedback(list(basic_agb.elements), dict(basic_agb.table), list(basic_agb.metallicities), float(a.agbmmin), float(a.agbmmax),list(solar_fractions))
basic_ssp.sn1a_feedback(list(basic_1a.elements), list(basic_1a.metallicities), dict(basic_1a.table), str(a.time_delay_functional_form), float(a.sn1ammin), float(a.sn1ammax), [a.N_0,a.sn1a_time_delay,a.sn1a_exponent,a.dummy],float(a.total_mass), a.stochastic_IMF)
|
tutorials/4-Simple_stellar_population.ipynb
|
jan-rybizki/Chempy
|
mit
|
Elemental feedback from an SSP over time
|
# Now we can plot the feedback of an SSP over time for a few elements
plt.plot(time_steps,np.cumsum(basic_ssp.table['H']), label = 'H')
plt.plot(time_steps,np.cumsum(basic_ssp.table['O']), label = 'O')
plt.plot(time_steps,np.cumsum(basic_ssp.table['C']), label = 'C')
plt.plot(time_steps,np.cumsum(basic_ssp.table['Fe']), label = 'Fe')
plt.yscale('log')
plt.xscale('log')
plt.ylabel('Mass fraction of Element expelled')
plt.title('Total feedback of an SSP of 1Msun')
plt.xlabel('Time in Gyr')
plt.legend()
|
tutorials/4-Simple_stellar_population.ipynb
|
jan-rybizki/Chempy
|
mit
|
The difference between different yield sets
|
# Loading an SSP which uses the alternative yield set
basic_ssp_alternative = SSP(False, np.copy(basic_solar.z), np.copy(basic_imf.x), np.copy(basic_imf.dm), np.copy(basic_imf.dn), np.copy(time_steps), list(elements_to_trace), 'Argast_2000', 'logarithmic', False)
basic_sn2_alternative = SN2_feedback()
getattr(basic_sn2_alternative, "chieffi04")()
basic_1a_alternative = SN1a_feedback()
getattr(basic_1a_alternative, "Thielemann")()
basic_agb_alternative = AGB_feedback()
getattr(basic_agb_alternative, "Ventura_net")()
basic_ssp_alternative.sn2_feedback(list(basic_sn2_alternative.elements), dict(basic_sn2_alternative.table), np.copy(basic_sn2_alternative.metallicities), float(a.sn2mmin), float(a.sn2mmax),list(solar_fractions))
basic_ssp_alternative.agb_feedback(list(basic_agb_alternative.elements), dict(basic_agb_alternative.table), list(basic_agb_alternative.metallicities), float(a.agbmmin), float(a.agbmmax),list(solar_fractions))
basic_ssp_alternative.sn1a_feedback(list(basic_1a_alternative.elements), list(basic_1a_alternative.metallicities), dict(basic_1a_alternative.table), str(a.time_delay_functional_form), float(a.sn1ammin), float(a.sn1ammax), [a.N_0,a.sn1a_time_delay,a.sn1a_exponent,a.dummy],float(a.total_mass), a.stochastic_IMF)
# Plotting the difference
plt.plot(time_steps,np.cumsum(basic_ssp.table['H']), label = 'H', color = 'b')
plt.plot(time_steps,np.cumsum(basic_ssp.table['O']), label = 'O', color = 'orange')
plt.plot(time_steps,np.cumsum(basic_ssp.table['C']), label = 'C', color = 'g')
plt.plot(time_steps,np.cumsum(basic_ssp.table['Fe']), label = 'Fe', color = 'r')
plt.plot(time_steps,np.cumsum(basic_ssp_alternative.table['H']), linestyle = '--', color = 'b')
plt.plot(time_steps,np.cumsum(basic_ssp_alternative.table['O']), linestyle = '--', color = 'orange')
plt.plot(time_steps,np.cumsum(basic_ssp_alternative.table['C']), linestyle = '--', color = 'g')
plt.plot(time_steps,np.cumsum(basic_ssp_alternative.table['Fe']), linestyle = '--', color = 'r')
plt.yscale('log')
plt.xscale('log')
plt.ylabel('Mass fraction of Element expelled')
plt.title('default/alternative yield set in solid/dashed lines')
plt.xlabel('Time in Gyr')
plt.legend()
|
tutorials/4-Simple_stellar_population.ipynb
|
jan-rybizki/Chempy
|
mit
|
The contribution of different nucleosynthetic paths to a single element
|
# The SSP class stores the individual feedback of each nucleosynthetic channel
# Here we plot the Carbon feedback over time
plt.plot(time_steps,np.cumsum(basic_ssp.table['C']), label = 'total')
plt.plot(time_steps,np.cumsum(basic_ssp.sn2_table['C']), label = 'CC-SN')
plt.plot(time_steps,np.cumsum(basic_ssp.sn1a_table['C']), label = 'SN Ia')
plt.plot(time_steps,np.cumsum(basic_ssp.agb_table['C']), label = 'AGB')
plt.yscale('log')
plt.xscale('log')
plt.ylabel('Mass fraction of Element expelled')
plt.xlabel('Time in Gyr')
plt.title('Carbon feedback per nucleosynthetic process')
plt.legend()
|
tutorials/4-Simple_stellar_population.ipynb
|
jan-rybizki/Chempy
|
mit
|
The number of events
|
# The number of events is stored as well
plt.plot(time_steps,np.cumsum(basic_ssp.table['sn2']), label = 'CC-SN')
plt.plot(time_steps,np.cumsum(basic_ssp.table['sn1a']), label = 'SN Ia')
plt.plot(time_steps,np.cumsum(basic_ssp.table['pn']), label = 'AGB')
plt.yscale('log')
plt.xscale('log')
plt.ylabel('# of events')
plt.xlabel('Time in Gyr')
plt.title('Number of events per SSP of 1Msun')
plt.legend()
|
tutorials/4-Simple_stellar_population.ipynb
|
jan-rybizki/Chempy
|
mit
|
The mass fractions
|
# As is the mass fraction of stars, remnants, dying stars from which the total feedback mass can be calculated
plt.plot(time_steps,basic_ssp.table['mass_in_ms_stars'], label = 'Ms stars')
plt.plot(time_steps,np.cumsum(basic_ssp.table['mass_in_remnants']), label = 'remnants')
plt.plot(time_steps,np.cumsum(basic_ssp.table['mass_of_ms_stars_dying']), label = 'dying')
plt.plot(time_steps,np.cumsum(basic_ssp.table['mass_of_ms_stars_dying']) - np.cumsum(basic_ssp.table['mass_in_remnants']), label = 'feedback')
plt.yscale('log')
plt.xscale('log')
plt.ylabel('Mass fraction')
plt.xlabel('Time in Gyr')
plt.title('Mass of stars gets transformed into remnants and feedback over time')
plt.legend(loc = 'right', bbox_to_anchor= (1.6,0.5))
|
tutorials/4-Simple_stellar_population.ipynb
|
jan-rybizki/Chempy
|
mit
|
IMF weighted yield of an SSP
Depends on the timespan over which we integrate (here we use the full 13.5Gyr)
Depends on the IMF
On the chosen yield set
The mass range of the nucleosynthetic process (e.g. low-mass CC-SN have only solar alpha/Fe abundances)
etc... play around and investigate
|
# Here we print the time-integrated yield of an SSP (feedback after 13,5Gyr)
# for different elements and also for CC-SNe feedback only
normalising_element = 'Fe'
print('alternative yield set')
print('Element, total SSP yield, CC-SN yield ([X/Fe] i.e. normalised to solar)')
for element in ['C', 'O', 'Mg', 'Ca', 'Mn', 'Ni']:
element_ssp_sn2 = sum(basic_ssp_alternative.sn2_table[element])
element_ssp = sum(basic_ssp_alternative.table[element])
element_sun = basic_solar.fractions[np.where(elements == element)]
normalising_element_ssp_sn2 = sum(basic_ssp_alternative.sn2_table[normalising_element])
normalising_element_ssp = sum(basic_ssp_alternative.table[normalising_element])
normalising_element_sun = basic_solar.fractions[np.where(elements == normalising_element)]
print(element, np.log10(element_ssp/element_sun)-np.log10(normalising_element_ssp/normalising_element_sun), np.log10(element_ssp_sn2/element_sun)-np.log10(normalising_element_ssp_sn2/normalising_element_sun))
print('------------------------------------------')
print('default yield set')
print('Element, total SSP yield, CC-SN yield ([X/Fe] i.e. normalised to solar)')
for element in ['C', 'O', 'Mg', 'Ca', 'Mn', 'Ni']:
element_ssp_sn2 = sum(basic_ssp.sn2_table[element])
element_ssp = sum(basic_ssp.table[element])
element_sun = basic_solar.fractions[np.where(elements == element)]
normalising_element_ssp_sn2 = sum(basic_ssp.sn2_table[normalising_element])
normalising_element_ssp = sum(basic_ssp.table[normalising_element])
normalising_element_sun = basic_solar.fractions[np.where(elements == normalising_element)]
print(element, np.log10(element_ssp/element_sun)-np.log10(normalising_element_ssp/normalising_element_sun), np.log10(element_ssp_sn2/element_sun)-np.log10(normalising_element_ssp_sn2/normalising_element_sun))
|
tutorials/4-Simple_stellar_population.ipynb
|
jan-rybizki/Chempy
|
mit
|
Net yield vs. gross yield
Here the difference between newly produced material (net yield) and total expelled material (gross yield) is shown for AGB and CC-SN.
|
# We can set the the additional table (e.g. agb_table) to only save the newly produced material
basic_ssp_net = SSP(False, np.copy(basic_solar.z), np.copy(basic_imf.x), np.copy(basic_imf.dm), np.copy(basic_imf.dn), np.copy(time_steps), list(elements_to_trace), 'Argast_2000', 'logarithmic', True)
basic_ssp_net.agb_feedback(list(basic_agb.elements), dict(basic_agb.table), list(basic_agb.metallicities), float(a.agbmmin), float(a.agbmmax),list(solar_fractions))
# And then compare these net yields to gross yields for C
plt.plot(time_steps,np.cumsum(basic_ssp.agb_table['C']), label = 'total')
plt.plot(time_steps,np.cumsum(basic_ssp_net.agb_table['C']), label = 'newly produced')
plt.yscale('log')
plt.xscale('log')
plt.ylabel('Carbon feedback from AGB stars')
plt.xlabel('Time in Gyr')
plt.title('Net yield vs. gross yield')
plt.legend()
# And show the same for O and CC-SNe
basic_ssp_net = SSP(False, basic_solar.z, basic_imf.x, basic_imf.dm, basic_imf.dn, time_steps, elements_to_trace, 'Argast_2000', 'logarithmic', True)
basic_ssp_net.sn2_feedback(list(basic_sn2.elements), dict(basic_sn2.table), np.copy(basic_sn2.metallicities), float(a.sn2mmin), float(a.sn2mmax),list(solar_fractions))
plt.plot(time_steps,np.cumsum(basic_ssp.sn2_table['He']), label = 'total')
plt.plot(time_steps,np.cumsum(basic_ssp_net.sn2_table['He']), label = 'newly produced')
plt.yscale('log')
plt.xscale('log')
plt.ylabel('Cumulative Helium feedback from CC-SN')
plt.xlabel('Time in Gyr')
plt.title('Net vs. gross yield')
plt.legend()
|
tutorials/4-Simple_stellar_population.ipynb
|
jan-rybizki/Chempy
|
mit
|
Stochastic IMF sampling
The feedback and the explosion of SN Ia can also be calculated stochastically.
The mass of the SSP needs to be provided (the feedback table is given in fractions).
Each realisation will be new (you can check by redoing the plot).
|
# The IMF can be sampled stochastically. First we plot the analytic version
basic_imf = IMF(a.mmin,a.mmax,a.mass_steps)
getattr(basic_imf, a.imf_type_name)((a.chabrier_para1,a.chabrier_para2,a.high_mass_slope))
basic_ssp = SSP(False, np.copy(basic_solar.z), np.copy(basic_imf.x), np.copy(basic_imf.dm), np.copy(basic_imf.dn), np.copy(time_steps), list(elements_to_trace), 'Argast_2000', 'logarithmic', False)
basic_ssp.sn2_feedback(list(basic_sn2.elements), dict(basic_sn2.table), np.copy(basic_sn2.metallicities), float(a.sn2mmin), float(a.sn2mmax),list(solar_fractions))
basic_ssp.agb_feedback(list(basic_agb.elements), dict(basic_agb.table), list(basic_agb.metallicities), float(a.agbmmin), float(a.agbmmax),list(solar_fractions))
basic_ssp.sn1a_feedback(list(basic_1a.elements), list(basic_1a.metallicities), dict(basic_1a.table), str(a.time_delay_functional_form), float(a.sn1ammin), float(a.sn1ammax), [a.N_0,a.sn1a_time_delay,a.sn1a_exponent,a.dummy],float(a.total_mass), True)
plt.plot(time_steps,np.cumsum(basic_ssp.table['Fe']), label = 'analytic IMF')
# Then we add the stochastic sampling for 3 different masses
for mass in [1e5,5e3,1e2]:
basic_imf = IMF(a.mmin,a.mmax,a.mass_steps)
getattr(basic_imf, a.imf_type_name)((a.chabrier_para1,a.chabrier_para2,a.high_mass_slope))
basic_imf.stochastic_sampling(mass)
basic_ssp = SSP(False, np.copy(basic_solar.z), np.copy(basic_imf.x), np.copy(basic_imf.dm), np.copy(basic_imf.dn), np.copy(time_steps), list(elements_to_trace), 'Argast_2000', 'logarithmic', False)
basic_ssp.sn2_feedback(list(basic_sn2.elements), dict(basic_sn2.table), np.copy(basic_sn2.metallicities), float(a.sn2mmin), float(a.sn2mmax),list(solar_fractions))
basic_ssp.agb_feedback(list(basic_agb.elements), dict(basic_agb.table), list(basic_agb.metallicities), float(a.agbmmin), float(a.agbmmax),list(solar_fractions))
basic_ssp.sn1a_feedback(list(basic_1a.elements), list(basic_1a.metallicities), dict(basic_1a.table), str(a.time_delay_functional_form), float(a.sn1ammin), float(a.sn1ammax), [a.N_0,a.sn1a_time_delay,a.sn1a_exponent,a.dummy],float(a.total_mass), True)
plt.plot(time_steps,np.cumsum(basic_ssp.table['Fe']), label = '%d Msun' %(mass))
plt.xscale('log')
plt.ylabel('Cumulative fractional iron feedback of an SSP')
plt.xlabel('Time in Gyr')
plt.legend(bbox_to_anchor = (1.5,1))
|
tutorials/4-Simple_stellar_population.ipynb
|
jan-rybizki/Chempy
|
mit
|
SSP wrapper
In order to query the SSP feedback faster and easier we write a little wrapper in wrapper.py and look at the imf weighted yield change with IMF. We compare the bottom-heavy Kroupa IMF with the Salpeter IMF (which has more high-mass stars). We see that the total SSP yield changes quite drastically.
|
# Here we show the functionality of the wrapper, which makes the SSP calculation easy.
# We want to show the differences of the SSP feedback for 2 IMFs and load Kroupa first
a.only_net_yields_in_process_tables = False
a.imf_type_name = 'normed_3slope'
a.imf_parameter = (-1.3,-2.2,-2.7,0.5,1.0)
# The feedback can now be calculated by just typing the next three lines
from Chempy.wrapper import SSP_wrap
basic_ssp = SSP_wrap(a)
ssp_mass = float(basic_sfr.sfr[0])
basic_ssp.calculate_feedback(float(basic_solar.z),list(elements_to_trace),list(solar_fractions),np.copy(time_steps), ssp_mass)
# We print the Kroupa IMF feedback
print('Kroupa IMF')
print('Element, total SSP yield, CC-SN yield ([X/Fe] i.e. normalised to solar)')
for element in ['C', 'O', 'Mg', 'Ca', 'Mn', 'Ni']:
element_ssp_sn2 = sum(basic_ssp.sn2_table[element])
element_ssp = sum(basic_ssp.table[element])
element_sun = basic_solar.fractions[np.where(elements == element)]
normalising_element_ssp_sn2 = sum(basic_ssp.sn2_table[normalising_element])
normalising_element_ssp = sum(basic_ssp.table[normalising_element])
normalising_element_sun = basic_solar.fractions[np.where(elements == normalising_element)]
print(element, np.log10(element_ssp/element_sun)-np.log10(normalising_element_ssp/normalising_element_sun), np.log10(element_ssp_sn2/element_sun)-np.log10(normalising_element_ssp_sn2/normalising_element_sun))
# Change to Salpeter
a.imf_type_name = 'salpeter'
a.imf_parameter = (2.35)
# Calculate the SSP feedback
basic_ssp = SSP_wrap(a)
basic_ssp.calculate_feedback(float(basic_solar.z),list(elements_to_trace),list(solar_fractions),np.copy(time_steps), ssp_mass)
# And print the feedback for comparison
print('Salpeter IMF')
print('Element, total SSP yield, CC-SN yield ([X/Fe] i.e. normalised to solar)')
for element in ['C', 'O', 'Mg', 'Ca', 'Mn', 'Ni']:
element_ssp_sn2 = sum(basic_ssp.sn2_table[element])
element_ssp = sum(basic_ssp.table[element])
element_sun = basic_solar.fractions[np.where(elements == element)]
normalising_element_ssp_sn2 = sum(basic_ssp.sn2_table[normalising_element])
normalising_element_ssp = sum(basic_ssp.table[normalising_element])
normalising_element_sun = basic_solar.fractions[np.where(elements == normalising_element)]
print(element, np.log10(element_ssp/element_sun)-np.log10(normalising_element_ssp/normalising_element_sun), np.log10(element_ssp_sn2/element_sun)-np.log10(normalising_element_ssp_sn2/normalising_element_sun))
|
tutorials/4-Simple_stellar_population.ipynb
|
jan-rybizki/Chempy
|
mit
|
Paper plot
Here is the code create a plot similar to figure 4 of the paper.
|
# Loading the default parameters so that we can change them and see what happens with the SSP feedback
a = ModelParameters()
a.high_mass_slope = -2.29
a.N_0 = np.power(10,-2.75)
a.sn1a_time_delay = np.power(10,-0.8)
a.imf_parameter = (0.69, 0.079, a.high_mass_slope)
a.sn1a_parameter = [a.N_0, a.sn1a_time_delay, 1.12, 0.0]
a.mmax = 100
time_steps = np.linspace(0.,13.5,1401)
# Then calculating the feedback table
basic_ssp = SSP_wrap(a)
basic_ssp.calculate_feedback(float(basic_solar.z),list(a.elements_to_trace),list(solar_fractions),np.copy(time_steps), ssp_mass)
alpha = 0.5
factor = 1.05
## Actual plotting
fig = plt.figure(figsize=(8.69,6.69), dpi=100)
ax = fig.add_subplot(111)
ax.plot(time_steps,np.cumsum(basic_ssp.sn2_table["Fe"]),'b', label = 'CC-SN')
ax.annotate(xy = (time_steps[-1]*factor,np.sum(basic_ssp.sn2_table["Fe"])*0.9) ,s = 'Fe',color = 'b')
ax.plot(time_steps,np.cumsum(basic_ssp.sn1a_table["Fe"]), 'r', label = 'SN Ia')
ax.annotate(xy = (time_steps[-1]*factor,np.sum(basic_ssp.sn1a_table["Fe"])) ,s = 'Fe',color = 'r')
ax.plot(time_steps,np.cumsum(basic_ssp.sn2_table["Mg"]),'b')
ax.annotate(xy = (time_steps[-1]*factor,np.sum(basic_ssp.sn2_table["Mg"])) ,s = 'Mg',color = 'b')
ax.plot(time_steps,np.cumsum(basic_ssp.sn1a_table["Mg"]),'r')
ax.annotate(xy = (time_steps[-1]*factor,np.sum(basic_ssp.sn1a_table["Mg"])) ,s = 'Mg',color = 'r')
ax.plot(time_steps,np.ones_like(time_steps)*5e-3,marker = '|', markersize = 10, linestyle = '', color = 'k', alpha = 2*alpha)#, label = 'time-steps')
ax.annotate(xy = (time_steps[1],2.7e-3),s = r'model time-steps with mass of stars dying in M$_\odot$', color = 'k', alpha = 2*alpha)
for numb in [1,2,4,11,38,117,1000]:
if numb < len(time_steps):
plt.annotate(xy = (time_steps[numb],3.5e-3),s = '%.f' %(basic_ssp.inverse_imf[numb]), color = 'k', alpha = 2*alpha)
ax.legend()
ax.set_ylim(2e-5,6e-3)
ax.set_xlim(7e-3,25)
ax.set_title(r'yield of SSP with mass = 1M$_\odot$ and metallicity = Z$_\odot$')
ax.set_ylabel(r"net yield in M$_\odot$")
ax.set_xlabel("time in Gyr")
ax.set_yscale('log')
ax.set_xscale('log')
plt.show()
|
tutorials/4-Simple_stellar_population.ipynb
|
jan-rybizki/Chempy
|
mit
|
Here's our trajectory. The grid happens to correspond with the bins I'll use for the histograms.
|
plt.grid(True)
plt.plot(x, y, 'o-')
|
examples/misc/tutorial_path_histogram.ipynb
|
dwhswenson/openpathsampling
|
mit
|
The first type of histogram is what you'd get from just histogramming the frames.
|
hist = PathHistogram(left_bin_edges=(0.0,0.0), bin_widths=(0.5,0.5),
interpolate=False, per_traj=False)
hist.add_trajectory(trajectory)
HistogramPlotter2D(hist).plot(normed=False, xlim=(0,2.5), ylim=(0, 3.5),
cmap="Blues", vmin=0, vmax=3)
|
examples/misc/tutorial_path_histogram.ipynb
|
dwhswenson/openpathsampling
|
mit
|
The next type of histogram uses that fact that we know this is a trajectory, so we do linear interpolation between the frames. This gives us a count of every time the trajectory enters a given bin. We can use this kind of histogram for free energy plots based on the reweighted path ensemble.
We have several possible interpolation algorithms, so let's show one image for each of them. SubdivideInterpolation is the most exact, but it is also quite slow. The default interpolation is BresenhamLikeInterpolation; this will be used if you just give interpolate=True.
|
hist = PathHistogram(left_bin_edges=(0.0,0.0), bin_widths=(0.5,0.5),
interpolate=SubdivideInterpolation, per_traj=False)
hist.add_trajectory(trajectory)
HistogramPlotter2D(hist).plot(normed=False, xlim=(0,2.5), ylim=(0, 3.5),
cmap="Blues", vmin=0, vmax=3)
hist = PathHistogram(left_bin_edges=(0.0,0.0), bin_widths=(0.5,0.5),
interpolate=BresenhamLikeInterpolation, per_traj=False)
hist.add_trajectory(trajectory)
HistogramPlotter2D(hist).plot(normed=False, xlim=(0,2.5), ylim=(0, 3.5),
cmap="Blues", vmin=0, vmax=3)
hist = PathHistogram(left_bin_edges=(0.0,0.0), bin_widths=(0.5,0.5),
interpolate=BresenhamInterpolation, per_traj=False)
hist.add_trajectory(trajectory)
HistogramPlotter2D(hist).plot(normed=False, xlim=(0,2.5), ylim=(0, 3.5),
cmap="Blues", vmin=0, vmax=3)
|
examples/misc/tutorial_path_histogram.ipynb
|
dwhswenson/openpathsampling
|
mit
|
The next type of histogram uses the interpolation, but also normalizes so that each trajectory only contributes once per bin. This is what we use for a path density plot.
|
hist = PathHistogram(left_bin_edges=(0.0,0.0), bin_widths=(0.5,0.5),
interpolate=SubdivideInterpolation, per_traj=True)
hist.add_trajectory(trajectory)
HistogramPlotter2D(hist).plot(normed=False, xlim=(0,2.5), ylim=(0, 3.5),
cmap="Blues", vmin=0, vmax=3)
|
examples/misc/tutorial_path_histogram.ipynb
|
dwhswenson/openpathsampling
|
mit
|
Of course, we can normalize to one contribution per path while not interpolating. I don't think this is actually useful.
|
hist = PathHistogram(left_bin_edges=(0.0,0.0), bin_widths=(0.5,0.5),
interpolate=False, per_traj=True)
hist.add_trajectory(trajectory)
HistogramPlotter2D(hist).plot(normed=False, xlim=(0,2.5), ylim=(0, 3.5),
cmap="Blues", vmin=0, vmax=3)
|
examples/misc/tutorial_path_histogram.ipynb
|
dwhswenson/openpathsampling
|
mit
|
Hypothetically, it is possible for a path to cut exactly through a corner. It won't happen in the real world, but we would like our interpolation algorithm to get even the unlikely cases right.
|
diag = [(0.25, 0.25), (2.25, 2.25)]
diag_x, diag_y = zip(*diag)
plt.grid(True)
ticks = [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5]
plt.xticks(ticks)
plt.yticks(ticks)
plt.xlim(0, 2.5)
plt.ylim(0, 3.5)
plt.plot(diag_x, diag_y, 'o-')
hist = PathHistogram(left_bin_edges=(0.0,0.0), bin_widths=(0.5,0.5),
interpolate=SubdivideInterpolation, per_traj=True)
hist.add_trajectory(diag)
HistogramPlotter2D(hist).plot(normed=False, xlim=(0,2.5), ylim=(0, 3.5),
cmap="Blues", vmin=0, vmax=3)
|
examples/misc/tutorial_path_histogram.ipynb
|
dwhswenson/openpathsampling
|
mit
|
How would we make this into an actual path density plot? Add the trajectories on top of each other.
|
hist = PathHistogram(left_bin_edges=(0.0,0.0), bin_widths=(0.5,0.5),
interpolate=SubdivideInterpolation, per_traj=True)
hist.add_trajectory(diag, weight=2) # each trajectory can be assigned a weight (useful for RPE)
hist.add_trajectory(trajectory)
HistogramPlotter2D(hist).plot(normed=False, xlim=(0,2.5), ylim=(0, 3.5),
cmap="Blues", vmin=0, vmax=3)
|
examples/misc/tutorial_path_histogram.ipynb
|
dwhswenson/openpathsampling
|
mit
|
Implement Preprocessing Functions
The first thing to do to any dataset is preprocessing. Implement the following preprocessing functions below:
- Lookup Table
- Tokenize Punctuation
Lookup Table
To create a word embedding, you first need to transform the words to ids. In this function, create two dictionaries:
- Dictionary to go from the words to an id, we'll call vocab_to_int
- Dictionary to go from the id to word, we'll call int_to_vocab
Return these dictionaries in the following tuple (vocab_to_int, int_to_vocab)
|
import numpy as np
import problem_unittests as tests
from collections import Counter
def create_lookup_tables(text):
"""
Create lookup tables for vocabulary
:param text: The text of tv scripts split into words
:return: A tuple of dicts (vocab_to_int, int_to_vocab)
"""
# TODO: Implement Function
counts = Counter(text)
vocab = sorted(counts, key=counts.get, reverse=True) # descending order
vocab_to_int = {word: ii for ii, word in enumerate(vocab)}
int_to_vocab = {ii: word for ii, word in enumerate(vocab)}
return vocab_to_int, int_to_vocab
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_create_lookup_tables(create_lookup_tables)
|
tv-script-generation/dlnd_tv_script_generation.ipynb
|
zhuanxuhit/deep-learning
|
mit
|
Tokenize Punctuation
We'll be splitting the script into a word array using spaces as delimiters. However, punctuations like periods and exclamation marks make it hard for the neural network to distinguish between the word "bye" and "bye!".
Implement the function token_lookup to return a dict that will be used to tokenize symbols like "!" into "||Exclamation_Mark||". Create a dictionary for the following symbols where the symbol is the key and value is the token:
- Period ( . )
- Comma ( , )
- Quotation Mark ( " )
- Semicolon ( ; )
- Exclamation mark ( ! )
- Question mark ( ? )
- Left Parentheses ( ( )
- Right Parentheses ( ) )
- Dash ( -- )
- Return ( \n )
This dictionary will be used to token the symbols and add the delimiter (space) around it. This separates the symbols as it's own word, making it easier for the neural network to predict on the next word. Make sure you don't use a token that could be confused as a word. Instead of using the token "dash", try using something like "||dash||".
|
def token_lookup():
"""
Generate a dict to turn punctuation into a token.
:return: Tokenize dictionary where the key is the punctuation and the value is the token
"""
# TODO: Implement Function
return {
'.':"||Period||",
',':"||Comma||",
'"':"||Quotation_Mark||",
';':"||Semicolon||",
'!':"||Exclamation_mark||",
'?':"||Question_mark||",
'(':"||Left_Parentheses||",
')':"||Right_Parentheses||",
'--':"||Dash||",
'\n':"||Return||"
}
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_tokenize(token_lookup)
|
tv-script-generation/dlnd_tv_script_generation.ipynb
|
zhuanxuhit/deep-learning
|
mit
|
Check Point
This is your first checkpoint. If you ever decide to come back to this notebook or have to restart the notebook, you can start from here. The preprocessed data has been saved to disk.
|
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
import helper
import numpy as np
import problem_unittests as tests
int_text, vocab_to_int, int_to_vocab, token_dict = helper.load_preprocess()
|
tv-script-generation/dlnd_tv_script_generation.ipynb
|
zhuanxuhit/deep-learning
|
mit
|
Input
Implement the get_inputs() function to create TF Placeholders for the Neural Network. It should create the following placeholders:
- Input text placeholder named "input" using the TF Placeholder name parameter.
- Targets placeholder
- Learning Rate placeholder
Return the placeholders in the following tuple (Input, Targets, LearningRate)
|
def get_inputs():
"""
Create TF Placeholders for input, targets, and learning rate.
:return: Tuple (input, targets, learning rate)
"""
# TODO: Implement Function
input_ = tf.placeholder(shape=[None,None],name='input',dtype=tf.int32) # input shape = [batch_size, seq_size]
targets = tf.placeholder(shape=[None,None],name='targets',dtype=tf.int32)
learning_rate = tf.placeholder(dtype=tf.float32)
return input_, targets, learning_rate
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_get_inputs(get_inputs)
|
tv-script-generation/dlnd_tv_script_generation.ipynb
|
zhuanxuhit/deep-learning
|
mit
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.