markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Isolines
There are two Isoline functions: isochrones and isodistances. In this guide we will use the isochrones function to calculate walking areas by time for each Starbucks store and the isodistances function to calculate the walking area by distance.
By definition, isolines are concentric polygons that display equal... | from cartoframes.data.services import Isolines
iso_service = Isolines()
_, isochrones_dry_metadata = iso_service.isochrones(geo_gdf, [300, 900, 1800], mode='walk', dry_run=True) | docs/guides/06-Data-Services.ipynb | CartoDB/cartoframes | bsd-3-clause |
Remember to always check the quota using dry_run parameter and available_quota method before running the service! | print('available {0}, required {1}'.format(
iso_service.available_quota(),
isochrones_dry_metadata.get('required_quota'))
)
isochrones_gdf, isochrones_metadata = iso_service.isochrones(geo_gdf, [300, 900, 1800], mode='walk')
isochrones_gdf.head()
from cartoframes.viz import Layer, basic_style, basic_legend
... | docs/guides/06-Data-Services.ipynb | CartoDB/cartoframes | bsd-3-clause |
Isodistances
For isodistances, let's calculate the distance ranges of 100, 500 and 1000 meters. These ranges are input in meters, so they will be 100, 500, and 1000 respectively. | _, isodistances_dry_metadata = iso_service.isodistances(geo_gdf, [100, 500, 1000], mode='walk', dry_run=True)
print('available {0}, required {1}'.format(
iso_service.available_quota(),
isodistances_dry_metadata.get('required_quota'))
)
isodistances_gdf, isodistances_metadata = iso_service.isodistances(geo_gdf... | docs/guides/06-Data-Services.ipynb | CartoDB/cartoframes | bsd-3-clause |
EXERCISE DATASET
Run the colorbot experiment and notice the choosen model_dir
Below is the input function definition,we don't need some of the auxiliar functions anymore
Add this cell and then add the solution to the EXERCISE EXPERIMENT
choose a different model_dir and run the cells
Copy the model_dir of the two model... | def get_input_fn(csv_file, batch_size, num_epochs=1, shuffle=True):
def _parse(line):
# each line: name, red, green, blue
# split line
items = tf.string_split([line],',').values
# get color (r, g, b)
color = tf.string_to_number(items[1:], out_type=tf.float32) / 255.0
... | code_samples/RNN/colorbot/colorbot_solutions.ipynb | mari-linhares/tensorflow-workshop | apache-2.0 |
As a result you will see something like:
We called the original model "sorted_batch" and the model using the simplified input function as "simple_batch"
Notice that both models have basically the same loss in the last step, but the "sorted_batch" model runs way faster , notice the global_step/sec metric, it measures h... | def get_model_fn(rnn_cell_sizes,
label_dimension,
dnn_layer_sizes=[],
optimizer='SGD',
learning_rate=0.01):
def model_fn(features, labels, mode):
color_name = features[COLOR_NAME_KEY]
sequence_length = tf.cast(features... | code_samples/RNN/colorbot/colorbot_solutions.ipynb | mari-linhares/tensorflow-workshop | apache-2.0 |
Edit form information | form.myattribute = "myinformation" | test/forms/test/test_testsuite_1234.ipynb | IS-ENES-Data/submission_forms | apache-2.0 |
Save your form
your form will be stored (the form name consists of your last name plut your keyword) | form_handler.save_form(sf,"..my comment..") # edit my comment info | test/forms/test/test_testsuite_1234.ipynb | IS-ENES-Data/submission_forms | apache-2.0 |
officially submit your form
the form will be submitted to the DKRZ team to process
you also receive a confirmation email with a reference to your online form for future modifications | form_handler.email_form_info(sf)
form_handler.form_submission(sf) | test/forms/test/test_testsuite_1234.ipynb | IS-ENES-Data/submission_forms | apache-2.0 |
TensorFlow 2 início rápido para especialistas
<table class="tfo-notebook-buttons" align="left">
<td><a target="_blank" href="https://www.tensorflow.org/tutorials/quickstart/advanced"><img src="https://www.tensorflow.org/images/tf_logo_32px.png">Ver em TensorFlow.org</a></td>
<td><a target="_blank" href="https://col... | from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow as tf
from tensorflow.keras.layers import Dense, Flatten, Conv2D
from tensorflow.keras import Model | site/pt-br/tutorials/quickstart/advanced.ipynb | tensorflow/docs-l10n | apache-2.0 |
Carregue e prepare o [conjunto de dados MNIST] (http://yann.lecun.com/exdb/mnist/). | mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
# Adicione uma dimensão de canais
x_train = x_train[..., tf.newaxis]
x_test = x_test[..., tf.newaxis] | site/pt-br/tutorials/quickstart/advanced.ipynb | tensorflow/docs-l10n | apache-2.0 |
Use tf.data para agrupar e embaralhar o conjunto de dados: | train_ds = tf.data.Dataset.from_tensor_slices(
(x_train, y_train)).shuffle(10000).batch(32)
test_ds = tf.data.Dataset.from_tensor_slices((x_test, y_test)).batch(32) | site/pt-br/tutorials/quickstart/advanced.ipynb | tensorflow/docs-l10n | apache-2.0 |
Crie o modelo tf.keras usando a Keras [API de subclasse de modelo] (https://www.tensorflow.org/guide/keras#model_subclassing): | class MyModel(Model):
def __init__(self):
super(MyModel, self).__init__()
self.conv1 = Conv2D(32, 3, activation='relu')
self.flatten = Flatten()
self.d1 = Dense(128, activation='relu')
self.d2 = Dense(10, activation='softmax')
def call(self, x):
x = self.conv1(x)
x = self.flatten(x)
... | site/pt-br/tutorials/quickstart/advanced.ipynb | tensorflow/docs-l10n | apache-2.0 |
Escolha uma função otimizadora e de perda para treinamento: | loss_object = tf.keras.losses.SparseCategoricalCrossentropy()
optimizer = tf.keras.optimizers.Adam() | site/pt-br/tutorials/quickstart/advanced.ipynb | tensorflow/docs-l10n | apache-2.0 |
Selecione métricas para medir a perda e a precisão do modelo. Essas métricas acumulam os valores ao longo das épocas e, em seguida, imprimem o resultado geral. | train_loss = tf.keras.metrics.Mean(name='train_loss')
train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='train_accuracy')
test_loss = tf.keras.metrics.Mean(name='test_loss')
test_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='test_accuracy') | site/pt-br/tutorials/quickstart/advanced.ipynb | tensorflow/docs-l10n | apache-2.0 |
Use tf.GradientTape para treinar o modelo: | @tf.function
def train_step(images, labels):
with tf.GradientTape() as tape:
# training=True é necessário apenas se houver camadas com diferentes
# comportamentos durante o treinamento versus inferência (por exemplo, Dropout).
predictions = model(images, training=True)
loss = loss_object(labels, predi... | site/pt-br/tutorials/quickstart/advanced.ipynb | tensorflow/docs-l10n | apache-2.0 |
Teste o modelo: | @tf.function
def test_step(images, labels):
# training=True é necessário apenas se houver camadas com diferentes
# comportamentos durante o treinamento versus inferência (por exemplo, Dropout).
predictions = model(images, training=False)
t_loss = loss_object(labels, predictions)
test_loss(t_loss)
test_accu... | site/pt-br/tutorials/quickstart/advanced.ipynb | tensorflow/docs-l10n | apache-2.0 |
We'll train an autoencoder with these images by flattening them into 784 length vectors. The images from this dataset are already normalized such that the values are between 0 and 1. Let's start by building basically the simplest autoencoder with a single ReLU hidden layer. This layer will be used as the compressed rep... | # Size of the encoding layer (the hidden layer)
encoding_dim = 32
image_size = mnist.train.images.shape[1]
inputs_ = tf.placeholder(tf.float32, (None, image_size), name='inputs')
targets_ = tf.placeholder(tf.float32, (None, image_size), name='targets')
# Output of hidden layer
encoded = tf.layers.dense(inputs_, enco... | autoencoder/Simple_Autoencoder_Solution.ipynb | chusine/dlnd | mit |
Spinning Symmetric Rigid Body setup: The body's orientation in inertial frame $\mathcal I$ is described by a 3-1-2 $(\psi,\theta,\phi)$ rotation: the body is rotated by angle $\psi$ about $\mathbf e_3$ (creating intermediate frame $\mathcal A$), by an angle $\theta$ about $\mathbf a_1$ (creating intermediate frame $\... | bCa = rotMat(1,th);bCa | Notebooks/Spinning Symmetric Rigid Body.ipynb | dsavransky/MAE4060 | mit |
$\left[{}^\mathcal{I}\boldsymbol{\omega}^\mathcal{B}\right]_\mathcal{B}$: | iWb_B = bCa*Matrix([0,0,psid])+ Matrix([thd,0,0]); iWb_B | Notebooks/Spinning Symmetric Rigid Body.ipynb | dsavransky/MAE4060 | mit |
${}^\mathcal{I}\boldsymbol{\omega}^\mathcal{C} = {}^\mathcal{I}\boldsymbol{\omega}^\mathcal{B} + {}^\mathcal{B}\boldsymbol{\omega}^\mathcal{C}$.
$\left[{}^\mathcal{I}\boldsymbol{\omega}^\mathcal{C}\right]_\mathcal{B}$: | iWc_B = iWb_B +Matrix([0,Omega,0]); iWc_B | Notebooks/Spinning Symmetric Rigid Body.ipynb | dsavransky/MAE4060 | mit |
$\left[ \mathbb I_G \right]_\mathcal B$: | IG_B = diag(I1,I2,I1);IG_B | Notebooks/Spinning Symmetric Rigid Body.ipynb | dsavransky/MAE4060 | mit |
$\left[{}^\mathcal{I} \mathbf h_G\right]_\mathcal{B}$: | hG_B = IG_B*iWc_B; hG_B | Notebooks/Spinning Symmetric Rigid Body.ipynb | dsavransky/MAE4060 | mit |
$\vphantom{\frac{\mathrm{d}}{\mathrm{d}t}}^\mathcal{I}\frac{\mathrm{d}}{\mathrm{d}t} {}^\mathcal{I} \mathbf h_G = \vphantom{\frac{\mathrm{d}}{\mathrm{d}t}}^\mathcal{B}\frac{\mathrm{d}}{\mathrm{d}t} {}^\mathcal{I} \mathbf h_G + {}^\mathcal{I}\boldsymbol{\omega}^\mathcal{B} \times \mathbf h_G$.
$\left[\vphantom{\frac{... | dhG_B = difftotalmat(hG_B,t,diffmap) + skew(iWb_B)*hG_B; dhG_B | Notebooks/Spinning Symmetric Rigid Body.ipynb | dsavransky/MAE4060 | mit |
Note that the $\mathbf b_2$ component of ${}^\mathcal{I}\boldsymbol{\omega}^\mathcal{B} \times \mathbf h_G$ is zero: | skew(iWb_B)*hG_B | Notebooks/Spinning Symmetric Rigid Body.ipynb | dsavransky/MAE4060 | mit |
Define $C \triangleq \Omega + \dot\psi\sin\theta$ and substitute into $\left[\vphantom{\frac{\mathrm{d}}{\mathrm{d}t}}^\mathcal{I}\frac{\mathrm{d}}{\mathrm{d}t} {}^\mathcal{I} \mathbf h_G\right]_\mathcal{B}$: | dhG_B_simp = dhG_B.subs(Omega+psid*sin(th),C); dhG_B_simp | Notebooks/Spinning Symmetric Rigid Body.ipynb | dsavransky/MAE4060 | mit |
Assume an external torque generating moment about $G$ of $\mathbf M_G = -M_1\mathbf b_1$: | solve([dhG_B_simp[0] + M1,dhG_B_simp[2]],[thdd,psidd]) | Notebooks/Spinning Symmetric Rigid Body.ipynb | dsavransky/MAE4060 | mit |
Training | batch_size = 100
epochs = 100
samples = []
losses = []
# Only save generator variables
saver = tf.train.Saver(var_list=g_vars)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for e in range(epochs):
for ii in range(mnist.train.num_examples//batch_size):
batch = mnist.t... | gan_mnist/Intro_to_GANs_Solution.ipynb | dataewan/deep-learning | mit |
Helper function to compute the Bit Error Rate (BER) | # helper function to compute the bit error rate
def BER(predictions, labels):
return np.mean(1-np.isclose((predictions > 0.5).astype(float), labels)) | mloc/ch4_Autoencoders/BinaryAutoencoder_AWGN.ipynb | kit-cel/wt | gpl-2.0 |
Define Parameters
Here, we consider the simple AWGN channel. We modulate using a constellation with $M = 2^m$ different symbol. To symbol $i$, we assign the binary representation of $i$ as bit pattern. | # number of bits assigned to symbol
m = 5
# number of symbols
M = 2**m
EbN0 = 10
# noise standard deviation
sigma_n = np.sqrt((1/2/np.log2(M)) * 10**(-EbN0/10)) | mloc/ch4_Autoencoders/BinaryAutoencoder_AWGN.ipynb | kit-cel/wt | gpl-2.0 |
Here, we define the parameters of the neural network and training, generate the validation set and a helping set to show the decision regions | # Bit representation of symbols
binaries = torch.from_numpy(np.reshape(np.unpackbits(np.uint8(np.arange(0,2**m))), (-1,8))).float().to(device)
binaries = binaries[:,(8-m):]
# validation set. Training examples are generated on the fly
N_valid = 100000
# number of neurons in hidden layers at receiver
hidden_neurons_RX_... | mloc/ch4_Autoencoders/BinaryAutoencoder_AWGN.ipynb | kit-cel/wt | gpl-2.0 |
Define the architecture of the autoencoder, i.e. the neural network
This is the main neural network/Autoencoder with transmitter, channel and receiver. Transmitter and receiver each with ELU activation function. Note that the final layer does not use a softmax function, as this function is already included in the Cross... | class Autoencoder(nn.Module):
def __init__(self, hidden_neurons_RX):
super(Autoencoder, self).__init__()
# Define Transmitter Layer: Linear function, M input neurons (symbols), 2 output neurons (real and imaginary part)
self.fcT = nn.Linear(M, 2)
# Define R... | mloc/ch4_Autoencoders/BinaryAutoencoder_AWGN.ipynb | kit-cel/wt | gpl-2.0 |
Train the NN and evaluate it at the end of each epoch
Here the idea is to vary the batch size during training. In the first iterations, we start with a small batch size to rapidly get to a working solution. The closer we come towards the end of the training we increase the batch size. If keeping the batch size small, i... | model = Autoencoder(hidden_neurons_RX)
model.to(device)
loss_fn = nn.BCELoss()
# Adam Optimizer
optimizer = optim.Adam(model.parameters())
# Training parameters
num_epochs = 150
batches_per_epoch = np.linspace(1, 1000, num=num_epochs).astype(int)
# Vary batch size during training
batch_size_per_epoch = np.l... | mloc/ch4_Autoencoders/BinaryAutoencoder_AWGN.ipynb | kit-cel/wt | gpl-2.0 |
Evaluate results
Plt decision region and scatter plot of the validation set. Note that the validation set is only used for computing SERs and plotting, there is no feedback towards the training! | cmap = matplotlib.cm.tab20
base = plt.cm.get_cmap(cmap)
color_list = base.colors
new_color_list = [[t/2 + 0.5 for t in color_list[k]] for k in range(len(color_list))]
# find minimum SER from validation set
min_BER_iter = np.argmin(validation_BERs)
plt.figure(figsize=(10,8))
font = {'size' : 14}
plt.rc('font', **fon... | mloc/ch4_Autoencoders/BinaryAutoencoder_AWGN.ipynb | kit-cel/wt | gpl-2.0 |
Generate animation and save as a gif. (Evaluate results III) | %matplotlib notebook
%matplotlib notebook
# Generate animation
from matplotlib import animation, rc
from matplotlib.animation import PillowWriter # Disable if you don't want to save any GIFs.
font = {'size' : 18}
plt.rc('font', **font)
fig = plt.figure(figsize=(8,6))
ax1 = fig.add_subplot(1,1,1)
ax1.axis('scaled')... | mloc/ch4_Autoencoders/BinaryAutoencoder_AWGN.ipynb | kit-cel/wt | gpl-2.0 |
Step 3: Complete application code in application/main.py
We can set up our server with python using Flask. Below, we've already built out most of the application for you.
The @app.route() decorator defines a function to handle web reqests. Let's say our website is www.example.com. With how our @app.route("/") function ... | %%bash
gsutil -m rm -r gs://$BUCKET/baby_app
gsutil -m cp -r application/ gs://$BUCKET/baby_app | courses/machine_learning/deepdive2/structured/labs/6_serving_babyweight.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Run the below cell, and copy the output into the Google Cloud Shell | %%bash
echo rm -r baby_app/
echo mkdir baby_app/
echo gsutil cp -r gs://$BUCKET/baby_app ./
echo python3 baby_app/main.py | courses/machine_learning/deepdive2/structured/labs/6_serving_babyweight.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Custom layers
<table class="tfo-notebook-buttons" align="left"><td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/tensorflow/blob/master/tensorflow/contrib/eager/python/examples/notebooks/custom_layers.ipynb">
<img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in ... | import tensorflow as tf
tfe = tf.contrib.eager
tf.enable_eager_execution() | tensorflow/contrib/eager/python/examples/notebooks/custom_layers.ipynb | manipopopo/tensorflow | apache-2.0 |
Layers: common sets of useful operations
Most of the time when writing code for machine learning models you want to operate at a higher level of abstraction than individual operations and manipulation of individual variables.
Many machine learning models are expressible as the composition and stacking of relatively sim... | # In the tf.keras.layers package, layers are objects. To construct a layer,
# simply construct the object. Most layers take as a first argument the number
# of output dimensions / channels.
layer = tf.keras.layers.Dense(100)
# The number of input dimensions is often unnecessary, as it can be inferred
# the first time t... | tensorflow/contrib/eager/python/examples/notebooks/custom_layers.ipynb | manipopopo/tensorflow | apache-2.0 |
The full list of pre-existing layers can be seen in the documentation. It includes Dense (a fully-connected layer),
Conv2D, LSTM, BatchNormalization, Dropout, and many others. | # To use a layer, simply call it.
layer(tf.zeros([10, 5]))
# Layers have many useful methods. For example, you can inspect all variables
# in a layer by calling layer.variables. In this case a fully-connected layer
# will have variables for weights and biases.
layer.variables
# The variables are also accessible throu... | tensorflow/contrib/eager/python/examples/notebooks/custom_layers.ipynb | manipopopo/tensorflow | apache-2.0 |
Implementing custom layers
The best way to implement your own layer is extending the tf.keras.Layer class and implementing:
* __init__ , where you can do all input-independent initialization
* build, where you know the shapes of the input tensors and can do the rest of the initialization
* call, where you do the... | class MyDenseLayer(tf.keras.layers.Layer):
def __init__(self, num_outputs):
super(MyDenseLayer, self).__init__()
self.num_outputs = num_outputs
def build(self, input_shape):
self.kernel = self.add_variable("kernel",
shape=[input_shape[-1].value,
... | tensorflow/contrib/eager/python/examples/notebooks/custom_layers.ipynb | manipopopo/tensorflow | apache-2.0 |
Note that you don't have to wait until build is called to create your variables, you can also create them in __init__.
Overall code is easier to read and maintain if it uses standard layers whenever possible, as other readers will be familiar with the behavior of standard layers. If you want to use a layer which is not... | class ResnetIdentityBlock(tf.keras.Model):
def __init__(self, kernel_size, filters):
super(ResnetIdentityBlock, self).__init__(name='')
filters1, filters2, filters3 = filters
self.conv2a = tf.keras.layers.Conv2D(filters1, (1, 1))
self.bn2a = tf.keras.layers.BatchNormalization()
self.conv2b = tf.... | tensorflow/contrib/eager/python/examples/notebooks/custom_layers.ipynb | manipopopo/tensorflow | apache-2.0 |
Much of the time, however, models which compose many layers simply call one layer after the other. This can be done in very little code using tf.keras.Sequential | my_seq = tf.keras.Sequential([tf.keras.layers.Conv2D(1, (1, 1)),
tf.keras.layers.BatchNormalization(),
tf.keras.layers.Conv2D(2, 1,
padding='same'),
tf.keras.layers.BatchN... | tensorflow/contrib/eager/python/examples/notebooks/custom_layers.ipynb | manipopopo/tensorflow | apache-2.0 |
retrieve the NBAR and PQ for the spatiotemporal range of interest | #Define which pixel quality artefacts you want removed from the results
mask_components = {'cloud_acca':'no_cloud',
'cloud_shadow_acca' :'no_cloud_shadow',
'cloud_shadow_fmask' : 'no_cloud_shadow',
'cloud_fmask' :'no_cloud',
'blue_saturated' : False,
'green_saturated' : False,
'red_saturated' : False,
'nir_saturated' :... | notebooks/07_hovmoller_space_time_visualisation.ipynb | data-cube/agdc-v2-examples | apache-2.0 |
Plotting an image, select a location for extracting the hovmoller plot
The interactive widget allows you to select a location (x, y coordinates), the plot will then show all of the time series that fall into the same x coordinate. | #select time slice of interest - this is trial and error until you get a decent image
time_slice_i = 481
rgb = nbar_clean.isel(time =time_slice_i).to_array(dim='color').sel(color=['swir1', 'nir', 'green']).transpose('y', 'x', 'color')
#rgb = nbar_clean.isel(time =time_slice).to_array(dim='color').sel(color=['swir1', 'n... | notebooks/07_hovmoller_space_time_visualisation.ipynb | data-cube/agdc-v2-examples | apache-2.0 |
Fun with MyPETS
Table of Contents
Motivation
Introduction
Problem Statement
Import packages
History of Open Source Movement
How to learn STEM (or MyPETS)
References
Contributors
Appendix
Motivation <a class="anchor" id="hid_why"></a>
Current Choice
<img src=http://www.cctechlimited.com/pics/office1.jpg>
A... | HTML("<img src=../images/office-suite.jpg>") | learn_stem/fun_with_mypets.ipynb | wgong/open_source_learning | apache-2.0 |
Introduction <a class="anchor" id="hid_intro"></a>
Problem Statement <a class="anchor" id="hid_problem"></a>
Import packages <a class="anchor" id="hid_pkg"></a> | # math function
import math
# create np array
import numpy as np
# pandas for data analysis
import pandas as pd
# plotting
import matplotlib.pyplot as plt
%matplotlib inline
# symbolic math
import sympy as sy
# html5
from IPython.display import HTML, SVG, YouTubeVideo
# widgets
from collections import OrderedDict... | learn_stem/fun_with_mypets.ipynb | wgong/open_source_learning | apache-2.0 |
History of Open Source Movement <a class="anchor" id="hid_open_src"></a> | with open('../dataset/open_src_move_v2_1.csv') as csvfile:
reader = csv.DictReader(csvfile)
table_str = '<table>'
table_row = """
<tr><td>{year}</td>
<td><img src={picture}></td>
<td><table>
<tr><td>{person}</td></tr>
<tr><td><a target=new href={subject_url}>{su... | learn_stem/fun_with_mypets.ipynb | wgong/open_source_learning | apache-2.0 |
How to learn STEM <a class="anchor" id="hid_stem"></a> | HTML("Wen calls it -<br><br><br> <font color=red size=+4>M</font><font color=purple>y</font><font color=blue size=+3>P</font><font color=blue size=+4>E</font><font color=green size=+4>T</font><font color=magenta size=+3>S</font><br>") | learn_stem/fun_with_mypets.ipynb | wgong/open_source_learning | apache-2.0 |
The MUV dataset is a challenging benchmark in molecular design that consists of 17 different "targets" where there are only a few "active" compounds per target. The goal of working with this dataset is to make a machine learnign model which achieves high accuracy on held-out compounds at predicting activity. To get sta... | import os
import deepchem as dc
current_dir = os.path.dirname(os.path.realpath("__file__"))
dataset_file = "medium_muv.csv.gz"
full_dataset_file = "muv.csv.gz"
# We use a small version of MUV to make online rendering of notebooks easy. Replace with full_dataset_file
# In order to run the full version of this notebook... | examples/tutorials/05_Putting_Multitask_Learning_to_Work.ipynb | miaecle/deepchem | mit |
Now, let's visualize some compounds from our dataset | from rdkit import Chem
from rdkit.Chem import Draw
from itertools import islice
from IPython.display import Image, display, HTML
def display_images(filenames):
"""Helper to pretty-print images."""
for filename in filenames:
display(Image(filename))
def mols_to_pngs(mols, basename="test"):
"""Helpe... | examples/tutorials/05_Putting_Multitask_Learning_to_Work.ipynb | miaecle/deepchem | mit |
There are 17 datasets total in MUV as we mentioned previously. We're going to train a multitask model that attempts to build a joint model to predict activity across all 17 datasets simultaneously. There's some evidence [2] that multitask training creates more robust models.
As fair warning, from my experience, this e... | MUV_tasks = ['MUV-692', 'MUV-689', 'MUV-846', 'MUV-859', 'MUV-644',
'MUV-548', 'MUV-852', 'MUV-600', 'MUV-810', 'MUV-712',
'MUV-737', 'MUV-858', 'MUV-713', 'MUV-733', 'MUV-652',
'MUV-466', 'MUV-832']
featurizer = dc.feat.CircularFingerprint(size=1024)
loader = dc.data.CSVLoader(
... | examples/tutorials/05_Putting_Multitask_Learning_to_Work.ipynb | miaecle/deepchem | mit |
We'll now want to split our dataset into training, validation, and test sets. We're going to do a simple random split using dc.splits.RandomSplitter. It's worth noting that this will provide overestimates of real generalizability! For better real world estimates of prospective performance, you'll want to use a harder s... | splitter = dc.splits.RandomSplitter(dataset_file)
train_dataset, valid_dataset, test_dataset = splitter.train_valid_test_split(
dataset)
#NOTE THE RENAMING:
valid_dataset, test_dataset = test_dataset, valid_dataset | examples/tutorials/05_Putting_Multitask_Learning_to_Work.ipynb | miaecle/deepchem | mit |
Let's now get started building some models! We'll do some simple hyperparameter searching to build a robust model. | import numpy as np
import numpy.random
params_dict = {"activation": ["relu"],
"momentum": [.9],
"batch_size": [50],
"init": ["glorot_uniform"],
"data_shape": [train_dataset.get_data_shape()],
"learning_rate": [1e-3],
"decay": [1e... | examples/tutorials/05_Putting_Multitask_Learning_to_Work.ipynb | miaecle/deepchem | mit |
Hodrick-Prescott Filter
The Hodrick-Prescott filter separates a time-series $y_t$ into a trend $\tau_t$ and a cyclical component $\zeta_t$
$$y_t = \tau_t + \zeta_t$$
The components are determined by minimizing the following quadratic loss function
$$\min_{\{ \tau_{t}\} }\sum_{t}^{T}\zeta_{t}^{2}+\lambda\sum_{t=1}^{T}\... | gdp_cycle, gdp_trend = sm.tsa.filters.hpfilter(dta.realgdp)
gdp_decomp = dta[['realgdp']]
gdp_decomp["cycle"] = gdp_cycle
gdp_decomp["trend"] = gdp_trend
fig = plt.figure(figsize=(12,8))
ax = fig.add_subplot(111)
gdp_decomp[["realgdp", "trend"]]["2000-03-31":].plot(ax=ax, fontsize=16);
legend = ax.get_legend()
legend... | examples/notebooks/tsa_filters.ipynb | phobson/statsmodels | bsd-3-clause |
Baxter-King approximate band-pass filter: Inflation and Unemployment
Explore the hypothesis that inflation and unemployment are counter-cyclical.
The Baxter-King filter is intended to explictly deal with the periodicty of the business cycle. By applying their band-pass filter to a series, they produce a new series that... | bk_cycles = sm.tsa.filters.bkfilter(dta[["infl","unemp"]]) | examples/notebooks/tsa_filters.ipynb | phobson/statsmodels | bsd-3-clause |
We lose K observations on both ends. It is suggested to use K=12 for quarterly data. | fig = plt.figure(figsize=(12,10))
ax = fig.add_subplot(111)
bk_cycles.plot(ax=ax, style=['r--', 'b-']); | examples/notebooks/tsa_filters.ipynb | phobson/statsmodels | bsd-3-clause |
Christiano-Fitzgerald approximate band-pass filter: Inflation and Unemployment
The Christiano-Fitzgerald filter is a generalization of BK and can thus also be seen as weighted moving average. However, the CF filter is asymmetric about $t$ as well as using the entire series. The implementation of their filter involves t... | print(sm.tsa.stattools.adfuller(dta['unemp'])[:3])
print(sm.tsa.stattools.adfuller(dta['infl'])[:3])
cf_cycles, cf_trend = sm.tsa.filters.cffilter(dta[["infl","unemp"]])
print(cf_cycles.head(10))
fig = plt.figure(figsize=(14,10))
ax = fig.add_subplot(111)
cf_cycles.plot(ax=ax, style=['r--','b-']); | examples/notebooks/tsa_filters.ipynb | phobson/statsmodels | bsd-3-clause |
Check your work | genos_new == [0, 2, 1, 1, 2] | tutorials/genotypes.ipynb | gastonstat/stat259 | mit |
Part 2:
Sometimes there are errors and the genotype cannot be determined. Adapt your code from above to deal with this problem (in this example missing data is assigned NA for "Not Available"). | genos_w_missing = ['AA', 'NA', 'GG', 'AG', 'AG', 'GG', 'NA']
genos_w_missing_new = []
# The missing data should not be converted to a number, but remain 'NA' in the new list | tutorials/genotypes.ipynb | gastonstat/stat259 | mit |
Check your work | genos_w_missing_new == [0, 'NA', 2, 1, 1, 2, 'NA'] | tutorials/genotypes.ipynb | gastonstat/stat259 | mit |
Main Practice
Setup: Open a terminal and run the following commands:
```bash
create a new directory
mkdir python-intro
cd python-intro
download data file, and ipython notebook
curl -O https://raw.githubusercontent.com/gastonstat/stat259/gh-pages/tutorials/genos.txt
curl -O https://raw.githubusercontent.com/gastonstat/s... | # things to be imported
from __future__ import division # if you use python 2.?
from collections import Counter | tutorials/genotypes.ipynb | gastonstat/stat259 | mit |
I. Reading a text file
Some refs about Reading Files:
File Operations: https://github.com/dlab-berkeley/python-fundamentals/blob/master/cheat-sheets/12-Files.ipynb
Reading Text Files: http://www.jarrodmillman.com/rcsds/lectures/reading_text_files.html | # open 'genos.txt' and store values in "genos"
# YOUR CODE | tutorials/genotypes.ipynb | gastonstat/stat259 | mit |
II. Unique Genotypes | # Find the unique values in genos
# YOUR CODE | tutorials/genotypes.ipynb | gastonstat/stat259 | mit |
III. Counting Genotypes
a) Using a for loop | # For loop to count occurrences of AA, AG, GG, NA
# (store results in dictionary "geno_counts")
# YOUR CODE | tutorials/genotypes.ipynb | gastonstat/stat259 | mit |
b) Using count method | # YOUR CODE | tutorials/genotypes.ipynb | gastonstat/stat259 | mit |
c) Using Counter from collections | # YOUR CODE | tutorials/genotypes.ipynb | gastonstat/stat259 | mit |
IV. Function to Calculate Proportions | # Write a function "get_proportions()"
# Parameters: geno_counts (dictionary)
# Returns: dictionary of proportions
# YOUR CODE
# apply your function:
# get_proportions(geno_counts)
# test for function get_proportions()
def test_get_proportions():
# We make a fake dictionary
input_val = {'AA': 2, 'AB': 4, 'BB'... | tutorials/genotypes.ipynb | gastonstat/stat259 | mit |
V. Converting to numeric genotypes | # convert genotypes: AA = 0, AG = 1, GG = 2, NA = NA
# (create a list called "numeric_genos")
# YOUR CODE | tutorials/genotypes.ipynb | gastonstat/stat259 | mit |
VI. Write Numeric Genotypes to a text file | # write values in "numeric_genos" to a file "genos_int.txt"
# YOUR CODE | tutorials/genotypes.ipynb | gastonstat/stat259 | mit |
Now that we have our design, let's generate some synthetic data. We will generate AR1 noise to add to the data; this is not a perfect model of the autocorrelation in fMRI, but it's at least a start towards realistic noise. | from statsmodels.tsa.arima_process import arma_generate_sample
ar1_noise=arma_generate_sample([1,0.3],[1,0.],len(regressor))
beta=4
y=regressor.T*beta + ar1_noise
print y.shape
plt.plot(y.T) | analysis/efficiency/DesignEfficiency.ipynb | poldrack/fmri-analysis-vm | mit |
Now let's fit the general linear model to these data. We will ignore serial autocorrelation for now. | X=numpy.vstack((regressor.T,numpy.ones(y.shape))).T
plt.imshow(X,interpolation='nearest',cmap='gray')
plt.axis('auto')
beta_hat=numpy.linalg.inv(X.T.dot(X)).dot(X.T).dot(y.T)
y_est=X.dot(beta_hat)
plt.plot(y.T,color='blue')
plt.plot(y_est,color='red',linewidth=2)
print X.shape | analysis/efficiency/DesignEfficiency.ipynb | poldrack/fmri-analysis-vm | mit |
Now let's make a function to repeatedly generate data and fit the model. | def efficiency_older(X,c=None):
if not c==None:
c=numpy.ones((X.shape[1]))
else:
c=numpy.array(c)
return 1./c.dot(numpy.linalg.inv(X.T.dot(X))).dot(c)
def efficiency(X,c=None):
""" remove the intercept"""
if not c==None:
c=numpy.ones((X.shape[1]))
else:
c=numpy.a... | analysis/efficiency/DesignEfficiency.ipynb | poldrack/fmri-analysis-vm | mit |
Now let's write a simulation that creates datasets with varying levels of blockiness, runs the previous function 1000 times for each level, and plots mean efficiency. Note that we don't actually need to run it 1000 times for blockiness=1, since that design is exactly the same each time. | nruns=100
blockiness_vals=numpy.arange(0,1.1,0.1)
meaneff_blockiness=numpy.zeros(len(blockiness_vals))
for b in range(len(blockiness_vals)):
eff=numpy.zeros(nruns)
for i in range(nruns):
d_sim,design_sim=create_design_singlecondition(blockiness=blockiness_vals[b])
regressor_sim,_=compute_regres... | analysis/efficiency/DesignEfficiency.ipynb | poldrack/fmri-analysis-vm | mit |
Now let's do a similar simulation looking at the effects of varying block length between 10 seconds and 120 seconds (in steps of 10). since blockiness is 1.0 here, we only need one run per block length. | blocklenvals=numpy.arange(10,120,1)
meaneff_blocklen=numpy.zeros(len(blocklenvals))
sims=[]
for b in range(len(blocklenvals)):
d_sim,design_sim=create_design_singlecondition(blocklength=blocklenvals[b],blockiness=1.)
regressor_sim,_=compute_regressor(design_sim,'spm',numpy.arange(0,len(d_sim)))
... | analysis/efficiency/DesignEfficiency.ipynb | poldrack/fmri-analysis-vm | mit |
Now let's look at the effects of correlation between regressors. We first need to create a function to generate a design with two conditions where we can control the correlation between them. | from mkdesign import create_design_twocondition
d,des1,des2=create_design_twocondition(correlation=1.0)
regressor1,_=compute_regressor(des1,'spm',numpy.arange(0,d.shape[0]))
regressor2,_=compute_regressor(des2,'spm',numpy.arange(0,d.shape[0]))
X=numpy.vstack((regressor1.T,regressor2.T,numpy.ones(y.shape))).T
nruns=1... | analysis/efficiency/DesignEfficiency.ipynb | poldrack/fmri-analysis-vm | mit |
Now let's look at efficiency of estimation of the shape of the HRF, rather than detection of the activation effect. This requires that we use a finite impulse response (FIR) model. | d,design=create_design_singlecondition(blockiness=0.0)
regressor,_=compute_regressor(design,'fir',numpy.arange(0,len(d)),fir_delays=numpy.arange(0,16))
plt.imshow(regressor[:50,:],interpolation='nearest',cmap='gray') | analysis/efficiency/DesignEfficiency.ipynb | poldrack/fmri-analysis-vm | mit |
Now let's simulate the FIR model, and estimate the variance of the fits. |
nruns=100
blockiness_vals=numpy.arange(0,1.1,0.1)
meaneff_fit_blockiness=numpy.zeros(len(blockiness_vals))
meancorr=[]
for b in range(len(blockiness_vals)):
eff=numpy.zeros(nruns)
cc=numpy.zeros(nruns)
for i in range(nruns):
d_sim,design_sim=create_design_singlecondition(blockiness=blockiness_vals[... | analysis/efficiency/DesignEfficiency.ipynb | poldrack/fmri-analysis-vm | mit |
Then connect to ChemSpider by creating a ChemSpider instance using your security token: | # Tip: Store your security token as an environment variable to reduce the chance of accidentally sharing it
import os
mytoken = os.environ['CHEMSPIDER_SECURITY_TOKEN']
cs = ChemSpider(security_token=mytoken) | examples/Getting Started.ipynb | mcs07/ChemSpiPy | mit |
All your interaction with the ChemSpider database should now happen through this ChemSpider object, cs.
Retrieve a Compound
Retrieving information about a specific Compound in the ChemSpider database is simple.
Let’s get the Compound with ChemSpider ID 2157: | comp = cs.get_compound(2157)
comp | examples/Getting Started.ipynb | mcs07/ChemSpiPy | mit |
Now we have a Compound object called comp. We can get various identifiers and calculated properties from this object: | print(comp.molecular_formula)
print(comp.molecular_weight)
print(comp.smiles)
print(comp.common_name) | examples/Getting Started.ipynb | mcs07/ChemSpiPy | mit |
Search for a name
What if you don’t know the ChemSpider ID of the Compound you want? Instead use the search method: | for result in cs.search('glucose'):
print(result) | examples/Getting Started.ipynb | mcs07/ChemSpiPy | mit |
numpy has a handy polyfit function we can use, to let us construct an nth-degree polynomial model of our data that minimizes squared error. Let's try it with a 4th degree polynomial: | x = np.array(pageSpeeds)
y = np.array(purchaseAmount)
p4 = np.poly1d(np.polyfit(x, y, 4))
| MachineLearning/DataScience-Python3/PolynomialRegression.ipynb | martinggww/lucasenlights | cc0-1.0 |
We'll visualize our original scatter plot, together with a plot of our predicted values using the polynomial for page speed times ranging from 0-7 seconds: | import matplotlib.pyplot as plt
xp = np.linspace(0, 7, 100)
plt.scatter(x, y)
plt.plot(xp, p4(xp), c='r')
plt.show() | MachineLearning/DataScience-Python3/PolynomialRegression.ipynb | martinggww/lucasenlights | cc0-1.0 |
Looks pretty good! Let's measure the r-squared error: | from sklearn.metrics import r2_score
r2 = r2_score(y, p4(x))
print(r2)
| MachineLearning/DataScience-Python3/PolynomialRegression.ipynb | martinggww/lucasenlights | cc0-1.0 |
Using the two contig names you sent me it's simplest to do this: | desired_contigs = ['Contig' + str(x) for x in [1131, 3182, 39106, 110, 5958]]
desired_contigs | scanfasta.ipynb | plumbwj01/Barcoding-Fraxinus | apache-2.0 |
If you have a genuinely big file then I would do the following: | grab = [c for c in contigs if c.name in desired_contigs]
len(grab) | scanfasta.ipynb | plumbwj01/Barcoding-Fraxinus | apache-2.0 |
Ya! There's two contigs. | import os
print(os.getcwd())
write_contigs_to_file('data2/sequences_desired.fa', grab)
[c.name for c in grab[:100]]
import os
os.path.realpath('') | scanfasta.ipynb | plumbwj01/Barcoding-Fraxinus | apache-2.0 |
Informal Methods
The most straightforward approach for assessing convergence is based on
simply plotting and inspecting traces and histograms of the observed
MCMC sample. If the trace of values for each of the stochastics exhibits
asymptotic behavior over the last $m$ iterations, this may be
satisfactory evidence for c... | with bioassay_model:
bioassay_trace = sample(10000)
traceplot(bioassay_trace[9000:], varnames=['beta']) | notebooks/6. Model Checking.ipynb | fonnesbeck/PyMC3_Oslo | cc0-1.0 |
A similar approach involves
plotting a histogram for every set of $k$ iterations (perhaps 50-100)
beyond some burn in threshold $n$; if the histograms are not visibly
different among the sample intervals, this may be considered some evidence for
convergence. Note that such diagnostics should be carried out for each
sto... | import matplotlib.pyplot as plt
beta_trace = bioassay_trace['beta']
fig, axes = plt.subplots(2, 5, figsize=(14,6))
axes = axes.ravel()
for i in range(10):
axes[i].hist(beta_trace[500*i:500*(i+1)])
plt.tight_layout() | notebooks/6. Model Checking.ipynb | fonnesbeck/PyMC3_Oslo | cc0-1.0 |
An extension of this approach can be taken
when multiple parallel chains are run, rather than just a single, long
chain. In this case, the final values of $c$ chains run for $n$
iterations are plotted in a histogram; just as above, this is repeated
every $k$ iterations thereafter, and the histograms of the endpoints ar... | with bioassay_model:
bioassay_trace = sample(1000, njobs=2, start=[{'alpha':0.5}, {'alpha':5}])
bioassay_trace.get_values('alpha', chains=0)[0]
plt.plot(bioassay_trace.get_values('alpha', chains=0)[:200], 'r--')
plt.plot(bioassay_trace.get_values('alpha', chains=1)[:200], 'k--') | notebooks/6. Model Checking.ipynb | fonnesbeck/PyMC3_Oslo | cc0-1.0 |
A principal reason that evidence from informal techniques cannot
guarantee convergence is a phenomenon called metastability. Chains may
appear to have converged to the true equilibrium value, displaying
excellent qualities by any of the methods described above. However,
after some period of stability around this value,... | from pymc3 import geweke
with bioassay_model:
tr = sample(2000)
z = geweke(tr, intervals=15)
plt.scatter(*z['alpha'].T)
plt.hlines([-1,1], 0, 1000, linestyles='dotted')
plt.xlim(0, 1000) | notebooks/6. Model Checking.ipynb | fonnesbeck/PyMC3_Oslo | cc0-1.0 |
The arguments expected are the following:
x : The trace of a variable.
first : The fraction of series at the beginning of the trace.
last : The fraction of series at the end to be compared with the section at the beginning.
intervals : The number of segments.
Plotting the output displays the scores in series, making ... | from pymc3 import gelman_rubin
gelman_rubin(bioassay_trace) | notebooks/6. Model Checking.ipynb | fonnesbeck/PyMC3_Oslo | cc0-1.0 |
For the best results, each chain should be initialized to highly
dispersed starting values for each stochastic node.
By default, when calling the forestplot function using nodes with
multiple chains, the $\hat{R}$ values will be plotted alongside the
posterior intervals. | from pymc3 import forestplot
forestplot(bioassay_trace) | notebooks/6. Model Checking.ipynb | fonnesbeck/PyMC3_Oslo | cc0-1.0 |
Autocorrelation | from pymc3 import autocorrplot
autocorrplot(tr);
bioassay_trace['alpha'].shape
from pymc3 import effective_n
effective_n(bioassay_trace) | notebooks/6. Model Checking.ipynb | fonnesbeck/PyMC3_Oslo | cc0-1.0 |
Goodness of Fit
Checking for model convergence is only the first step in the evaluation
of MCMC model outputs. It is possible for an entirely unsuitable model
to converge, so additional steps are needed to ensure that the estimated
model adequately fits the data. One intuitive way of evaluating model
fit is to compare ... | from pymc3 import Normal, Binomial, Deterministic, invlogit
# Samples for each dose level
n = 5 * np.ones(4, dtype=int)
# Log-dose
dose = np.array([-.86, -.3, -.05, .73])
with Model() as model:
# Logit-linear model parameters
alpha = Normal('alpha', 0, 0.01)
beta = Normal('beta', 0, 0.01)
# Calculat... | notebooks/6. Model Checking.ipynb | fonnesbeck/PyMC3_Oslo | cc0-1.0 |
The posterior predictive distribution of deaths uses the same functional
form as the data likelihood, in this case a binomial stochastic. Here is
the corresponding sample from the posterior predictive distribution: | with model:
deaths_sim = Binomial('deaths_sim', n=n, p=theta, shape=4) | notebooks/6. Model Checking.ipynb | fonnesbeck/PyMC3_Oslo | cc0-1.0 |
Notice that the observed stochastic Binomial has been replaced with a stochastic node that is identical in every respect to deaths, except that its values are not fixed to be the observed data -- they are left to vary according to the values of the fitted parameters.
The degree to which simulated data correspond to obs... | with model:
gof_trace = sample(2000)
from pymc3 import forestplot
forestplot(gof_trace, varnames=['deaths_sim']) | notebooks/6. Model Checking.ipynb | fonnesbeck/PyMC3_Oslo | cc0-1.0 |
Exercise: Meta-analysis of beta blocker effectiveness
Carlin (1992) considers a Bayesian approach to meta-analysis, and includes the following examples of 22 trials of beta-blockers to prevent mortality after myocardial infarction.
In a random effects meta-analysis we assume the true effect (on a log-odds scale) $d_i$ ... | r_t_obs = [3, 7, 5, 102, 28, 4, 98, 60, 25, 138, 64, 45, 9, 57, 25, 33, 28, 8, 6, 32, 27, 22]
n_t_obs = [38, 114, 69, 1533, 355, 59, 945, 632, 278,1916, 873, 263, 291, 858, 154, 207, 251, 151, 174, 209, 391, 680]
r_c_obs = [3, 14, 11, 127, 27, 6, 152, 48, 37, 188, 52, 47, 16, 45, 31, 38, 12, 6, 3, 40, 43, 39]
n_c_obs =... | notebooks/6. Model Checking.ipynb | fonnesbeck/PyMC3_Oslo | cc0-1.0 |
Class 9: The Solow growth model
The Solow growth model is at the core of modern theories of growth and business cycles. The Solow model is a model of exogenous growth: long-run growth arises in the model as a consequence of exogenous growth in the labor supply and total factor productivity. The Solow model, like many o... | # Initialize parameters for the simulation (A, s, T, delta, alpha, K0)
# Initialize a variable called capital as a (T+1)x1 array of zeros and set first value to K0
# Compute all capital values by iterating over t from 0 through T
# Print the value of capital at dates 0 and T
# Store the simulated capital da... | winter2017/econ129/python/Econ129_Class_09.ipynb | letsgoexploring/teaching | mit |
The Solow model with exogenous population growth
Now, let's suppose that production is a function of the supply of labor $L_t$:
\begin{align}
Y_t & = AK_t^{\alpha} L_t^{1-\alpha}\tag{6}
\end{align}
The supply of labor grows at an exogenously determined rate $n$ and so it's value is determined recursively by a first-ord... | # Initialize parameters for the simulation (A, s, T, delta, alpha, n, K0, L0)
# Initialize a variable called labor as a (T+1)x1 array of zeros and set first value to L0
# Compute all labor values by iterating over t from 0 through T
# Plot the simulated labor series
# Initialize a variable called capi... | winter2017/econ129/python/Econ129_Class_09.ipynb | letsgoexploring/teaching | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.