markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
A custom function to pick a default device | def get_default_device():
"""Pick GPU if available else CPU"""
if torch.cuda.is_available():
return torch.device('cuda')
else:
return torch.device('cpu')
device = get_default_device()
device
def to_device(data,device):
"""Move tensors to chosen device"""
if isinstance(data,(list,tuple)):
return [t... | _____no_output_____ | MIT | VGG/VGG.ipynb | gowriaddepalli/papers |
Training the model | @torch.no_grad()
def evaluate(model, val_loader):
model.eval()
outputs = [model.validation_step(batch) for batch in val_loader]
return model.validation_epoch_end(outputs)
def fit(epochs, lr, model, train_loader, val_loader, opt_func=torch.optim.SGD):
history = []
train_losses =[]
optimizer = o... | _____no_output_____ | MIT | VGG/VGG.ipynb | gowriaddepalli/papers |
*Accompanying code examples of the book "Introduction to Artificial Neural Networks and Deep Learning: A Practical Guide with Applications in Python" by [Sebastian Raschka](https://sebastianraschka.com). All code examples are released under the [MIT license](https://github.com/rasbt/deep-learning-book/blob/master/LICEN... | %load_ext watermark
%watermark -a 'Sebastian Raschka' -v -p torch | Sebastian Raschka
CPython 3.6.6
IPython 7.1.1
torch 0.4.1
| MIT | code/model_zoo/pytorch_ipynb/convnet-resnet50-celeba-dataparallel.ipynb | wpsliu123/Sebastian_Raschka-Deep-Learning-Book |
Model Zoo -- CNN Gender Classifier (ResNet-50 Architecture, CelebA) with Data Parallelism Network Architecture The network in this notebook is an implementation of the ResNet-50 [1] architecture on the CelebA face dataset [2] to train a gender classifier. References - [1] He, K., Zhang, X., Ren, S., & Sun, J. (20... | import os
import time
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision import transforms
import matplotlib.pyplot as plt
from PIL i... | _____no_output_____ | MIT | code/model_zoo/pytorch_ipynb/convnet-resnet50-celeba-dataparallel.ipynb | wpsliu123/Sebastian_Raschka-Deep-Learning-Book |
Dataset Downloading the Dataset Note that the ~200,000 CelebA face image dataset is relatively large (~1.3 Gb). The download link provided below was provided by the author on the official CelebA website at http://mmlab.ie.cuhk.edu.hk/projects/CelebA.html. 1) Download and unzip the file `img_align_celeba.zip`, which ... | df1 = pd.read_csv('list_attr_celeba.txt', sep="\s+", skiprows=1, usecols=['Male'])
# Make 0 (female) & 1 (male) labels instead of -1 & 1
df1.loc[df1['Male'] == -1, 'Male'] = 0
df1.head()
df2 = pd.read_csv('list_eval_partition.txt', sep="\s+", skiprows=0, header=None)
df2.columns = ['Filename', 'Partition']
df2 = df2.... | (218, 178, 3)
| MIT | code/model_zoo/pytorch_ipynb/convnet-resnet50-celeba-dataparallel.ipynb | wpsliu123/Sebastian_Raschka-Deep-Learning-Book |
Implementing a Custom DataLoader Class | class CelebaDataset(Dataset):
"""Custom Dataset for loading CelebA face images"""
def __init__(self, csv_path, img_dir, transform=None):
df = pd.read_csv(csv_path, index_col=0)
self.img_dir = img_dir
self.csv_path = csv_path
self.img_names = df.index.values
self.y =... | Epoch: 1 | Batch index: 0 | Batch size: 1024
Epoch: 2 | Batch index: 0 | Batch size: 1024
| MIT | code/model_zoo/pytorch_ipynb/convnet-resnet50-celeba-dataparallel.ipynb | wpsliu123/Sebastian_Raschka-Deep-Learning-Book |
Model | ##########################
### SETTINGS
##########################
# Hyperparameters
random_seed = 1
learning_rate = 0.001
num_epochs = 5
# Architecture
num_features = 128*128
num_classes = 2 | _____no_output_____ | MIT | code/model_zoo/pytorch_ipynb/convnet-resnet50-celeba-dataparallel.ipynb | wpsliu123/Sebastian_Raschka-Deep-Learning-Book |
The following code cell that implements the ResNet-34 architecture is a derivative of the code provided at https://pytorch.org/docs/0.4.0/_modules/torchvision/models/resnet.html. | ##########################
### MODEL
##########################
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False)
class Bottleneck(nn.Module):
expansion = 4
... | Using 4 GPUs
| MIT | code/model_zoo/pytorch_ipynb/convnet-resnet50-celeba-dataparallel.ipynb | wpsliu123/Sebastian_Raschka-Deep-Learning-Book |
Training | def compute_accuracy(model, data_loader):
correct_pred, num_examples = 0, 0
for i, (features, targets) in enumerate(data_loader):
features = features.to(device)
targets = targets.to(device)
logits, probas = model(features)
_, predicted_labels = torch.max(probas, 1)
... | Epoch: 001/005 | Batch 0000/0158 | Cost: 0.7133
Epoch: 001/005 | Batch 0050/0158 | Cost: 0.1586
Epoch: 001/005 | Batch 0100/0158 | Cost: 0.1041
Epoch: 001/005 | Batch 0150/0158 | Cost: 0.1345
Epoch: 001/005 | Train: 93.080% | Valid: 94.050%
Time elapsed: 2.74 min
Epoch: 002/005 | Batch 0000/0158 | Cost: 0.1176
Epoch: 0... | MIT | code/model_zoo/pytorch_ipynb/convnet-resnet50-celeba-dataparallel.ipynb | wpsliu123/Sebastian_Raschka-Deep-Learning-Book |
Evaluation | with torch.set_grad_enabled(False): # save memory during inference
print('Test accuracy: %.2f%%' % (compute_accuracy(model, test_loader)))
for batch_idx, (features, targets) in enumerate(test_loader):
features = features
targets = targets
break
plt.imshow(np.transpose(features[0], (1, 2, 0)))
mode... | Probability Female 99.19%
| MIT | code/model_zoo/pytorch_ipynb/convnet-resnet50-celeba-dataparallel.ipynb | wpsliu123/Sebastian_Raschka-Deep-Learning-Book |
Filtering data | df.filter('Close>500').show()
df.filter('Close>500').select('Open').show()
df.filter((df["Close"]> 500) &(df["Open"]< 495)).show()
df.filter((df["Close"]>200) | (df["Open"]< 200)).show()
result = df.filter(df["open"] == 208.330002 ).collect()
type(result[0])
row = result[0]
row.asDict()
for item in result[0]:
prin... | 2010-01-19 00:00:00
208.330002
215.18999900000003
207.240004
215.039995
182501900
27.860484999999997
| MIT | spark/SparkBasic/DataFrames_Basic_Operations.ipynb | AlphaSunny/RecSys |
Examples of matrix products | import pyJvsip as pjv | _____no_output_____ | MIT | doc/notebooks/MatrixProduct.ipynb | rrjudd/jvsip |
Example of matrix product prod | inA=pjv.create('mview_d',2,5).randn(5)
inB=pjv.create('mview_d',5,5).identity
outC=inA.prod(inB)
outC.mprint('%.3f')
print("Frobenius of difference %.2f"%(inA-outC).normFro)
inB=pjv.create('mview_d',2,2).identity
outC=inB.prod(inA)
outC.mprint('%.3f')
print("Frobenius of difference %.2f"%(inA-outC).normFro) | [ 0.508 0.535 0.699 -0.960 0.231;
0.040 -0.477 0.208 0.506 -0.383]
Frobenius of difference 0.00
| MIT | doc/notebooks/MatrixProduct.ipynb | rrjudd/jvsip |
Example of prodjConjugate matrix product | inA=pjv.create('cmview_f',3,4).randn(3)
inB=pjv.create('cmview_f',4,2).randn(4)
outC=inA.prodj(inB)
print('C=A.prodj(B)');
print('A');inA.mprint('%.3f')
print('B');inB.mprint('%.3f')
print('C');outC.mprint('%.3f')
print('test using prod and inB.conj');pjv.prod(inA,(inB.conj),outC).mprint('%.3f') | test using prod and inB.conj
[ 1.384-2.247i -0.287-2.598i;
2.453+1.101i 0.404+0.091i;
-1.963+3.397i -3.496+0.722i]
| MIT | doc/notebooks/MatrixProduct.ipynb | rrjudd/jvsip |
Example of prodhHermitian matrix product | inA=pjv.create('cmview_f',3,4).randn(3)
inB=pjv.create('cmview_f',2,4).randn(4)
outC=inA.prodh(inB)
print('C=A.prodj(B)');
print('A');inA.mprint('%.3f')
print('B');inB.mprint('%.3f')
print('C');outC.mprint('%.3f')
print('test using prod and inB.herm');pjv.prod(inA,(inB.herm),outC).mprint('%.3f') | test using prod and inB.herm
[-2.193+0.832i -0.311+4.938i;
0.322-0.693i -3.759-1.877i;
-0.758+1.496i -2.282+2.687i]
| MIT | doc/notebooks/MatrixProduct.ipynb | rrjudd/jvsip |
Example of prodtTranspose matrix product. | inA=pjv.create('cmview_f',3,4).randn(3)
inB=pjv.create('cmview_f',2,4).randn(4)
outC=inA.prodt(inB)
print('C=A.prodj(B)');
print('A');inA.mprint('%.3f')
print('B');inB.mprint('%.3f')
print('C');outC.mprint('%.3f')
print('test using prod and inB.herm');pjv.prod(inA,(inB.transview),outC).mprint('%.3f')
inA=pjv.create('mv... | [ 0.555 -1.017 -0.534 0.872 -1.029 1.373 -1.534 -2.648 -0.214 2.112;
-0.796 -0.389 0.591 -0.835 -0.654 0.024 3.188 2.993 0.176 -2.690;
-0.202 1.608 -0.422 0.629 1.406 -1.663 -2.301 -2.322 -0.565 2.163]
| MIT | doc/notebooks/MatrixProduct.ipynb | rrjudd/jvsip |
Priority Queue Reference Implementation Operations:For the sake of simplicity, all inputs assumed to be valid**enqueue(data, priority)*** Insert data to the priority queue**dequeue()*** Remove one node from the priority queue with highest priority* If queue is empty, return None | class Node(object):
def __init__(self, data, priority, next=None):
self.data = data
self.priority = priority
self.next = next
class PriorityQueue(object):
def __init__(self):
self.head = None
def enqueue(self, data, priority):
if self.head is None:
se... | 2 with priority of 30
1 with priority of 20
3 with priority of 15
Dequeue 2 with priority of 30
1 with priority of 20
3 with priority of 15
| MIT | DataStructures/PriorityQueue.ipynb | varian97/ComputerScience-Notebook |
May | features_hierarchical_may, transformed_tokens_may, linkage_matrix_may, clusters_may = hierarchical_clustering(best_model_may, tfidf_matrix_may, 2)
agglomerative_clustering(6, features_hierarchical_may, df_may, 2, best_model_may, transformed_tokens_may, clusters_may)
elbow_method(tfidf_matrix_may[clusters_may==2], linka... | _____no_output_____ | MIT | Mediacloud_Hierarchical_clustering.ipynb | gesiscss/media_frames |
September | features_hierarchical_sep, transformed_tokens_sep, linkage_matrix_sep, clusters_sep = hierarchical_clustering(best_model_sep, tfidf_matrix_sep, 10)
agglomerative_clustering(2, features_hierarchical_sep, df_sep, 10, best_model_sep, transformed_tokens_sep, clusters_sep) | _____no_output_____ | MIT | Mediacloud_Hierarchical_clustering.ipynb | gesiscss/media_frames |
REINFORCE in PyTorchJust like we did before for Q-learning, this time we'll design a PyTorch network to learn `CartPole-v0` via policy gradient (REINFORCE).Most of the code in this notebook is taken from approximate Q-learning, so you'll find it more or less familiar and even simpler. | import sys, os
if 'google.colab' in sys.modules and not os.path.exists('.setup_complete'):
!wget -q https://raw.githubusercontent.com/yandexdataschool/Practical_RL/master/setup_colab.sh -O- | bash
!touch .setup_complete
# This code creates a virtual display to draw game images on.
# It will have no effect if y... | _____no_output_____ | Unlicense | week06_policy_based/reinforce_pytorch.ipynb | RomaKoks/Practical_RL |
A caveat: with some versions of `pyglet`, the following cell may crash with `NameError: name 'base' is not defined`. The corresponding bug report is [here](https://github.com/pyglet/pyglet/issues/134). If you see this error, try restarting the kernel. | env = gym.make("CartPole-v0")
# gym compatibility: unwrap TimeLimit
if hasattr(env, '_max_episode_steps'):
env = env.env
env.reset()
n_actions = env.action_space.n
state_dim = env.observation_space.shape
plt.imshow(env.render("rgb_array")) | _____no_output_____ | Unlicense | week06_policy_based/reinforce_pytorch.ipynb | RomaKoks/Practical_RL |
Building the network for REINFORCE For REINFORCE algorithm, we'll need a model that predicts action probabilities given states.For numerical stability, please __do not include the softmax layer into your network architecture__.We'll use softmax or log-softmax where appropriate. | import torch
import torch.nn as nn
# Build a simple neural network that predicts policy logits.
# Keep it simple: CartPole isn't worth deep architectures.
model = nn.Sequential(
<YOUR CODE: define a neural network that predicts policy logits>
) | _____no_output_____ | Unlicense | week06_policy_based/reinforce_pytorch.ipynb | RomaKoks/Practical_RL |
Predict function Note: output value of this function is not a torch tensor, it's a numpy array.So, here gradient calculation is not needed.Use [no_grad](https://pytorch.org/docs/stable/autograd.htmltorch.autograd.no_grad)to suppress gradient calculation.Also, `.detach()` (or legacy `.data` property) can be used instea... | def predict_probs(states):
"""
Predict action probabilities given states.
:param states: numpy array of shape [batch, state_shape]
:returns: numpy array of shape [batch, n_actions]
"""
# convert states, compute logits, use softmax to get probability
<YOUR CODE>
return <YOUR CODE>
test_s... | _____no_output_____ | Unlicense | week06_policy_based/reinforce_pytorch.ipynb | RomaKoks/Practical_RL |
Play the gameWe can now use our newly built agent to play the game. | def generate_session(env, t_max=1000):
"""
Play a full session with REINFORCE agent.
Returns sequences of states, actions, and rewards.
"""
# arrays to record session
states, actions, rewards = [], [], []
s = env.reset()
for t in range(t_max):
# action probabilities array aka p... | _____no_output_____ | Unlicense | week06_policy_based/reinforce_pytorch.ipynb | RomaKoks/Practical_RL |
Computing cumulative rewards$$\begin{align*}G_t &= r_t + \gamma r_{t + 1} + \gamma^2 r_{t + 2} + \ldots \\&= \sum_{i = t}^T \gamma^{i - t} r_i \\&= r_t + \gamma * G_{t + 1}\end{align*}$$ | def get_cumulative_rewards(rewards, # rewards at each step
gamma=0.99 # discount for reward
):
"""
Take a list of immediate rewards r(s,a) for the whole session
and compute cumulative returns (a.k.a. G(s,a) in Sutton '16).
G_t = r_t + gamma*r... | _____no_output_____ | Unlicense | week06_policy_based/reinforce_pytorch.ipynb | RomaKoks/Practical_RL |
Loss function and updatesWe now need to define objective and update over policy gradient.Our objective function is$$ J \approx { 1 \over N } \sum_{s_i,a_i} G(s_i,a_i) $$REINFORCE defines a way to compute the gradient of the expected reward with respect to policy parameters. The formula is as follows:$$ \nabla_\theta ... | def to_one_hot(y_tensor, ndims):
""" helper: take an integer vector and convert it to 1-hot matrix. """
y_tensor = y_tensor.type(torch.LongTensor).view(-1, 1)
y_one_hot = torch.zeros(
y_tensor.size()[0], ndims).scatter_(1, y_tensor, 1)
return y_one_hot
# Your code: define optimizers
optimizer = ... | _____no_output_____ | Unlicense | week06_policy_based/reinforce_pytorch.ipynb | RomaKoks/Practical_RL |
The actual training | for i in range(100):
rewards = [train_on_session(*generate_session(env)) for _ in range(100)] # generate new sessions
print("mean reward:%.3f" % (np.mean(rewards)))
if np.mean(rewards) > 500:
print("You Win!") # but you can train even further
break | _____no_output_____ | Unlicense | week06_policy_based/reinforce_pytorch.ipynb | RomaKoks/Practical_RL |
Results & video | # Record sessions
import gym.wrappers
with gym.wrappers.Monitor(gym.make("CartPole-v0"), directory="videos", force=True) as env_monitor:
sessions = [generate_session(env_monitor) for _ in range(100)]
# Show video. This may not work in some setups. If it doesn't
# work for you, you can download the videos and view... | _____no_output_____ | Unlicense | week06_policy_based/reinforce_pytorch.ipynb | RomaKoks/Practical_RL |
Equivalent layer technique for estimating total magnetization direction: Analysis of the result Importing libraries | % matplotlib inline
import sys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import cPickle as pickle
import datetime
import timeit
import string as st
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
from fatiando.gridder import regular
notebook_name = 'airborne_EQL_ma... | _____no_output_____ | BSD-3-Clause | code/notebooks/synthetic_tests/model_multibody_shallow-seated/airborne_EQL_magdirection_RM_analysis.ipynb | pinga-lab/eqlayer-magnetization-direction |
Plot style | plt.style.use('ggplot') | _____no_output_____ | BSD-3-Clause | code/notebooks/synthetic_tests/model_multibody_shallow-seated/airborne_EQL_magdirection_RM_analysis.ipynb | pinga-lab/eqlayer-magnetization-direction |
Importing my package | dir_modules = '../../../mypackage'
sys.path.append(dir_modules)
import auxiliary_functions as fc | _____no_output_____ | BSD-3-Clause | code/notebooks/synthetic_tests/model_multibody_shallow-seated/airborne_EQL_magdirection_RM_analysis.ipynb | pinga-lab/eqlayer-magnetization-direction |
Loading model | with open('data/model_multi.pickle') as f:
model_multi = pickle.load(f) | _____no_output_____ | BSD-3-Clause | code/notebooks/synthetic_tests/model_multibody_shallow-seated/airborne_EQL_magdirection_RM_analysis.ipynb | pinga-lab/eqlayer-magnetization-direction |
Loading observation points | with open('data/airborne_survey.pickle') as f:
airborne = pickle.load(f) | _____no_output_____ | BSD-3-Clause | code/notebooks/synthetic_tests/model_multibody_shallow-seated/airborne_EQL_magdirection_RM_analysis.ipynb | pinga-lab/eqlayer-magnetization-direction |
Loading data set | with open('data/data_set.pickle') as f:
data = pickle.load(f) | _____no_output_____ | BSD-3-Clause | code/notebooks/synthetic_tests/model_multibody_shallow-seated/airborne_EQL_magdirection_RM_analysis.ipynb | pinga-lab/eqlayer-magnetization-direction |
Loading results | with open('data/result_RM_airb.pickle') as f:
results = pickle.load(f) | _____no_output_____ | BSD-3-Clause | code/notebooks/synthetic_tests/model_multibody_shallow-seated/airborne_EQL_magdirection_RM_analysis.ipynb | pinga-lab/eqlayer-magnetization-direction |
List of saved files | saved_files = [] | _____no_output_____ | BSD-3-Clause | code/notebooks/synthetic_tests/model_multibody_shallow-seated/airborne_EQL_magdirection_RM_analysis.ipynb | pinga-lab/eqlayer-magnetization-direction |
Observation area | print 'Area limits: \n x_max = %.1f m \n x_min = %.1f m \n y_max = %.1f m \n y_min = %.1f m' % (airborne['area'][1],
airborne['area'][0],
... | Area limits:
x_max = 5500.0 m
x_min = -6500.0 m
y_max = 6500.0 m
y_min = -5500.0 m
| BSD-3-Clause | code/notebooks/synthetic_tests/model_multibody_shallow-seated/airborne_EQL_magdirection_RM_analysis.ipynb | pinga-lab/eqlayer-magnetization-direction |
Airborne survey information | print 'Shape : (%.0f,%.0f)'% airborne['shape']
print 'Number of data: %.1f' % airborne['N']
print 'dx: %.1f m' % airborne['dx']
print 'dy: %.1f m ' % airborne['dy'] | Shape : (49,25)
Number of data: 1225.0
dx: 250.0 m
dy: 500.0 m
| BSD-3-Clause | code/notebooks/synthetic_tests/model_multibody_shallow-seated/airborne_EQL_magdirection_RM_analysis.ipynb | pinga-lab/eqlayer-magnetization-direction |
Properties of the model Main field | inc_gf,dec_gf = model_multi['main_field']
print'Main field inclination: %.1f degree' % inc_gf
print'Main field declination: %.1f degree' % dec_gf | Main field inclination: -40.0 degree
Main field declination: -22.0 degree
| BSD-3-Clause | code/notebooks/synthetic_tests/model_multibody_shallow-seated/airborne_EQL_magdirection_RM_analysis.ipynb | pinga-lab/eqlayer-magnetization-direction |
Magnetization direction | print 'Inclination: %.1f degree' % model_multi['inc_R']
print 'Declination: %.1f degree' % model_multi['dec_R']
inc_R,dec_R = model_multi['inc_R'],model_multi['dec_R'] | _____no_output_____ | BSD-3-Clause | code/notebooks/synthetic_tests/model_multibody_shallow-seated/airborne_EQL_magdirection_RM_analysis.ipynb | pinga-lab/eqlayer-magnetization-direction |
Coordinates equivalent sources | h = results['layer_depth']
shape_layer = (airborne['shape'][0],airborne['shape'][1])
xs,ys,zs = regular(airborne['area'],shape_layer,h) | _____no_output_____ | BSD-3-Clause | code/notebooks/synthetic_tests/model_multibody_shallow-seated/airborne_EQL_magdirection_RM_analysis.ipynb | pinga-lab/eqlayer-magnetization-direction |
The best solution using L-curve | m_LM = results['magnetic_moment'][4]
inc_est = results['inc_est'][4]
dec_est = results['dec_est'][4]
mu = results['reg_parameter'][4]
phi = results['phi'][4]
print mu | 350000.0
| BSD-3-Clause | code/notebooks/synthetic_tests/model_multibody_shallow-seated/airborne_EQL_magdirection_RM_analysis.ipynb | pinga-lab/eqlayer-magnetization-direction |
Visualization of the convergence | phi = (np.array(phi)/airborne['x'].size)
title_font = 22
bottom_font = 20
saturation_factor = 1.
plt.close('all')
plt.figure(figsize=(10,10), tight_layout=True)
plt.plot(phi,'b-',linewidth=1.5)
plt.title('Convergence', fontsize=title_font)
plt.xlabel('iteration', fontsize = title_font)
plt.ylabel('Goal function ', fon... | /home/andrelreis/anaconda3/envs/py2/lib/python2.7/site-packages/matplotlib/figure.py:2299: UserWarning: This figure includes Axes that are not compatible with tight_layout, so results might be incorrect.
warnings.warn("This figure includes Axes that are not compatible "
| BSD-3-Clause | code/notebooks/synthetic_tests/model_multibody_shallow-seated/airborne_EQL_magdirection_RM_analysis.ipynb | pinga-lab/eqlayer-magnetization-direction |
Estimated magnetization direction | print (inc_est,dec_est)
print (inc_R,dec_R) | (-25.0, 30.0)
| BSD-3-Clause | code/notebooks/synthetic_tests/model_multibody_shallow-seated/airborne_EQL_magdirection_RM_analysis.ipynb | pinga-lab/eqlayer-magnetization-direction |
Comparison between observed data and predicted data | pred = fc.tfa_layer(airborne['x'],airborne['y'],airborne['z'],
xs,ys,zs,inc_gf,dec_gf,m_LM,inc_est,dec_est)
res = pred - data['tfa_obs_RM_airb']
r_norm,r_mean,r_std = fc.residual(data['tfa_obs_RM_airb'],pred)
title_font = 22
bottom_font = 20
plt.figure(figsize=(28,11), tight_layout=True)
ranges = n... | /home/andrelreis/anaconda3/envs/py2/lib/python2.7/site-packages/matplotlib/axes/_axes.py:6571: UserWarning: The 'normed' kwarg is deprecated, and has been replaced by the 'density' kwarg.
warnings.warn("The 'normed' kwarg is deprecated, and has been "
/home/andrelreis/anaconda3/envs/py2/lib/python2.7/site-packages/ip... | BSD-3-Clause | code/notebooks/synthetic_tests/model_multibody_shallow-seated/airborne_EQL_magdirection_RM_analysis.ipynb | pinga-lab/eqlayer-magnetization-direction |
Positive magnetic-moment distribution | title_font = 22
bottom_font = 20
plt.close('all')
plt.figure(figsize=(10,10), tight_layout=True)
plt.title('Magnetic moment distribution', fontsize=title_font)
plt.contourf(1e-3*ys.reshape(shape_layer),1e-3*xs.reshape(shape_layer),
m_LM.reshape(shape_layer), 40, cmap='inferno')
cb = plt.colorbar(pad=0.01... | _____no_output_____ | BSD-3-Clause | code/notebooks/synthetic_tests/model_multibody_shallow-seated/airborne_EQL_magdirection_RM_analysis.ipynb | pinga-lab/eqlayer-magnetization-direction |
Figure for paper | #title_font = 17
title_font = 5
#bottom_font = 14
bottom_font = 4
hist_font = 5
height_per_width = 17./15.
plt.figure(figsize=(4.33,4.33*height_per_width), tight_layout=True)
ranges = np.abs([data['tfa_obs_RM_airb'].max(),
data['tfa_obs_RM_airb'].min(),
pred.max(), pred.min()]).max()... | /home/andrelreis/anaconda3/envs/py2/lib/python2.7/site-packages/ipykernel_launcher.py:71: MatplotlibDeprecationWarning: scipy.stats.norm.pdf
| BSD-3-Clause | code/notebooks/synthetic_tests/model_multibody_shallow-seated/airborne_EQL_magdirection_RM_analysis.ipynb | pinga-lab/eqlayer-magnetization-direction |
Parsing Natural Language in Python **(C) 2018 by [Damir Cavar](http://damir.cavar.me/)** **License:** [Creative Commons Attribution-ShareAlike 4.0 International License](https://creativecommons.org/licenses/by-sa/4.0/) ([CA BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/)) This is a tutorial related to the ... | import sys | _____no_output_____ | Apache-2.0 | notebooks/Parsing Natural Language in Python.ipynb | peey/python-tutorial-notebooks |
The Grammar Class Let us assume that our Phrase Structure Grammar consists of rules that contain one symbol in the Left-Hand Side, followed by a production symbol, an arrow, and by a list of at least one terminal and symbol. Comments can be introduced using the ** symbol. Every rule has to be contained in one line. | grammarText = """
# PSG1
# small English grammar
# (C) 2005 by Damir Cavar, Indiana University
# Grammar:
S -> NP VP
NP -> N
NP -> Adj N
NP -> Art Adj N
NP -> Art N
NP -> Art N PP
#NP -> Art N NP
VP -> V
VP -> V NP
VP -> Adv V NP
VP -> V PP
VP -> V NP PP
PP -> P NP
# Lexicon:
N -> John
N -> Mary
N -> bench... | _____no_output_____ | Apache-2.0 | notebooks/Parsing Natural Language in Python.ipynb | peey/python-tutorial-notebooks |
We can parse this grammar into a representation that allows us to fetch the left- and the right-hand side of a rule for top- or bottom-up parsing. | class PSG:
def __init__(self, grammar):
self.LHS = {}
self.RHS = {}
self.__read__(grammar)
def __str__(self):
text = ""
for i in self.LHS.keys():
if len(text) > 0:
text += "\n"
for x in self.LHS[i]:
text += i + " ->... | _____no_output_____ | Apache-2.0 | notebooks/Parsing Natural Language in Python.ipynb | peey/python-tutorial-notebooks |
The grammar file: The Top-Down Parser Defining some parameters: | LIFO = -1
FIFO = 0
strategy = FIFO
def tdparse(inp, goal, grammar, agenda):
print("Got : %s\tinput: %s" % (goal, inp))
if goal == inp == []: print("Success")
elif goal == [] or inp == []:
if agenda == []: print("Fail: Agenda empty!")
else:
entry = agenda.pop(strategy)
... | S -> NP VP
NP -> N
NP -> Adj N
NP -> Art Adj N
NP -> Art N
NP -> Art N PP
VP -> V
VP -> V NP
VP -> Adv V NP
VP -> V PP
VP -> V NP PP
PP -> P NP
N -> John
N -> Mary
N -> bench
N -> cat
N -> mouse
Art -> the
Art -> a
Adj -> green
Adj -> yellow
Adj -> big
Adj -> small
Adv -> often
Adv -> yesterday
V -> kissed
V ->... | Apache-2.0 | notebooks/Parsing Natural Language in Python.ipynb | peey/python-tutorial-notebooks |
Mask R-CNN DemoA quick intro to using the pre-trained model to detect and segment objects. | import os
import sys
import random
import math
import numpy as np
import skimage.io
import matplotlib
import matplotlib.pyplot as plt
import cv2,time,json,glob
from IPython.display import clear_output
# Root directory of the project
ROOT_DIR = os.path.abspath("../")
# Import Mask RCNN
sys.path.append(ROOT_DIR) # To... | tensorflow version: 1.15.0
using gpu: True
| MIT | samples/demo.ipynb | jtchilders/Mask_RCNN |
ConfigurationsWe'll be using a model trained on the MS-COCO dataset. The configurations of this model are in the ```CocoConfig``` class in ```coco.py```.For inferencing, modify the configurations a bit to fit the task. To do so, sub-class the ```CocoConfig``` class and override the attributes you need to change. | class InferenceConfig(coco.CocoConfig):
# Set batch size to 1 since we'll be running inference on
# one image at a time. Batch size = GPU_COUNT * IMAGES_PER_GPU
GPU_COUNT = 1
IMAGES_PER_GPU = 10
BATCH_SIZE=10
config = InferenceConfig()
config.display() | _____no_output_____ | MIT | samples/demo.ipynb | jtchilders/Mask_RCNN |
Create Model and Load Trained Weights | # Create model object in inference mode.
model = modellib.MaskRCNN(mode="inference", model_dir=MODEL_DIR, config=config)
# Load weights trained on MS-COCO
model.load_weights(COCO_MODEL_PATH, by_name=True) | _____no_output_____ | MIT | samples/demo.ipynb | jtchilders/Mask_RCNN |
Class NamesThe model classifies objects and returns class IDs, which are integer value that identify each class. Some datasets assign integer values to their classes and some don't. For example, in the MS-COCO dataset, the 'person' class is 1 and 'teddy bear' is 88. The IDs are often sequential, but not always. The CO... | # COCO Class names
# Index of the class in the list is its ID. For example, to get ID of
# the teddy bear class, use: class_names.index('teddy bear')
class_names = ['BG', 'person', 'bicycle', 'car', 'motorcycle', 'airplane',
'bus', 'train', 'truck', 'boat', 'traffic light',
'fire hydrant',... | _____no_output_____ | MIT | samples/demo.ipynb | jtchilders/Mask_RCNN |
Run Object Detection | # Load a random image from the images folder
file_names = next(os.walk(IMAGE_DIR))[2]
image = skimage.io.imread(os.path.join(IMAGE_DIR, random.choice(file_names)))
# Run detection
results = model.detect([image], verbose=1)
# Visualize results
r = results[0]
visualize.display_instances(image, r['rois'], r['masks'], r[... | files: 345
0 of 345
frames per second: 25
WARNING:tensorflow:From /home/jchilders/conda/mask_rcnn/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py:422: The name tf.global_variables is deprecated. Please use tf.compat.v1.global_variables instead.
| MIT | samples/demo.ipynb | jtchilders/Mask_RCNN |
The perceptron - Recognising the MNIST digits Table of contents | %matplotlib inline
from pylab import *
from utils import * | _____no_output_____ | MIT | course/perceptron-MNIST-simulation.ipynb | cecconeurale/neunet-basics |
Let us implement a perceptron that categorize the MNIST images as numbers. As you will see below the behaviour of the network is far from optimal. As we see the network [learns well the training set](Plotting-the-results-of-test). Nevertheless its behaviour in a [test with new digits](Spreading-of-the-network-during-t... | #-----------------------------------------------------------
# training
# Set the number of patterns
n_patterns = 500
# Take 'n_patterns' rows
indices = arange(training_length)
shuffle(indices)
indices = indices[:n_patterns]
# Get patterns
patterns = array(mndata.train_images)[indices]
# Rescale all patterns betwe... | _____no_output_____ | MIT | course/perceptron-MNIST-simulation.ipynb | cecconeurale/neunet-basics |
Let us visualize the first 20 patterns of the trining set: | for i in xrange(20):
# Create a new figure after each 10-th item
if i%10 == 0:
fig = figure(figsize = (20, 1))
# Plot current item (we use the
# function plot_img in our utils.py)
plot_img( to_mat(patterns[i]),
fig, (i%10)+1, windows = 20 )
# show figure after all 1o ... | _____no_output_____ | MIT | course/perceptron-MNIST-simulation.ipynb | cecconeurale/neunet-basics |
Spreading of the network during trainingHere starts the core part, iterating the timesteps. We also divide the training phase in epochs. Each epoch is a single presentation of the whole input pattern series. The sum of squared errors will be grouped by epochs. | # counter of repetitions
# of the series of patterns
epoch = -1
# Iterate trials
for t in xrange(stime) :
# Reiterate the input pattern
# sequence through timesteps
# Reshuffle at the end
# of the series
if t%n_patterns == 0:
shuffle(pattern_indices)
epoch += 1
... | _____no_output_____ | MIT | course/perceptron-MNIST-simulation.ipynb | cecconeurale/neunet-basics |
Plotting the results of trainingWe plot the history of the squared errors through epocs a | fig = figure()
ax = fig.add_subplot(111)
ax.plot(squared_errors)
xlabel("Epochs")
ylabel("Sum of squared errors") | _____no_output_____ | MIT | course/perceptron-MNIST-simulation.ipynb | cecconeurale/neunet-basics |
and a visualization of the weights to each ouput unit. Each set of weights seems to reproduce (in a very raugh manner) a generalization of the target digit. | figure(figsize=(15,2))
for i in xrange(m) :
subplot(1,m,i+1)
title(i)
im = to_mat(w[i,1:])
imshow(im, cmap=cm.bone)
axis('off')
show() | _____no_output_____ | MIT | course/perceptron-MNIST-simulation.ipynb | cecconeurale/neunet-basics |
Testing Initializing data and parametersNow we create a new dataset to test the network and reset some variables: | #-----------------------------------------------------------
# test
# Set the number of patterns
n_patterns = 1000
# Take 'n_patterns' rows
indices = arange(test_length)
shuffle(indices)
indices = indices[:n_patterns]
# Get patterns
patterns = array(mndata.test_images)[indices]
# Rescale all patterns between 0 and... | _____no_output_____ | MIT | course/perceptron-MNIST-simulation.ipynb | cecconeurale/neunet-basics |
Spreading of the network during testThe network react to each test pattern in each spreading timestep: | # Iterate trials
for p in xrange(n_patterns) :
# Aggregate inputs and the bias unit
x = hstack([ 1, patterns[p] ])
# !!!! The dot product becomes a matrix
# product with more than one output unit !!!!
net = dot(w,x)
# output function
y = step(net)
y_index = squeez... | _____no_output_____ | MIT | course/perceptron-MNIST-simulation.ipynb | cecconeurale/neunet-basics |
Let us see what is the proportion of correct answers of the network: |
print "Proportion of correct answers:{}" \
.format(sum(error_store)/float(n_patterns)) | Proportion of correct answers:0.655
| MIT | course/perceptron-MNIST-simulation.ipynb | cecconeurale/neunet-basics |
Plotting the results of testNow we plot few test samples to get the real idea. For each sample we plot the input digit on the top, the answer of the network on the center and the target digit on the left. Squared brakets indicate that the network gave zero or more than one answer. | import matplotlib.gridspec as gridspec
gs = gridspec.GridSpec(8, 4*10)
n_patterns = 20
for p in xrange(n_patterns) :
im = to_mat(input_store[:,p])
k = p%10
if k==0 :
fig = figure(figsize=(15,2))
ax1 = fig.add_subplot(gs[:4,(k*4):(k*4+4)])
ax1.imshow(im, cmap... | _____no_output_____ | MIT | course/perceptron-MNIST-simulation.ipynb | cecconeurale/neunet-basics |
The next cell is just for styling | from IPython.core.display import HTML
def css_styling():
styles = open("../style/ipybn.css", "r").read()
return HTML(styles)
css_styling() | _____no_output_____ | MIT | course/perceptron-MNIST-simulation.ipynb | cecconeurale/neunet-basics |
BE 240 Lecture 4 Sub-SBML Modeling diffusion, shared resources, and compartmentalized systems _Ayush Pandey_ | # This notebook is designed to be converted to a HTML slide show
# To do this in the command prompt type (in the folder containing the notebook):
# jupyter nbconvert BE240_Lecture4_Sub-SBML.ipynb --to slides | _____no_output_____ | BSD-3-Clause | examples/BE240_Lecture4_Sub-SBML.ipynb | BuildACell/subsbml |
  An example: Three different "subsystems" - each with its SBML model Another "signal in mixture" subsystem - models signal in the environment / mixture Using Sub-SBML we can obtain the combined model for such a system with* transport across membrane... | # Import statements
from subsbml.Subsystem import createNewSubsystem, createSubsystem
import numpy as np
import pylab as plt | _____no_output_____ | BSD-3-Clause | examples/BE240_Lecture4_Sub-SBML.ipynb | BuildACell/subsbml |
Transcription Model:Consider the following simple transcription-only model where $G$ is a gene, $T$ is a transcript, and $S$ is the signaling molecule.We can write the following reduced order dynamics:1. $G \xrightarrow[]{\rho_{tx}(G, S)} G + T$; \begin{align} \rho_{tx}(G, S) = G K_{X}\frac{S^{2}}{K_{S}^{2}+S^{2}}\\\e... | # Import SBML models by creating Subsystem class objects
ss1 = createSubsystem('transcription_SBML_model.xml')
ss2 = createSubsystem('translation_SBML_model.xml')
ss1.renameSName('mRNA_T', 'T')
# Combine the two subsystems together
tx_tl_subsystem = ss1 + ss2
# The longer way to do the same thing:
# tx_tl_subsystem... | {'default_bioscrape_generated_model_47961': 'default_bioscrape_generated_model_245758_combined', 'default_bioscrape_generated_model_245758': 'default_bioscrape_generated_model_245758_combined', 'mRNA_T_bioscrape_generated_model_245758': 'mRNA_T_bioscrape_generated_model_245758_1_combined', 'T_bioscrape_generated_model_... | BSD-3-Clause | examples/BE240_Lecture4_Sub-SBML.ipynb | BuildACell/subsbml |
Signal induction model:1. $\varnothing \xrightarrow[]{\rho(I)} S$; \begin{align} \rho(S) = K_{0} \frac{I^2}{K_{I} + I^2}\\\end{align}Here $S$ is the signal produced on induction by an inducer $I$.The lumped parameters $K_{0}$ and $K_S$ model effects of cooperative production of the signal by the inducer. This is the s... | ss3 = createSubsystem('signal_in_mixture.xml')
# Signal subsystem (production of signal molecule)
combined_ss = ss1 + ss2 + ss3
# Alternatively
combined_ss = createNewSubsystem()
combined_ss.combineSubsystems([ss1,ss2,ss3])
# Writing a Subsystem to an SBML file (Export SBML)
combined_ss.writeSBML('txtl_combined.xml... | _____no_output_____ | BSD-3-Clause | examples/BE240_Lecture4_Sub-SBML.ipynb | BuildACell/subsbml |
What does Sub-SBML look for?1. For compartments: if two compartments have the same `name` and the same `size` attributes => they are combined together.1. For species: if two species have the same `name` attribute => they are combined together. If initial amount is not the same, the first amount is set. It is easy to s... | from subsbml.System import System, combineSystems
cell_1 = System('cell_1')
ss1 = createSubsystem('txtl_ss.xml')
ss1.renameSName('S', 'IPTG')
ss2 = createSubsystem('IPTG_reservoir.xml')
IPTG_external_conc = ss2.getSpeciesByName('IPTG').getInitialConcentration()
cell_1.setInternal([ss1])
cell_1.setExternal([ss2])
# ... | _____no_output_____ | BSD-3-Clause | examples/BE240_Lecture4_Sub-SBML.ipynb | BuildACell/subsbml |
System 2 : TX-TL with IPTG reservoir and a simple membrane Membrane : IPTG external and internal diffusion in a one step reversible reaction | from subsbml import System, createSubsystem, combineSystems, createNewSubsystem
ss1 = createSubsystem('txtl_ss.xml')
ss1.renameSName('S','IPTG')
ss2 = createSubsystem('IPTG_reservoir.xml')
# Create a simple IPTG membrane where IPTG goes in an out of the membrane via a reversible reaction
mb2 = createSubsystem('membran... | The subsystem from membrane_IPTG.xml has multiple compartments
| BSD-3-Clause | examples/BE240_Lecture4_Sub-SBML.ipynb | BuildACell/subsbml |
System 3 : TX-TL with IPTG reservoir and a detailed membrane diffusion Membrane : IPTG external binds to a transport protein and forms a complex. This complex causes the diffusion of IPTG in the internal of the cell. | # Create a more detailed IPTG membrane where IPTG binds to an intermediate transporter protein, forms a complex
# then transports out of the cell system to the external environment
mb3 = createSubsystem('membrane_IPTG_detailed.xml', membrane = True)
cell_3 = System('cell_3',ListOfInternalSubsystems = [ss1],
... | _____no_output_____ | BSD-3-Clause | examples/BE240_Lecture4_Sub-SBML.ipynb | BuildACell/subsbml |
[Table of Contents](http://nbviewer.ipython.org/github/rlabbe/Kalman-and-Bayesian-Filters-in-Python/blob/master/table_of_contents.ipynb) The Extended Kalman Filter | #format the book
%matplotlib inline
from __future__ import division, print_function
from book_format import load_style
load_style() | _____no_output_____ | CC-BY-4.0 | 11-Extended-Kalman-Filters.ipynb | galuardi/Kalman-and-Bayesian-Filters-in-Python |
At this point in the book we have developed the theory for the linear Kalman filter. Then, in the last two chapters we broached the topic of using Kalman filters for nonlinear problems. In this chapter we will learn the Extended Kalman filter (EKF). The EKF handles nonlinearity by linearizing the system at the point of... | import ekf_internal
ekf_internal.show_linearization() | _____no_output_____ | CC-BY-4.0 | 11-Extended-Kalman-Filters.ipynb | galuardi/Kalman-and-Bayesian-Filters-in-Python |
If the curve above is the process model, then the dotted lines shows the linearization of that curve for the estimate $x=1.5$.We linearize systems by finding the slope of the curve at the given point:$$\begin{aligned}f(x) &= x^2 -2x \\\frac{df}{dx} &= 2x - 2\end{aligned}$$and then finding its value at the evaluation po... | import ekf_internal
ekf_internal.show_radar_chart() | _____no_output_____ | CC-BY-4.0 | 11-Extended-Kalman-Filters.ipynb | galuardi/Kalman-and-Bayesian-Filters-in-Python |
This gives us the equality $x=\sqrt{slant^2 - altitude^2}$. Design the State Variables We want to track the position of an aircraft assuming a constant velocity and altitude, and measurements of the slant distance to the aircraft. That means we need 3 state variables - horizontal distance, horizonal velocity, and alt... | from math import sqrt
def HJacobian_at(x):
""" compute Jacobian of H matrix at x """
horiz_dist = x[0]
altitude = x[2]
denom = sqrt(horiz_dist**2 + altitude**2)
return array ([[horiz_dist/denom, 0., altitude/denom]]) | _____no_output_____ | CC-BY-4.0 | 11-Extended-Kalman-Filters.ipynb | galuardi/Kalman-and-Bayesian-Filters-in-Python |
Finally, let's provide the code for $h(\mathbf x)$ | def hx(x):
""" compute measurement for slant range that
would correspond to state x.
"""
return (x[0]**2 + x[2]**2) ** 0.5 | _____no_output_____ | CC-BY-4.0 | 11-Extended-Kalman-Filters.ipynb | galuardi/Kalman-and-Bayesian-Filters-in-Python |
Now lets write a simulation for our radar. | from numpy.random import randn
import math
class RadarSim(object):
""" Simulates the radar signal returns from an object
flying at a constant altityude and velocity in 1D.
"""
def __init__(self, dt, pos, vel, alt):
self.pos = pos
self.vel = vel
self.alt = alt
self.... | _____no_output_____ | CC-BY-4.0 | 11-Extended-Kalman-Filters.ipynb | galuardi/Kalman-and-Bayesian-Filters-in-Python |
Design Process and Measurement NoiseThe radar returns the range distance. A good radar can achieve accuracy of $\sigma_{range}= 5$ meters, so we will use that value. This gives us$$\mathbf R = \begin{bmatrix}\sigma_{range}^2\end{bmatrix} = \begin{bmatrix}25\end{bmatrix}$$The design of $\mathbf Q$ requires some discuss... | from filterpy.common import Q_discrete_white_noise
from filterpy.kalman import ExtendedKalmanFilter
from numpy import eye, array, asarray
import numpy as np
dt = 0.05
rk = ExtendedKalmanFilter(dim_x=3, dim_z=1)
radar = RadarSim(dt, pos=0., vel=100., alt=1000.)
# make an imperfect starting guess
rk.x = array([radar.po... | _____no_output_____ | CC-BY-4.0 | 11-Extended-Kalman-Filters.ipynb | galuardi/Kalman-and-Bayesian-Filters-in-Python |
Using SymPy to compute Jacobians Depending on your experience with derivatives you may have found the computation of the Jacobian difficult. Even if you found it easy, a slightly more difficult problem easily leads to very difficult computations.As explained in Appendix A, we can use the SymPy package to compute the J... | import sympy
sympy.init_printing(use_latex=True)
x, x_vel, y = sympy.symbols('x, x_vel y')
H = sympy.Matrix([sympy.sqrt(x**2 + y**2)])
state = sympy.Matrix([x, x_vel, y])
H.jacobian(state) | _____no_output_____ | CC-BY-4.0 | 11-Extended-Kalman-Filters.ipynb | galuardi/Kalman-and-Bayesian-Filters-in-Python |
This result is the same as the result we computed above, and with much less effort on our part! Robot LocalizationSo, time to try a real problem. I warn you that this is far from a simple problem. However, most books choose simple, textbook problems with simple answers, and you are left wondering how to implement a re... | ekf_internal.plot_bicycle() | _____no_output_____ | CC-BY-4.0 | 11-Extended-Kalman-Filters.ipynb | galuardi/Kalman-and-Bayesian-Filters-in-Python |
In the **Unscented Kalman Filter** chapter we derived these equations describing for this model:$$\begin{aligned} x &= x - R\sin(\theta) + R\sin(\theta + \beta) \\y &= y + R\cos(\theta) - R\cos(\theta + \beta) \\\theta &= \theta + \beta\end{aligned}$$where $\theta$ is the robot's heading.You do not need to understand t... | import sympy
from sympy.abc import alpha, x, y, v, w, R, theta
from sympy import symbols, Matrix
sympy.init_printing(use_latex="mathjax", fontsize='16pt')
time = symbols('t')
d = v*time
beta = (d/w)*sympy.tan(alpha)
r = w/sympy.tan(alpha)
fxu = Matrix([[x-r*sympy.sin(theta) + r*sympy.sin(theta+beta)],
[y... | _____no_output_____ | CC-BY-4.0 | 11-Extended-Kalman-Filters.ipynb | galuardi/Kalman-and-Bayesian-Filters-in-Python |
That looks a bit complicated. We can use SymPy to substitute terms: | # reduce common expressions
B, R = symbols('beta, R')
J = J.subs((d/w)*sympy.tan(alpha), B)
J.subs(w/sympy.tan(alpha), R) | _____no_output_____ | CC-BY-4.0 | 11-Extended-Kalman-Filters.ipynb | galuardi/Kalman-and-Bayesian-Filters-in-Python |
In that form we can see that our computation of the Jacobian is correct.Now we can turn our attention to the noise. Here, the noise is in our control input, so it is in *control space*. In other words, we command a specific velocity and steering angle, but we need to convert that into errors in $x, y, \theta$. In a rea... | V = fxu.jacobian(Matrix([v, alpha]))
V = V.subs(sympy.tan(alpha)/w, 1/R)
V = V.subs(time*v/R, B)
V = V.subs(time*v, 'd')
V | _____no_output_____ | CC-BY-4.0 | 11-Extended-Kalman-Filters.ipynb | galuardi/Kalman-and-Bayesian-Filters-in-Python |
This should give you an appreciation of how quickly the EKF become mathematically intractable. This gives us the final form of our prediction equations:$$\begin{aligned}\mathbf{\overline x} &= \mathbf x + \begin{bmatrix}- R\sin(\theta) + R\sin(\theta + \beta) \\R\cos(\theta) - R\cos(\theta + \beta) \\\beta\end{bmatrix}... | px, py = symbols('p_x, p_y')
z = Matrix([[sympy.sqrt((px-x)**2 + (py-y)**2)],
[sympy.atan2(py-y, px-x) - theta]])
z.jacobian(Matrix([x, y, theta])) | _____no_output_____ | CC-BY-4.0 | 11-Extended-Kalman-Filters.ipynb | galuardi/Kalman-and-Bayesian-Filters-in-Python |
Now we need to write that as a Python function. For example we might write: | from math import sqrt
def H_of(x, landmark_pos):
""" compute Jacobian of H matrix where h(x) computes
the range and bearing to a landmark for state x """
px = landmark_pos[0]
py = landmark_pos[1]
hyp = (px - x[0, 0])**2 + (py - x[1, 0])**2
dist = sqrt(hyp)
H = array(
[[-(px - x[0... | _____no_output_____ | CC-BY-4.0 | 11-Extended-Kalman-Filters.ipynb | galuardi/Kalman-and-Bayesian-Filters-in-Python |
We also need to define a function that converts the system state into a measurement. | from math import atan2
def Hx(x, landmark_pos):
""" takes a state variable and returns the measurement
that would correspond to that state.
"""
px = landmark_pos[0]
py = landmark_pos[1]
dist = sqrt((px - x[0, 0])**2 + (py - x[1, 0])**2)
Hx = array([[dist],
[atan2(py - x[1, 0... | _____no_output_____ | CC-BY-4.0 | 11-Extended-Kalman-Filters.ipynb | galuardi/Kalman-and-Bayesian-Filters-in-Python |
Design Measurement NoiseThis is quite straightforward as we need to specify measurement noise in measurement space, hence it is linear. It is reasonable to assume that the range and bearing measurement noise is independent, hence$$R=\begin{bmatrix}\sigma_{range}^2 & 0 \\ 0 & \sigma_{bearing}^2\end{bmatrix}$$ Implement... | from filterpy.kalman import ExtendedKalmanFilter as EKF
from numpy import dot, array, sqrt
class RobotEKF(EKF):
def __init__(self, dt, wheelbase, std_vel, std_steer):
EKF.__init__(self, 3, 2, 2)
self.dt = dt
self.wheelbase = wheelbase
self.std_vel = std_vel
self.std_steer = s... | _____no_output_____ | CC-BY-4.0 | 11-Extended-Kalman-Filters.ipynb | galuardi/Kalman-and-Bayesian-Filters-in-Python |
Now we have another issue to handle. The residual is notionally computed as $y = z - h(x)$ but this will not work because our measurement contains an angle in it. Suppose z has a bearing of $1^\circ$ and $h(x)$ has a bearing of $359^\circ$. Naively subtracting them would yield a bearing difference of $-358^\circ$, whic... | def residual(a, b):
""" compute residual (a-b) between measurements containing
[range, bearing]. Bearing is normalized to [-pi, pi)"""
y = a - b
y[1] = y[1] % (2 * np.pi) # force in range [0, 2 pi)
if y[1] > np.pi: # move to [-pi, pi)
y[1] -= 2 * np.pi
return y | _____no_output_____ | CC-BY-4.0 | 11-Extended-Kalman-Filters.ipynb | galuardi/Kalman-and-Bayesian-Filters-in-Python |
The rest of the code runs the simulation and plots the results, and shouldn't need too much comment by now. I create a variable `landmarks` that contains the coordinates of the landmarks. I update the simulated robot position 10 times a second, but run the EKF only once. This is for two reasons. First, we are not using... | from filterpy.stats import plot_covariance_ellipse
from math import sqrt, tan, cos, sin, atan2
import matplotlib.pyplot as plt
dt = 1.0
def z_landmark(lmark, sim_pos, std_rng, std_brg):
x, y = sim_pos[0, 0], sim_pos[1, 0]
d = np.sqrt((lmark[0] - x)**2 + (lmark[1] - y)**2)
a = atan2(lmark[1] - y, lmark[0... | _____no_output_____ | CC-BY-4.0 | 11-Extended-Kalman-Filters.ipynb | galuardi/Kalman-and-Bayesian-Filters-in-Python |
I have plotted the landmarks as solid squares. The path of the robot is drawn with black line. The covariance ellipses for the predict step is light gray, and the covariances of the update are shown in green. To make them visible at this scale I have set the ellipse boundary at 6$\sigma$.From this we can see that there... | landmarks = array([[5, 10], [10, 5], [15, 15], [20, 5]])
ekf = run_localization(
landmarks, std_vel=0.1, std_steer=np.radians(1),
std_range=0.3, std_bearing=0.1)
plt.show()
print('Final P:', ekf.P.diagonal()) | _____no_output_____ | CC-BY-4.0 | 11-Extended-Kalman-Filters.ipynb | galuardi/Kalman-and-Bayesian-Filters-in-Python |
The uncertainly in the estimates near the end of the track are smaller with the additional landmark. We can see the fantastic effect that multiple landmarks has on our uncertainty by only using the first two landmarks. | ekf = run_localization(
landmarks[0:2], std_vel=1.e-10, std_steer=1.e-10,
std_range=1.4, std_bearing=.05)
print('Final P:', ekf.P.diagonal()) | _____no_output_____ | CC-BY-4.0 | 11-Extended-Kalman-Filters.ipynb | galuardi/Kalman-and-Bayesian-Filters-in-Python |
The estimate quickly diverges from the robot's path after passing the landmarks. The covariance also grows quickly. Let's see what happens with only one landmark: | ekf = run_localization(
landmarks[0:1], std_vel=1.e-10, std_steer=1.e-10,
std_range=1.4, std_bearing=.05)
print('Final P:', ekf.P.diagonal()) | _____no_output_____ | CC-BY-4.0 | 11-Extended-Kalman-Filters.ipynb | galuardi/Kalman-and-Bayesian-Filters-in-Python |
As you probably suspected, only one landmark produces a very bad result. Conversely, a large number of landmarks allows us to make very accurate estimates. | landmarks = array([[5, 10], [10, 5], [15, 15], [20, 5], [15, 10],
[10,14], [23, 14], [25, 20], [10, 20]])
ekf = run_localization(
landmarks, std_vel=0.1, std_steer=np.radians(1),
std_range=0.3, std_bearing=0.1, ylim=(0, 21))
print('Final P:', ekf.P.diagonal()) | _____no_output_____ | CC-BY-4.0 | 11-Extended-Kalman-Filters.ipynb | galuardi/Kalman-and-Bayesian-Filters-in-Python |
DiscussionI said that this was a 'real' problem, and in some ways it is. I've seen alternative presentations that used robot motion models that led to much easier Jacobians. On the other hand, my model of a automobile's movement is itself simplistic in several ways. First, it uses a bicycle model. A real car has two s... | import nonlinear_plots
nonlinear_plots.plot_ekf_vs_mc() | _____no_output_____ | CC-BY-4.0 | 11-Extended-Kalman-Filters.ipynb | galuardi/Kalman-and-Bayesian-Filters-in-Python |
We can see from both the graph and the print out at the bottom that the EKF has introduced quite a bit of error.In contrast, here is the performance of the UKF: | nonlinear_plots.plot_ukf_vs_mc(alpha=0.001, beta=3., kappa=1.) | _____no_output_____ | CC-BY-4.0 | 11-Extended-Kalman-Filters.ipynb | galuardi/Kalman-and-Bayesian-Filters-in-Python |
!nvidia-smi
!git clone https://github.com/venkat2319/MIRnet
%cd MIRNet
!pip install -qq wandb
from glob import glob
import tensorflow as tf
from mirnet.train import LowLightTrainer
from mirnet.utils import init_wandb, download_dataset
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
download_dataset('LO... | _____no_output_____ | Apache-2.0 | notebook/MIRNet_Low_Light_Train.ipynb | venkat2319/MIRnet | |
Using ObjectScript in a notebookThis notebook uses a kernel written in Python, which plugs into Jupyter to enable execution of ObjectScript inside IRIS. See `misc/kernels/objectscript/*` and `src/ObjectScript/Kernel/CodeExecutor.cls` for how this is done.Indenting each line with at least one space allows InterSystems ... | Set hello = "helloworld2"
zw hello | hello="helloworld2"
| MIT | src/Notebooks/ObjectScript.ipynb | gjsjohnmurray/iris-python-template |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.