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 fed...
@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.""" # I...
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 standard...
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 cons...
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(bat...
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...
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...
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_f...
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 #...
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 mu...
"""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) => # h...
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....
# 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 f...
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 Redu...
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: f...
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...
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 ...
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 ...
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 dimen...
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 ...
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...
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 ...
!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 back...
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.matm...
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.gradie...
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 demon...
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) # W...
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 ...
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, sel...
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...
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...
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...
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-orie...
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 ...
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...
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...
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, = mod...
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)...
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 = ...
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 bi...
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...
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_...
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. D...
# 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_netw...
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 loc...
# 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_c...
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 ...
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_r...
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-sh...
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_rin...
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...
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_ra...
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,...
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 ...
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-rewi...
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 ...
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. Aft...
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 g...
# 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): retur...
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 deriv...
# 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...
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 minu...
# 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, '-', col...
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 q...
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, d...
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_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 res...
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.li...
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 b...
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 wh...
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=2...
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 cl...
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 co...
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 use...
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 ...
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 t...
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 ...
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): # ...
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...
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 transpor...
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_nam...
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 sho...
# 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.co...
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 invers...
# 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...
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']...
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_s...
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[...
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') pl...
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.tab...
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', ...
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_fee...
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_i...
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 ...
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...
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 in...
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 = Path...
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), ...
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...
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: - Dict...
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 Functio...
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 token...
def token_lookup(): """ Generate a dict to turn punctuation into a token. :return: Tokenize dictionary where the key is the punctuation and the value is the token """ # TODO: Implement Function return { '.':"||Period||", ',':"||Comma||", '"':"||Quotation_Mark||", ...
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 (Inpu...
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.placeho...
tv-script-generation/dlnd_tv_script_generation.ipynb
zhuanxuhit/deep-learning
mit