markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
.on specifies when something should be executed. In our case when the project has a number of 20 trajectories. This is not yet the case so this event will not do anything unless we simulation more trajectories.
.do specifies the function to be called.
The concept is borrowed from event based languages like often used i... | def hello():
print 'DONE!!!'
return [] # todo: allow for None here
finished = Event().on(ev.on_done).do(hello)
scheduler.add_event(ev)
scheduler.add_event(finished) | examples/rp/3_example_adaptive.ipynb | markovmodel/adaptivemd | lgpl-2.1 |
All events and tasks run parallel or at least get submitted and queue for execution in parallel. RP takes care of the actual execution. | print '# of files', len(project.files) | examples/rp/3_example_adaptive.ipynb | markovmodel/adaptivemd | lgpl-2.1 |
So for now lets run more trajectories and schedule computation of models in regular intervals. | ev1 = Event().on(project.on_ntraj(range(30, 70, 4))).do(task_generator)
ev2 = Event().on(project.on_ntraj(38)).do(lambda: modeller.execute(list(project.trajectories))).repeat().until(ev1.on_done)
scheduler.add_event(ev1)
scheduler.add_event(ev2)
len(project.trajectories)
len(project.models) | examples/rp/3_example_adaptive.ipynb | markovmodel/adaptivemd | lgpl-2.1 |
.repeat means to redo the same task when the last is finished (it will just append an infinite list of conditions to keep on running).
.until specifies a termination condition. The event will not be executed once this condition is met. Makes most sense if you use .repeat or if the trigger condition and stopping should ... | print project.files | examples/rp/3_example_adaptive.ipynb | markovmodel/adaptivemd | lgpl-2.1 |
Strategies (aka the brain)
The brain is just a collection of events. This makes it reuseable and easy to extend. | project.close() | examples/rp/3_example_adaptive.ipynb | markovmodel/adaptivemd | lgpl-2.1 |
First we'll load the text file and convert it into integers for our network to use. Here I'm creating a couple dictionaries to convert the characters to and from integers. Encoding the characters as integers makes it easier to use as input in the network. | with open('jinpingmei.txt', 'r') as f:
text=f.read()
vocab = sorted(set(text))
vocab_to_int = {c: i for i, c in enumerate(vocab)}
int_to_vocab = dict(enumerate(vocab))
encoded = np.array([vocab_to_int[c] for c in text], dtype=np.int32) | intro-to-rnns/Anna_KaRNNa.ipynb | oscarmore2/deep-learning-study | mit |
Let's check out the first 100 characters, make sure everything is peachy. According to the American Book Review, this is the 6th best first line of a book ever. | text[:100] | intro-to-rnns/Anna_KaRNNa.ipynb | oscarmore2/deep-learning-study | mit |
And we can see the characters encoded as integers. | encoded[:100] | intro-to-rnns/Anna_KaRNNa.ipynb | oscarmore2/deep-learning-study | mit |
Since the network is working with individual characters, it's similar to a classification problem in which we are trying to predict the next character from the previous text. Here's how many 'classes' our network has to pick from. | len(vocab) | intro-to-rnns/Anna_KaRNNa.ipynb | oscarmore2/deep-learning-study | mit |
Making training mini-batches
Here is where we'll make our mini-batches for training. Remember that we want our batches to be multiple sequences of some desired number of sequence steps. Considering a simple example, our batches would look like this:
<img src="assets/sequence_batching@1x.png" width=500px>
<br>
We have o... | def get_batches(arr, n_seqs, n_steps):
'''Create a generator that returns batches of size
n_seqs x n_steps from arr.
Arguments
---------
arr: Array you want to make batches from
n_seqs: Batch size, the number of sequences per batch
n_steps: Number of sequence steps ... | intro-to-rnns/Anna_KaRNNa.ipynb | oscarmore2/deep-learning-study | mit |
Now I'll make my data sets and we can check out what's going on here. Here I'm going to use a batch size of 10 and 50 sequence steps. | batches = get_batches(encoded, 10, 50)
x, y = next(batches)
print('x\n', x[:10, :10])
print('\ny\n', y[:10, :10]) | intro-to-rnns/Anna_KaRNNa.ipynb | oscarmore2/deep-learning-study | mit |
If you implemented get_batches correctly, the above output should look something like
```
x
[[55 63 69 22 6 76 45 5 16 35]
[ 5 69 1 5 12 52 6 5 56 52]
[48 29 12 61 35 35 8 64 76 78]
[12 5 24 39 45 29 12 56 5 63]
[ 5 29 6 5 29 78 28 5 78 29]
[ 5 13 6 5 36 69 78 35 52 12]
[63 76 12 5 18 52 1 76 5... | def build_inputs(batch_size, num_steps):
''' Define placeholders for inputs, targets, and dropout
Arguments
---------
batch_size: Batch size, number of sequences per batch
num_steps: Number of sequence steps in a batch
'''
# Declare placeholders we'll feed into... | intro-to-rnns/Anna_KaRNNa.ipynb | oscarmore2/deep-learning-study | mit |
LSTM Cell
Here we will create the LSTM cell we'll use in the hidden layer. We'll use this cell as a building block for the RNN. So we aren't actually defining the RNN here, just the type of cell we'll use in the hidden layer.
We first create a basic LSTM cell with
python
lstm = tf.contrib.rnn.BasicLSTMCell(num_units)
w... | def build_lstm(lstm_size, num_layers, batch_size, keep_prob):
''' Build LSTM cell.
Arguments
---------
keep_prob: Scalar tensor (tf.placeholder) for the dropout keep probability
lstm_size: Size of the hidden layers in the LSTM cells
num_layers: Number of LSTM layers
... | intro-to-rnns/Anna_KaRNNa.ipynb | oscarmore2/deep-learning-study | mit |
RNN Output
Here we'll create the output layer. We need to connect the output of the RNN cells to a full connected layer with a softmax output. The softmax output gives us a probability distribution we can use to predict the next character.
If our input has batch size $N$, number of steps $M$, and the hidden layer has $... | def build_output(lstm_output, in_size, out_size):
''' Build a softmax layer, return the softmax output and logits.
Arguments
---------
x: Input tensor
in_size: Size of the input tensor, for example, size of the LSTM cells
out_size: Size of this softmax layer
... | intro-to-rnns/Anna_KaRNNa.ipynb | oscarmore2/deep-learning-study | mit |
Training loss
Next up is the training loss. We get the logits and targets and calculate the softmax cross-entropy loss. First we need to one-hot encode the targets, we're getting them as encoded characters. Then, reshape the one-hot targets so it's a 2D tensor with size $(MN) \times C$ where $C$ is the number of classe... | def build_loss(logits, targets, lstm_size, num_classes):
''' Calculate the loss from the logits and the targets.
Arguments
---------
logits: Logits from final fully connected layer
targets: Targets for supervised learning
lstm_size: Number of LSTM hidden units
nu... | intro-to-rnns/Anna_KaRNNa.ipynb | oscarmore2/deep-learning-study | mit |
Optimizer
Here we build the optimizer. Normal RNNs have have issues gradients exploding and disappearing. LSTMs fix the disappearance problem, but the gradients can still grow without bound. To fix this, we can clip the gradients above some threshold. That is, if a gradient is larger than that threshold, we set it to t... | def build_optimizer(loss, learning_rate, grad_clip):
''' Build optmizer for training, using gradient clipping.
Arguments:
loss: Network loss
learning_rate: Learning rate for optimizer
'''
# Optimizer for training, using gradient clipping to control exploding gradients
... | intro-to-rnns/Anna_KaRNNa.ipynb | oscarmore2/deep-learning-study | mit |
Build the network
Now we can put all the pieces together and build a class for the network. To actually run data through the LSTM cells, we will use tf.nn.dynamic_rnn. This function will pass the hidden and cell states across LSTM cells appropriately for us. It returns the outputs for each LSTM cell at each step for ea... | class CharRNN:
def __init__(self, num_classes, batch_size=64, num_steps=50,
lstm_size=128, num_layers=2, learning_rate=0.001,
grad_clip=5, sampling=False):
# When we're using this network for sampling later, we'll be passing in
# one characte... | intro-to-rnns/Anna_KaRNNa.ipynb | oscarmore2/deep-learning-study | mit |
Hyperparameters
Here I'm defining the hyperparameters for the network.
batch_size - Number of sequences running through the network in one pass.
num_steps - Number of characters in the sequence the network is trained on. Larger is better typically, the network will learn more long range dependencies. But it takes lon... | batch_size = 128 # Sequences per batch
num_steps = 100 # Number of sequence steps per batch
lstm_size = 512 # Size of hidden layers in LSTMs
num_layers = 2 # Number of LSTM layers
learning_rate = 0.0003 # Learning rate
keep_prob = 0.5 # Dropout keep probability | intro-to-rnns/Anna_KaRNNa.ipynb | oscarmore2/deep-learning-study | mit |
Time for training
This is typical training code, passing inputs and targets into the network, then running the optimizer. Here we also get back the final LSTM state for the mini-batch. Then, we pass that state back into the network so the next batch can continue the state from the previous batch. And every so often (se... | epochs = 50
# Save every N iterations
save_every_n = 200
model = CharRNN(len(vocab), batch_size=batch_size, num_steps=num_steps,
lstm_size=lstm_size, num_layers=num_layers,
learning_rate=learning_rate)
saver = tf.train.Saver(max_to_keep=100)
with tf.Session() as sess:
sess.run(tf.... | intro-to-rnns/Anna_KaRNNa.ipynb | oscarmore2/deep-learning-study | mit |
Saved checkpoints
Read up on saving and loading checkpoints here: https://www.tensorflow.org/programmers_guide/variables | tf.train.get_checkpoint_state('checkpoints') | intro-to-rnns/Anna_KaRNNa.ipynb | oscarmore2/deep-learning-study | mit |
Sampling
Now that the network is trained, we'll can use it to generate new text. The idea is that we pass in a character, then the network will predict the next character. We can use the new one, to predict the next one. And we keep doing this to generate all new text. I also included some functionality to prime the ne... | def pick_top_n(preds, vocab_size, top_n=5):
p = np.squeeze(preds)
p[np.argsort(p)[:-top_n]] = 0
p = p / np.sum(p)
c = np.random.choice(vocab_size, 1, p=p)[0]
return c
def sample(checkpoint, n_samples, lstm_size, vocab_size, prime="The "):
samples = [c for c in prime]
model = CharRNN(len(voc... | intro-to-rnns/Anna_KaRNNa.ipynb | oscarmore2/deep-learning-study | mit |
Here, pass in the path to a checkpoint and sample from the network. | tf.train.latest_checkpoint('checkpoints')
checkpoint = tf.train.latest_checkpoint('checkpoints')
samp = sample(checkpoint, 7000, lstm_size, len(vocab), prime="浪")
print(samp)
checkpoint = 'checkpoints/i200_l512.ckpt'
samp = sample(checkpoint, 1000, lstm_size, len(vocab), prime="Far")
print(samp)
checkpoint = 'checkp... | intro-to-rnns/Anna_KaRNNa.ipynb | oscarmore2/deep-learning-study | mit |
Add py files | sc.addPyFile('pyFiles/my_module.py')
SparkFiles.get('my_module.py') | notebooks/04-miscellaneous/add-python-files-to-spark-cluster.ipynb | MingChen0919/learning-apache-spark | mit |
Use my_module.py
We can import my_module as a python module | from my_module import *
addPyFiles_is_successfull()
sum_two_variables(4,5) | notebooks/04-miscellaneous/add-python-files-to-spark-cluster.ipynb | MingChen0919/learning-apache-spark | mit |
Single files | !h5ls fxe_control_example.h5
from karabo_data import H5File
f = H5File('fxe_control_example.h5')
f.control_sources
f.instrument_sources | docs/Demo.ipynb | European-XFEL/h5tools-py | bsd-3-clause |
Get data by train | for tid, data in f.trains():
print("Processing train", tid)
print("beam iyPos:", data['SA1_XTD2_XGM/DOOCS/MAIN']['beamPosition.iyPos.value'])
break
tid, data = f.train_from_id(10005)
data['FXE_XAD_GEC/CAM/CAMERA:daqOutput']['data.image.dims'] | docs/Demo.ipynb | European-XFEL/h5tools-py | bsd-3-clause |
These are just a few of the ways to access data. The attributes and methods described below for run directories also work with individual files. We expect that it will normally make sense to access a run directory as a single object, rather than working with the files separately.
Run directories
An experimental run is ... | !ls fxe_example_run/
from karabo_data import RunDirectory
run = RunDirectory('fxe_example_run/')
run.files[:3] # The objects for the individual files (see above) | docs/Demo.ipynb | European-XFEL/h5tools-py | bsd-3-clause |
What devices were recording in this run?
Control devices are slow data, recording once per train. Instrument devices includes detector data, but also some other data sources such as cameras. They can have more than one reading per train. | run.control_sources
run.instrument_sources | docs/Demo.ipynb | European-XFEL/h5tools-py | bsd-3-clause |
Which trains are in this run? | print(run.train_ids[:10]) | docs/Demo.ipynb | European-XFEL/h5tools-py | bsd-3-clause |
See the available keys for a given source: | run.keys_for_source('SPB_XTD9_XGM/DOOCS/MAIN:output') | docs/Demo.ipynb | European-XFEL/h5tools-py | bsd-3-clause |
This collects data from across files, including detector data: | for tid, data in run.trains():
print("Processing train", tid)
print("Detctor data module 0 shape:", data['FXE_DET_LPD1M-1/DET/0CH0:xtdf']['image.data'].shape)
break # Stop after the first train to keep the demo short | docs/Demo.ipynb | European-XFEL/h5tools-py | bsd-3-clause |
Train IDs are meant to be globally unique (although there were some glitches with this in the past). A train index is only within this run. | tid, data = run.train_from_id(10005)
tid, data = run.train_from_index(5) | docs/Demo.ipynb | European-XFEL/h5tools-py | bsd-3-clause |
Series data to pandas
Data which holds a single number per train (or per pulse) can be extracted to as series (individual columns) and dataframes (tables) for pandas, a widely-used tool for data manipulation.
karabo_data chains sequence files, which contain successive data from the same source. In this example, trains ... | ixPos = run.get_series('SA1_XTD2_XGM/DOOCS/MAIN', 'beamPosition.ixPos.value')
ixPos.tail(10) | docs/Demo.ipynb | European-XFEL/h5tools-py | bsd-3-clause |
To extract a dataframe, you can select interesting data fields with glob syntax, as often used for selecting files on Unix platforms.
[abc]: one character, a/b/c
?: any one character
*: any sequence of characters | run.get_dataframe(fields=[("*_XGM/*", "*.i[xy]Pos")]) | docs/Demo.ipynb | European-XFEL/h5tools-py | bsd-3-clause |
Labelled arrays
Data with extra dimensions can be handled as xarray labelled arrays.
These are a wrapper around Numpy arrays with indexes which can be used to align them and select data. | xtd2_intensity = run.get_array('SA1_XTD2_XGM/DOOCS/MAIN:output', 'data.intensityTD', extra_dims=['pulseID'])
xtd2_intensity | docs/Demo.ipynb | European-XFEL/h5tools-py | bsd-3-clause |
Here's a brief example of using xarray to align the data and select by train ID. See the examples in the xarray docs for more on what it can do.
In this example data, all the data sources have the same range of train IDs, so aligning them doesn't change anything. In real data, devices may miss some trains that other de... | import xarray as xr
xtd9_intensity = run.get_array('SPB_XTD9_XGM/DOOCS/MAIN:output', 'data.intensityTD', extra_dims=['pulseID'])
# Align two arrays, keep only trains which they both have data for:
xtd2_intensity, xtd9_intensity = xr.align(xtd2_intensity, xtd9_intensity, join='inner')
# Select data for a single train ... | docs/Demo.ipynb | European-XFEL/h5tools-py | bsd-3-clause |
You can also specify a region of interest from an array to load only part of the data: | from karabo_data import by_index
# Select the first 5 trains in this run:
sel = run.select_trains(by_index[:5])
# Get the whole of this array:
arr = sel.get_array('FXE_XAD_GEC/CAM/CAMERA:daqOutput', 'data.image.pixels')
print("Whole array shape:", arr.shape)
# Get a region of interest
arr2 = sel.get_array('FXE_XAD_G... | docs/Demo.ipynb | European-XFEL/h5tools-py | bsd-3-clause |
General information
karabo_data provides a few ways to get general information about what's in data files. First, from Python code: | run.info()
run.detector_info('FXE_DET_LPD1M-1/DET/0CH0:xtdf') | docs/Demo.ipynb | European-XFEL/h5tools-py | bsd-3-clause |
The lsxfel command provides similar information at the command line: | !lsxfel fxe_example_run/RAW-R0450-LPD00-S00000.h5
!lsxfel fxe_example_run/RAW-R0450-DA01-S00000.h5
!lsxfel fxe_example_run | docs/Demo.ipynb | European-XFEL/h5tools-py | bsd-3-clause |
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/hub/tutorials/tf2_object_detection"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a>
</td>
<td>
<a target="_blank" href="https://colab.research.google.com/gi... | # This Colab requires TF 2.5.
!pip install -U "tensorflow>=2.5"
import os
import pathlib
import matplotlib
import matplotlib.pyplot as plt
import io
import scipy.misc
import numpy as np
from six import BytesIO
from PIL import Image, ImageDraw, ImageFont
from six.moves.urllib.request import urlopen
import tensorflow... | site/en-snapshot/hub/tutorials/tf2_object_detection.ipynb | tensorflow/docs-l10n | apache-2.0 |
Utilities
Run the following cell to create some utils that will be needed later:
Helper method to load an image
Map of Model Name to TF Hub handle
List of tuples with Human Keypoints for the COCO 2017 dataset. This is needed for models with keypoints. | # @title Run this!!
def load_image_into_numpy_array(path):
"""Load an image from file into a numpy array.
Puts image into numpy array to feed into tensorflow graph.
Note that by convention we put it into a numpy array with shape
(height, width, channels), where channels=3 for RGB.
Args:
path: the file ... | site/en-snapshot/hub/tutorials/tf2_object_detection.ipynb | tensorflow/docs-l10n | apache-2.0 |
Visualization tools
To visualize the images with the proper detected boxes, keypoints and segmentation, we will use the TensorFlow Object Detection API. To install it we will clone the repo. | # Clone the tensorflow models repository
!git clone --depth 1 https://github.com/tensorflow/models | site/en-snapshot/hub/tutorials/tf2_object_detection.ipynb | tensorflow/docs-l10n | apache-2.0 |
Intalling the Object Detection API | %%bash
sudo apt install -y protobuf-compiler
cd models/research/
protoc object_detection/protos/*.proto --python_out=.
cp object_detection/packages/tf2/setup.py .
python -m pip install .
| site/en-snapshot/hub/tutorials/tf2_object_detection.ipynb | tensorflow/docs-l10n | apache-2.0 |
Now we can import the dependencies we will need later | from object_detection.utils import label_map_util
from object_detection.utils import visualization_utils as viz_utils
from object_detection.utils import ops as utils_ops
%matplotlib inline | site/en-snapshot/hub/tutorials/tf2_object_detection.ipynb | tensorflow/docs-l10n | apache-2.0 |
Load label map data (for plotting).
Label maps correspond index numbers to category names, so that when our convolution network predicts 5, we know that this corresponds to airplane. Here we use internal utility functions, but anything that returns a dictionary mapping integers to appropriate string labels would be fi... | PATH_TO_LABELS = './models/research/object_detection/data/mscoco_label_map.pbtxt'
category_index = label_map_util.create_category_index_from_labelmap(PATH_TO_LABELS, use_display_name=True) | site/en-snapshot/hub/tutorials/tf2_object_detection.ipynb | tensorflow/docs-l10n | apache-2.0 |
Build a detection model and load pre-trained model weights
Here we will choose which Object Detection model we will use.
Select the architecture and it will be loaded automatically.
If you want to change the model to try other architectures later, just change the next cell and execute following ones.
Tip: if you want t... | #@title Model Selection { display-mode: "form", run: "auto" }
model_display_name = 'CenterNet HourGlass104 Keypoints 512x512' # @param ['CenterNet HourGlass104 512x512','CenterNet HourGlass104 Keypoints 512x512','CenterNet HourGlass104 1024x1024','CenterNet HourGlass104 Keypoints 1024x1024','CenterNet Resnet50 V1 FPN 5... | site/en-snapshot/hub/tutorials/tf2_object_detection.ipynb | tensorflow/docs-l10n | apache-2.0 |
Loading the selected model from TensorFlow Hub
Here we just need the model handle that was selected and use the Tensorflow Hub library to load it to memory. | print('loading model...')
hub_model = hub.load(model_handle)
print('model loaded!') | site/en-snapshot/hub/tutorials/tf2_object_detection.ipynb | tensorflow/docs-l10n | apache-2.0 |
Loading an image
Let's try the model on a simple image. To help with this, we provide a list of test images.
Here are some simple things to try out if you are curious:
* Try running inference on your own images, just upload them to colab and load the same way it's done in the cell below.
* Modify some of the input imag... | #@title Image Selection (don't forget to execute the cell!) { display-mode: "form"}
selected_image = 'Beach' # @param ['Beach', 'Dogs', 'Naxos Taverna', 'Beatles', 'Phones', 'Birds']
flip_image_horizontally = False #@param {type:"boolean"}
convert_image_to_grayscale = False #@param {type:"boolean"}
image_path = IMAGES... | site/en-snapshot/hub/tutorials/tf2_object_detection.ipynb | tensorflow/docs-l10n | apache-2.0 |
Doing the inference
To do the inference we just need to call our TF Hub loaded model.
Things you can try:
* Print out result['detection_boxes'] and try to match the box locations to the boxes in the image. Notice that coordinates are given in normalized form (i.e., in the interval [0, 1]).
* inspect other output keys ... | # running inference
results = hub_model(image_np)
# different object detection models have additional results
# all of them are explained in the documentation
result = {key:value.numpy() for key,value in results.items()}
print(result.keys()) | site/en-snapshot/hub/tutorials/tf2_object_detection.ipynb | tensorflow/docs-l10n | apache-2.0 |
Visualizing the results
Here is where we will need the TensorFlow Object Detection API to show the squares from the inference step (and the keypoints when available).
the full documentation of this method can be seen here
Here you can, for example, set min_score_thresh to other values (between 0 and 1) to allow more de... | label_id_offset = 0
image_np_with_detections = image_np.copy()
# Use keypoints if available in detections
keypoints, keypoint_scores = None, None
if 'detection_keypoints' in result:
keypoints = result['detection_keypoints'][0]
keypoint_scores = result['detection_keypoint_scores'][0]
viz_utils.visualize_boxes_and_... | site/en-snapshot/hub/tutorials/tf2_object_detection.ipynb | tensorflow/docs-l10n | apache-2.0 |
[Optional]
Among the available object detection models there's Mask R-CNN and the output of this model allows instance segmentation.
To visualize it we will use the same method we did before but adding an aditional parameter: instance_masks=output_dict.get('detection_masks_reframed', None) | # Handle models with masks:
image_np_with_mask = image_np.copy()
if 'detection_masks' in result:
# we need to convert np.arrays to tensors
detection_masks = tf.convert_to_tensor(result['detection_masks'][0])
detection_boxes = tf.convert_to_tensor(result['detection_boxes'][0])
# Reframe the bbox mask to the im... | site/en-snapshot/hub/tutorials/tf2_object_detection.ipynb | tensorflow/docs-l10n | apache-2.0 |
Permutation | from numpy.random import permutation
def permutate(X):
new_array = permutation(X)
return sum(new_array[0:2435]) - sum(new_array[2435::]) # calculate difference between first group and second
difference = []
for i in range(0,100000):
difference.append(permutate(data.call))
# Co... | exercises/statistics project 2/sliderule_dsi_inferential_statistics_exercise_2.ipynb | RoebideBruijn/datascience-intensive-course | mit |
T-test | nw = sum(data.race == 'w')
nb = sum(data.race == 'b')
kw = sum(data[data.race=='w'].call)
kb = sum(data[data.race=='b'].call)
pw = kw/nw
pb = kb/nb
pw - pb # difference in means
# You should actually use the Z-test, since it's normally distributed and over 30 samples,
# but T-test gives similar results.
from scipy.st... | exercises/statistics project 2/sliderule_dsi_inferential_statistics_exercise_2.ipynb | RoebideBruijn/datascience-intensive-course | mit |
Running
You'll need a celery worker instance and a flower instance running. In one terminal window run
celery worker --loglevel INFO -A proj -E --autoscale 10,3
and in another terminal run
celery flower -A proj
Tasks API
The tasks API is async, meaning calls will return immediatly and you'll need to poll on task stat... | # Done once for the whole docs
import requests, json
api_root = 'http://localhost:5555/api'
task_api = '{}/task'.format(api_root) | docs/api.ipynb | alexmojaki/flower | bsd-3-clause |
async-apply | args = {'args': [1, 2]}
url = '{}/async-apply/tasks.add'.format(task_api)
print(url)
resp = requests.post(url, data=json.dumps(args))
reply = resp.json()
reply | docs/api.ipynb | alexmojaki/flower | bsd-3-clause |
We can see that we created a new task and it's pending. Note that the API is async, meaning it won't wait until the task finish.
apply
For create task and wait results you can use 'apply' API. | args = {'args': [1, 2]}
url = '{}/apply/tasks.add'.format(task_api)
print(url)
resp = requests.post(url, data=json.dumps(args))
reply = resp.json()
reply | docs/api.ipynb | alexmojaki/flower | bsd-3-clause |
result
Gets the task result. This is async and will return immediatly even if the task didn't finish (with state 'PENDING') | url = '{}/result/{}'.format(task_api, reply['task-id'])
print(url)
resp = requests.get(url)
resp.json() | docs/api.ipynb | alexmojaki/flower | bsd-3-clause |
revoke
Revoke a running task. | # Run a task
args = {'args': [1, 2]}
resp = requests.post('{}/async-apply/tasks.sub'.format(task_api), data=json.dumps(args))
reply = resp.json()
# Now revoke it
url = '{}/revoke/{}'.format(task_api, reply['task-id'])
print(url)
resp = requests.post(url, data='terminate=True')
resp.json() | docs/api.ipynb | alexmojaki/flower | bsd-3-clause |
rate-limit
Update rate limit for a task. | worker = 'miki-manjaro' # You'll need to get the worker name from the worker API (seel below)
url = '{}/rate-limit/{}'.format(task_api, worker)
print(url)
resp = requests.post(url, params={'taskname': 'tasks.add', 'ratelimit': '10'})
resp.json() | docs/api.ipynb | alexmojaki/flower | bsd-3-clause |
timeout
Set timeout (both hard and soft) for a task. | url = '{}/timeout/{}'.format(task_api, worker)
print(url)
resp = requests.post(url, params={'taskname': 'tasks.add', 'hard': '3.14', 'soft': '3'}) # You can omit soft or hard
resp.json() | docs/api.ipynb | alexmojaki/flower | bsd-3-clause |
Worker API | # Once for the documentation
worker_api = '{}/worker'.format(api_root) | docs/api.ipynb | alexmojaki/flower | bsd-3-clause |
workers
List workers. | url = '{}/workers'.format(api_root) # Only one not under /worker
print(url)
resp = requests.get(url)
workers = resp.json()
workers | docs/api.ipynb | alexmojaki/flower | bsd-3-clause |
pool/shutdown
Shutdown a worker. | worker = workers.keys()[0]
url = '{}/shutdown/{}'.format(worker_api, worker)
print(url)
resp = requests.post(url)
resp.json() | docs/api.ipynb | alexmojaki/flower | bsd-3-clause |
pool/restart
Restart a worker pool, you need to have CELERYD_POOL_RESTARTS enabled in your configuration). | pool_api = '{}/pool'.format(worker_api)
url = '{}/restart/{}'.format(pool_api, worker)
print(url)
resp = requests.post(url)
resp.json() | docs/api.ipynb | alexmojaki/flower | bsd-3-clause |
pool/grow
Grows worker pool. | url = '{}/grow/{}'.format(pool_api, worker)
print(url)
resp = requests.post(url, params={'n': '10'})
resp.json() | docs/api.ipynb | alexmojaki/flower | bsd-3-clause |
pool/shrink
Shrink worker pool. | url = '{}/shrink/{}'.format(pool_api, worker)
print(url)
resp = requests.post(url, params={'n': '3'})
resp.json() | docs/api.ipynb | alexmojaki/flower | bsd-3-clause |
pool/autoscale
Autoscale a pool. | url = '{}/autoscale/{}'.format(pool_api, worker)
print(url)
resp = requests.post(url, params={'min': '3', 'max': '10'})
resp.json() | docs/api.ipynb | alexmojaki/flower | bsd-3-clause |
queue/add-consumer
Add a consumer to a queue. | queue_api = '{}/queue'.format(worker_api)
url = '{}/add-consumer/{}'.format(queue_api, worker)
print(url)
resp = requests.post(url, params={'queue': 'jokes'})
resp.json() | docs/api.ipynb | alexmojaki/flower | bsd-3-clause |
queue/cancel-consumer
Cancel a consumer queue. | url = '{}/cancel-consumer/{}'.format(queue_api, worker)
print(url)
resp = requests.post(url, params={'queue': 'jokes'})
resp.json() | docs/api.ipynb | alexmojaki/flower | bsd-3-clause |
Queue API
We assume that we've two queues; the default one 'celery' and 'all' | url = '{}/queues/length'.format(api_root)
print(url)
resp = requests.get(url)
resp.json() | docs/api.ipynb | alexmojaki/flower | bsd-3-clause |
We open up a NANOGrav par/tim file combination with libstempo, and plot the residuals. | psr = T.tempopulsar(parfile = T.data + 'B1953+29_NANOGrav_dfg+12.par',
timfile = T.data + 'B1953+29_NANOGrav_dfg+12.tim')
LP.plotres(psr) | demo/libstempo-toasim-demo.ipynb | vallis/libstempo | mit |
We now remove the computed residuals from the TOAs, obtaining (in effect) a perfect realization of the deterministic timing model. The pulsar parameters will have changed somewhat, so make_ideal calls fit() on the pulsar object. | LT.make_ideal(psr)
LP.plotres(psr) | demo/libstempo-toasim-demo.ipynb | vallis/libstempo | mit |
We now add a single line of noise at $10^{6.5}$ Hz, with an amplitude of 10 us. We also put back radiometer noise, with rms amplitude equal to 1x the nominal TOA errors.
All the noise-generating commands take an optional argument seed that will reseed the numpy pseudorandom-number generator, so you are able to reproduc... | #LT.add_line(psr,f=10**6.5,A=1e-5)
LT.add_efac(psr,efac=1.0,seed=1234)
LP.plotres(psr) | demo/libstempo-toasim-demo.ipynb | vallis/libstempo | mit |
We could also add EQUAD quadrature noise (with add_equad) or its coarse-grained version (with add_jitter), but instead we prefer some red noise of "GW-like" amplitude $10^{-12}$ and spectral slope $\gamma = -3$. | LT.add_rednoise(psr,1e-12,3)
LP.plotres(psr) | demo/libstempo-toasim-demo.ipynb | vallis/libstempo | mit |
Or, we may add a GW background as simulated by the tempo2 GWbkgrd plugin (see the docstring below). | LT.add_gwb(psr,flow=1e-8,gwAmp=5e-12)
LP.plotres(psr)
help(LT.add_gwb)
LT.createGWB([psr],Amp=5e-15,gam=13./3.)
LP.plotres(psr) | demo/libstempo-toasim-demo.ipynb | vallis/libstempo | mit |
Refitting will remove some of the power. | psr.fit()
LP.plotres(psr) | demo/libstempo-toasim-demo.ipynb | vallis/libstempo | mit |
All done! We can save the resulting par and tim file, and analyze them with a favorite pipeline. | psr.savepar('B1953+29-simulate.par')
psr.savetim('B1953+29-simulate.tim') | demo/libstempo-toasim-demo.ipynb | vallis/libstempo | mit |
Note that currently the tim file that is output by tempo2 has a spurious "MODE 1" line that tempo2 does not like upon reloading. To erase it, you can do | T.purgetim('B1953+29-simulate.tim') | demo/libstempo-toasim-demo.ipynb | vallis/libstempo | mit |
And if we reload the files we get pack the same thing... | psr2 = T.tempopulsar(parfile = 'B1953+29-simulate.par',
timfile = 'B1953+29-simulate.tim')
LP.plotres(psr2) | demo/libstempo-toasim-demo.ipynb | vallis/libstempo | mit |
It's also possible to obtain a perfect realization of the timing model described in a par file without a tim file, by specifying a new set of observation times (in MJD) and errors (in us). The observation frequency, observatory, and flags can also be specified (see the docstring below). | psr = LT.fakepulsar(parfile=T.data+'B1953+29_NANOGrav_dfg+12.par',
obstimes=N.arange(53000,54800,30)+N.random.randn(60), # observe every 30+-1 days
toaerr=0.1)
LT.add_efac(psr,efac=1.0,seed=1234)
LP.plotres(psr)
help(LT.fakepulsar) | demo/libstempo-toasim-demo.ipynb | vallis/libstempo | mit |
Rather than generating fake TOAs you might want to calculate a pulsar's phase at a particular set of times. Using the tempopulsar object you can input an arbitrary set of observation times and use the residuals to get the pulsar's relative phase. For example: | # create a set of times (in MJD)
obstimes = N.arange(53000, 54800, 10, dtype=N.float128)
toaerr = 1e-3 # set the (probably arbitrary) errors in the times (us)
observatory = "ao" # the observatory
obsfreq = 1440.0 # the observation frequency (MHz)
psr = T.tempopulsar(
parfile="B1953+29-simulate.par",
toas=ob... | demo/libstempo-toasim-demo.ipynb | vallis/libstempo | mit |
The observation times can be input as an array of astropy Time objects. The TOA error values, observatory values, and observation frequencies, can also be arrays of the same length as array of observation times.
If you want to extract phases referenced to a particular epoch, observatory and frequency, you can use the r... | phaseref = psr.phaseresiduals(removemean="refphs", epoch=52973.0, site="@") | demo/libstempo-toasim-demo.ipynb | vallis/libstempo | mit |
Convolution: Naive forward pass
The core of a convolutional network is the convolution operation. In the file cs231n/layers.py, implement the forward pass for the convolution layer in the function conv_forward_naive.
You don't have to worry too much about efficiency at this point; just write the code in whatever way y... | x_shape = (2, 3, 4, 4)
w_shape = (3, 3, 4, 4)
x = np.linspace(-0.1, 0.5, num=np.prod(x_shape)).reshape(x_shape)
w = np.linspace(-0.2, 0.3, num=np.prod(w_shape)).reshape(w_shape)
b = np.linspace(-0.1, 0.2, num=3)
conv_param = {'stride': 2, 'pad': 1}
out, _ = conv_forward_naive(x, w, b, conv_param)
correct_out = np.arra... | CS231n/assignment2/ConvolutionalNetworks.ipynb | ALEXKIRNAS/DataScience | mit |
Aside: Image processing via convolutions
As fun way to both check your implementation and gain a better understanding of the type of operation that convolutional layers can perform, we will set up an input containing two images and manually set up filters that perform common image processing operations (grayscale conve... | from scipy.misc import imread, imresize
kitten, puppy = imread('kitten.jpg'), imread('puppy.jpg')
# kitten is wide, and puppy is already square
d = kitten.shape[1] - kitten.shape[0]
kitten_cropped = kitten[:, d//2:-d//2, :]
img_size = 200 # Make this smaller if it runs too slow
x = np.zeros((2, 3, img_size, img_siz... | CS231n/assignment2/ConvolutionalNetworks.ipynb | ALEXKIRNAS/DataScience | mit |
Convolution: Naive backward pass
Implement the backward pass for the convolution operation in the function conv_backward_naive in the file cs231n/layers.py. Again, you don't need to worry too much about computational efficiency.
When you are done, run the following to check your backward pass with a numeric gradient ch... | np.random.seed(231)
x = np.random.randn(4, 3, 5, 5)
w = np.random.randn(2, 3, 3, 3)
b = np.random.randn(2,)
dout = np.random.randn(4, 2, 5, 5)
conv_param = {'stride': 1, 'pad': 1}
dx_num = eval_numerical_gradient_array(lambda x: conv_forward_naive(x, w, b, conv_param)[0], x, dout)
dw_num = eval_numerical_gradient_arra... | CS231n/assignment2/ConvolutionalNetworks.ipynb | ALEXKIRNAS/DataScience | mit |
Max pooling: Naive forward
Implement the forward pass for the max-pooling operation in the function max_pool_forward_naive in the file cs231n/layers.py. Again, don't worry too much about computational efficiency.
Check your implementation by running the following: | x_shape = (2, 3, 4, 4)
x = np.linspace(-0.3, 0.4, num=np.prod(x_shape)).reshape(x_shape)
pool_param = {'pool_width': 2, 'pool_height': 2, 'stride': 2}
out, _ = max_pool_forward_naive(x, pool_param)
correct_out = np.array([[[[-0.26315789, -0.24842105],
[-0.20421053, -0.18947368]],
... | CS231n/assignment2/ConvolutionalNetworks.ipynb | ALEXKIRNAS/DataScience | mit |
Max pooling: Naive backward
Implement the backward pass for the max-pooling operation in the function max_pool_backward_naive in the file cs231n/layers.py. You don't need to worry about computational efficiency.
Check your implementation with numeric gradient checking by running the following: | np.random.seed(231)
x = np.random.randn(3, 2, 8, 8)
dout = np.random.randn(3, 2, 4, 4)
pool_param = {'pool_height': 2, 'pool_width': 2, 'stride': 2}
dx_num = eval_numerical_gradient_array(lambda x: max_pool_forward_naive(x, pool_param)[0], x, dout)
out, cache = max_pool_forward_naive(x, pool_param)
dx = max_pool_back... | CS231n/assignment2/ConvolutionalNetworks.ipynb | ALEXKIRNAS/DataScience | mit |
Fast layers
Making convolution and pooling layers fast can be challenging. To spare you the pain, we've provided fast implementations of the forward and backward passes for convolution and pooling layers in the file cs231n/fast_layers.py.
The fast convolution implementation depends on a Cython extension; to compile it ... | from cs231n.fast_layers import conv_forward_fast, conv_backward_fast
from time import time
np.random.seed(231)
x = np.random.randn(100, 3, 31, 31)
w = np.random.randn(25, 3, 3, 3)
b = np.random.randn(25,)
dout = np.random.randn(100, 25, 16, 16)
conv_param = {'stride': 2, 'pad': 1}
t0 = time()
out_naive, cache_naive = ... | CS231n/assignment2/ConvolutionalNetworks.ipynb | ALEXKIRNAS/DataScience | mit |
Convolutional "sandwich" layers
Previously we introduced the concept of "sandwich" layers that combine multiple operations into commonly used patterns. In the file cs231n/layer_utils.py you will find sandwich layers that implement a few commonly used patterns for convolutional networks. | from cs231n.layer_utils import conv_relu_pool_forward, conv_relu_pool_backward
np.random.seed(231)
x = np.random.randn(2, 3, 16, 16)
w = np.random.randn(3, 3, 3, 3)
b = np.random.randn(3,)
dout = np.random.randn(2, 3, 8, 8)
conv_param = {'stride': 1, 'pad': 1}
pool_param = {'pool_height': 2, 'pool_width': 2, 'stride': ... | CS231n/assignment2/ConvolutionalNetworks.ipynb | ALEXKIRNAS/DataScience | mit |
Three-layer ConvNet
Now that you have implemented all the necessary layers, we can put them together into a simple convolutional network.
Open the file cs231n/classifiers/cnn.py and complete the implementation of the ThreeLayerConvNet class. Run the following cells to help you debug:
Sanity check loss
After you build a... | model = ThreeLayerConvNet()
N = 50
X = np.random.randn(N, 3, 32, 32)
y = np.random.randint(10, size=N)
loss, grads = model.loss(X, y)
print('Initial loss (no regularization): ', loss)
model.reg = 0.5
loss, grads = model.loss(X, y)
print('Initial loss (with regularization): ', loss) | CS231n/assignment2/ConvolutionalNetworks.ipynb | ALEXKIRNAS/DataScience | mit |
Gradient check
After the loss looks reasonable, use numeric gradient checking to make sure that your backward pass is correct. When you use numeric gradient checking you should use a small amount of artifical data and a small number of neurons at each layer. Note: correct implementations may still have relative errors ... | num_inputs = 2
input_dim = (3, 16, 16)
reg = 0.0
num_classes = 10
np.random.seed(231)
X = np.random.randn(num_inputs, *input_dim)
y = np.random.randint(num_classes, size=num_inputs)
model = ThreeLayerConvNet(num_filters=3, filter_size=3,
input_dim=input_dim, hidden_dim=7,
... | CS231n/assignment2/ConvolutionalNetworks.ipynb | ALEXKIRNAS/DataScience | mit |
Overfit small data
A nice trick is to train your model with just a few training samples. You should be able to overfit small datasets, which will result in very high training accuracy and comparatively low validation accuracy. | np.random.seed(231)
num_train = 100
small_data = {
'X_train': data['X_train'][:num_train],
'y_train': data['y_train'][:num_train],
'X_val': data['X_val'],
'y_val': data['y_val'],
}
model = ThreeLayerConvNet(weight_scale=1e-2)
solver = Solver(model, small_data,
num_epochs=15, batch_size=50,
... | CS231n/assignment2/ConvolutionalNetworks.ipynb | ALEXKIRNAS/DataScience | mit |
Plotting the loss, training accuracy, and validation accuracy should show clear overfitting: | plt.subplot(2, 1, 1)
plt.plot(solver.loss_history, 'o')
plt.xlabel('iteration')
plt.ylabel('loss')
plt.subplot(2, 1, 2)
plt.plot(solver.train_acc_history, '-o')
plt.plot(solver.val_acc_history, '-o')
plt.legend(['train', 'val'], loc='upper left')
plt.xlabel('epoch')
plt.ylabel('accuracy')
plt.show() | CS231n/assignment2/ConvolutionalNetworks.ipynb | ALEXKIRNAS/DataScience | mit |
Train the net
By training the three-layer convolutional network for one epoch, you should achieve greater than 40% accuracy on the training set: | model = ThreeLayerConvNet(weight_scale=0.001, hidden_dim=500, reg=0.001)
solver = Solver(model, data,
num_epochs=1, batch_size=50,
update_rule='adam',
optim_config={
'learning_rate': 1e-3,
},
verbose=True, print_every=20)... | CS231n/assignment2/ConvolutionalNetworks.ipynb | ALEXKIRNAS/DataScience | mit |
Visualize Filters
You can visualize the first-layer convolutional filters from the trained network by running the following: | from cs231n.vis_utils import visualize_grid
grid = visualize_grid(model.params['W1'].transpose(0, 2, 3, 1))
plt.imshow(grid.astype('uint8'))
plt.axis('off')
plt.gcf().set_size_inches(5, 5)
plt.show() | CS231n/assignment2/ConvolutionalNetworks.ipynb | ALEXKIRNAS/DataScience | mit |
Spatial Batch Normalization
We already saw that batch normalization is a very useful technique for training deep fully-connected networks. Batch normalization can also be used for convolutional networks, but we need to tweak it a bit; the modification will be called "spatial batch normalization."
Normally batch-normali... | np.random.seed(231)
# Check the training-time forward pass by checking means and variances
# of features both before and after spatial batch normalization
N, C, H, W = 2, 3, 4, 5
x = 4 * np.random.randn(N, C, H, W) + 10
print('Before spatial batch normalization:')
print(' Shape: ', x.shape)
print(' Means: ', x.mean... | CS231n/assignment2/ConvolutionalNetworks.ipynb | ALEXKIRNAS/DataScience | mit |
Spatial batch normalization: backward
In the file cs231n/layers.py, implement the backward pass for spatial batch normalization in the function spatial_batchnorm_backward. Run the following to check your implementation using a numeric gradient check: | np.random.seed(231)
N, C, H, W = 2, 3, 4, 5
x = 5 * np.random.randn(N, C, H, W) + 12
gamma = np.random.randn(C)
beta = np.random.randn(C)
dout = np.random.randn(N, C, H, W)
bn_param = {'mode': 'train'}
fx = lambda x: spatial_batchnorm_forward(x, gamma, beta, bn_param)[0]
fg = lambda a: spatial_batchnorm_forward(x, gam... | CS231n/assignment2/ConvolutionalNetworks.ipynb | ALEXKIRNAS/DataScience | mit |
Viewing a RAW FITS File
Assume you have a file:
fits_data/raw_fits/single_ccd.fits
...containing an unmodified FITS full frame image.
To get started, open this file and extract a httm.data_structures.raw_converter.SingleCCDRawConverter object.
This is done by calling httm.fits_utilities.raw_fits.raw_converter_from_fi... | import httm
from httm.fits_utilities.raw_fits import raw_converter_from_fits
raw_data = raw_converter_from_fits('fits_data/raw_fits/single_ccd.fits') | test/notebooks/tutorial.ipynb | TESScience/httm | gpl-3.0 |
Each raw image contains the data for a single CCD. It contains 4 slices if it was taken by the instrument, and either 1 or 4 if it was created synthetically.
Below, we visualize the first slice of the image. | matplotlib.pyplot.imshow(raw_data.slices[0].pixels)
matplotlib.pyplot.gca().invert_yaxis() | test/notebooks/tutorial.ipynb | TESScience/httm | gpl-3.0 |
Viewing an Electron Flux FITS Image | from httm.fits_utilities.electron_flux_fits import electron_flux_converter_from_fits
electron_flux_data = electron_flux_converter_from_fits('fits_data/electron_flux_fits/small_simulated_data.fits')
matplotlib.pyplot.imshow(electron_flux_data.slices[0].pixels)
matplotlib.pyplot.gca().invert_yaxis() | test/notebooks/tutorial.ipynb | TESScience/httm | gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.