markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
$$
s_{new} = \begin{cases} (t+1,h-1,i) & \text{if } x = 0 \ (t+1,h+1,i) & \text{if } x = 1 \ (t+1,h+1.5,i) & \text{if } x = 2\end{cases}
$$ | assert(hjb((settings['T'],settings['H_init']-1)) == 10000)
assert(hjb((settings['T'],settings['H_init'])) == 0)
assert(hjb((settings['T']-1,settings['H_min']-1)) == 10000)
assert(hjb((settings['T']-1,settings['H_max']+1)) == 10000) | Dynamic programming class.ipynb | icfly2/hjb_solvers | gpl-3.0 |
state is given by $s = (t,h,i)$
$$
v(s) = \min_x(cost(x,s) + \sum_j p_{ij} v(new state(x,s)))
$$ | def make_schedule(settings):
sched = np.ones(settings['T'])*np.nan
cost_calc= 0
elev = np.ones(settings['T']+1)*np.nan
s = settings['Initial state']
t = 0
while t < settings['T']:
sched[t] = settings['cache'][s][1]
print sched[t]
cost_calc += settings['Cost eq.'](s... | Dynamic programming class.ipynb | icfly2/hjb_solvers | gpl-3.0 |
Let Jupyter know that you're gonna be charting inline
(Don't worry if you get a warning about building a font library.) | %matplotlib inline | completed/07. pandas? pandas! (Part 3).ipynb | ireapps/cfj-2017 | mit |
Read in MLB data | # create a data frame
df = pd.read_csv('data/mlb.csv')
# use head to check it out
df.head() | completed/07. pandas? pandas! (Part 3).ipynb | ireapps/cfj-2017 | mit |
Prep data for charting
Let's chart total team payroll, most to least. Let's repeat the grouping we did before. | # group by team, aggregate on sum
grouped_by_team = df[['TEAM', 'SALARY']].groupby('TEAM') \
.sum() \
.reset_index() \
.set_index('TEAM') \
.sort_values('SALARY... | completed/07. pandas? pandas! (Part 3).ipynb | ireapps/cfj-2017 | mit |
Make a horizonal bar chart | # make a horizontal bar chart
# set the figure size
bar_chart = top_10.plot.barh(figsize=(14, 6))
# sort the bars top to bottom
bar_chart.invert_yaxis()
# set the title
bar_chart.set_title('Top 10 opening day MLB payrolls, 2017')
# kill the legend
bar_chart.legend_.remove()
# kill y axis label
bar_chart.set_ylabel(... | completed/07. pandas? pandas! (Part 3).ipynb | ireapps/cfj-2017 | mit |
Calculating scale heights for temperature and air density
Here is equation 1 of the hydrostatic balance notes
$$\frac{ 1}{\overline{H_p}} = \overline{ \left ( \frac{1 }{H} \right )} = \frac{\int_{0 }^{z}!\frac{1}{H} dz^\prime }{z-0} $$
where
$$H=R_d T/g$$
and here is the Python code to do that integral: | g=9.8 #don't worry about g(z) for this exercise
Rd=287. #kg/m^3
def calcScaleHeight(T,p,z):
"""
Calculate the pressure scale height H_p
Parameters
----------
T: vector (float)
temperature (K)
p: vector (float) of len(T)
pressure (pa)
z: vector (float) of... | notebooks/hydrostatic.ipynb | a301-teaching/a301_code | mit |
Similarly, equation (5) of the hydrostatic balance notes
is:
$$\frac{d\rho }{\rho} = - \left ( \frac{1 }{H} +
\frac{1 }{T} \frac{dT }{dz} \right ) dz \equiv - \frac{dz }{H_\rho} $$
Which leads to
$$\frac{ 1}{\overline{H_\rho}} = \frac{\int_{0 }^{z}!\left [ \frac{1}{H} + \frac{1 }{T} \frac{dT }{dz}... | def calcDensHeight(T,p,z):
"""
Calculate the density scale height H_rho
Parameters
----------
T: vector (float)
temperature (K)
p: vector (float) of len(T)
pressure (pa)
z: vector (float) of len(T
height (m)
Returns
-------
Hb... | notebooks/hydrostatic.ipynb | a301-teaching/a301_code | mit |
How do $\overline{H_p}$ and $\overline{H_\rho}$ compare for the tropical sounding? | sounding='tropics'
#
# grab the dataframe and get the sounding columns
#
df=sound_dict[sounding]
z=df['z'].values
Temp=df['temp'].values
press=df['press'].values
#
# limit calculation to bottom 10 km
#
hit=z<10000.
zL,pressL,TempL=(z[hit],press[hit],Temp[hit])
rhoL=pressL/(Rd*TempL)
Hbar= calcScaleHeight(TempL,pressL,... | notebooks/hydrostatic.ipynb | a301-teaching/a301_code | mit |
How well do these average values represent the pressure and density profiles? | theFig,theAx=plt.subplots(1,1)
theAx.semilogy(Temp,press/100.)
#
# need to flip the y axis since pressure decreases with height
#
theAx.invert_yaxis()
tickvals=[1000,800, 600, 400, 200, 100, 50,1]
theAx.set_yticks(tickvals)
majorFormatter = ticks.FormatStrFormatter('%d')
theAx.yaxis.set_major_formatter(majorFormatter)
... | notebooks/hydrostatic.ipynb | a301-teaching/a301_code | mit |
Now check the hydrostatic approximation by plotting the pressure column against
$$p(z) = p_0 \exp \left (-z/\overline{H_p} \right )$$
vs. the actual sounding p(T): | fig,theAx=plt.subplots(1,1)
hydroPress=pressL[0]*np.exp(-zL/Hbar)
theAx.plot(pressL/100.,zL/1000.,label='sounding')
theAx.plot(hydroPress/100.,zL/1000.,label='hydrostat approx')
theAx.set_title('height vs. pressure for tropics')
theAx.set_xlabel('pressure (hPa)')
theAx.set_ylabel('height (km)')
theAx.set_xlim([500,1000... | notebooks/hydrostatic.ipynb | a301-teaching/a301_code | mit |
Again plot the hydrostatic approximation
$$\rho(z) = \rho_0 \exp \left (-z/\overline{H_\rho} \right )$$
vs. the actual sounding $\rho(z)$: | fig,theAx=plt.subplots(1,1)
hydroDens=rhoL[0]*np.exp(-zL/Hrho)
theAx.plot(rhoL,zL/1000.,label='sounding')
theAx.plot(hydroDens,zL/1000.,label='hydrostat approx')
theAx.set_title('height vs. density for the tropics')
theAx.set_xlabel('density ($kg\,m^{-3}$)')
theAx.set_ylabel('height (km)')
theAx.set_ylim([0,5])
_=theAx... | notebooks/hydrostatic.ipynb | a301-teaching/a301_code | mit |
Q: What is the variance of $\mathscr{P}_{HV}$? | psi.dag()*Phv*Phv*psi
1- (-0.6)**2 | Lab 4 - Measurements.ipynb | amcdawes/QMlabs | mit |
Example: Use the random function to generate a mock data set for the state $|\psi\rangle$.
random.choice([1,-1],size=10,p=[0.2,0.8])
gives a list of 10 numbers, either 1 or -1 with the associated probability p: | data = random.choice([1, -1],size=1000000,p=[0.2,0.8]) | Lab 4 - Measurements.ipynb | amcdawes/QMlabs | mit |
Q: Verify the mean and variance of the mock data set match your QM predictions. How big does the set need to be for you to get ±5% agreement? | data.mean()
data.var() | Lab 4 - Measurements.ipynb | amcdawes/QMlabs | mit |
These are what we want from the new pipeline.
Extracting spectra from the mzml, mzxml files
Grouping features and exporting in a format that MS2LDA can deal with
Running MS2LDA
Visualising
with possible variations on step (1), (2) and maybe even (3) too.
Example Step 1
Below we define an example class to load existin... | class ExtractSpectra(lg.Task):
datadir = lg.Parameter()
prefix = lg.Parameter()
def run(self):
# we could actually extract the spectra from mzxml, mzml files here
print 'Processing %s and %s' % (datadir, prefix)
def output(self):
out_dict = {
'ms1': lg.... | notebooks/experimental_pipeline.ipynb | sdrogers/lda | gpl-3.0 |
Example Step 2
Similarly here we define a class to take the output of the ExtractSpectra class above (the dependency is defined in the requires method below), performs the grouping by detecting gaps along the groups (defined in the run method) and produces the output to a pickled file (defined in the output method).
It... | class GroupFeatures(lg.Task):
scaling_factor = lg.IntParameter(default=1000)
fragment_grouping_tol = lg.IntParameter(default=7)
loss_grouping_tol = lg.IntParameter(default=7)
loss_threshold_min_count = lg.IntParameter(default=5)
loss_threshold_max_val = lg.IntParameter(default=200)
loss_thr... | notebooks/experimental_pipeline.ipynb | sdrogers/lda | gpl-3.0 |
Example Step 3
Finally here we define a RunLDA task that depends on the output of the grouping class above. | class RunLDA(lg.Task):
n_its = lg.IntParameter(default=10)
K = lg.IntParameter(default=300)
alpha = lg.FloatParameter(default=1)
eta = lg.FloatParameter(default=0.1)
update_alpha = lg.BoolParameter(default=True)
datadir = lg.Parameter()
prefixes = lg.ListParameter()
def requir... | notebooks/experimental_pipeline.ipynb | sdrogers/lda | gpl-3.0 |
Run the pipeline
Set up the initial parameters | datadir = '/Users/joewandy/Dropbox/Meta_clustering/MS2LDA/large_study/Urine_mzXML_large_study/method_1/POS/'
prefixes = [
'Urine_StrokeDrugs_02_T10_POS',
'Urine_StrokeDrugs_03_T10_POS',
'Urine_StrokeDrugs_08_T10_POS',
'Urine_StrokeDrugs_09_T10_POS',
]
prefixes_json = json.dumps(prefixes) | notebooks/experimental_pipeline.ipynb | sdrogers/lda | gpl-3.0 |
And run the pipeline | lg.run(['RunLDA', '--workers', '1', '--local-scheduler', '--datadir', datadir, '--prefixes', prefixes_json]) | notebooks/experimental_pipeline.ipynb | sdrogers/lda | gpl-3.0 |
We create 'bins' for the columns Age and Fare to help with later plots. | df['Ages'] = df['Age'].map(lambda x: int(x/10)*10)
df['Fares'] = df['Fare'].map(lambda x: int(x/10)*10)
%reload_ext rpy2.ipython
%Rpush df
%%R
library(ggplot2) | scikit/titanic/notebooks/Appendix B - Visualisation.ipynb | obulpathi/datascience | apache-2.0 |
First, we review the number of passengers by the column Survived, which indicates whether or not they survived. | %%R -w 400
qplot(factor(Survived), data=df, geom="bar") | scikit/titanic/notebooks/Appendix B - Visualisation.ipynb | obulpathi/datascience | apache-2.0 |
We now view a breakdown of the data by the column Sex, and rescale so that the breakdown appears as a percentage. | %%R -w 400
qplot(factor(Survived), data=df, fill=factor(Sex), geom="bar", position="fill")
#qplot(factor(Survived), data=df, fill=factor(Pclass), geom="bar", position="fill")
#qplot(factor(Survived), data=df, fill=factor(Ages), geom="bar", position="fill") | scikit/titanic/notebooks/Appendix B - Visualisation.ipynb | obulpathi/datascience | apache-2.0 |
Next, we make a scatter plot between the columns Age and Survived. Note that the column Survived has categorical values, and is represented as factor(Survived). | %%R -w 800
qplot(Age, factor(Survived), data=df) | scikit/titanic/notebooks/Appendix B - Visualisation.ipynb | obulpathi/datascience | apache-2.0 |
We improve our plot by adjusting the shade of each point, such that the point is lighter if the passenger is older. | %%R -w 800
qplot(Age, factor(Survived), data=df, color=Age, size=10, alpha=0.5)
#qplot(Age, factor(Survived), data=df, color=Age, size=Age, alpha=0.5) | scikit/titanic/notebooks/Appendix B - Visualisation.ipynb | obulpathi/datascience | apache-2.0 |
We plot the passengers by their passenger class. | %%R -w 600
qplot(factor(Pclass), data=df, fill=factor(Pclass), geom="bar") + coord_flip() | scikit/titanic/notebooks/Appendix B - Visualisation.ipynb | obulpathi/datascience | apache-2.0 |
We improve this plot by breaking down each bar by their departure point. | %%R -w 600
qplot(factor(Pclass), data=df, fill=Embarked, geom="bar") + coord_flip() | scikit/titanic/notebooks/Appendix B - Visualisation.ipynb | obulpathi/datascience | apache-2.0 |
Finally, we review the column Age in a histogram. | %%R -w 800
qplot(Age, data=df, geom="histogram") | scikit/titanic/notebooks/Appendix B - Visualisation.ipynb | obulpathi/datascience | apache-2.0 |
We then review the fare distribution by each age range. | %%R -w 800
qplot(Age, data=df, fill=factor(Fares), geom="histogram", binwidth=5) | scikit/titanic/notebooks/Appendix B - Visualisation.ipynb | obulpathi/datascience | apache-2.0 |
Funkci plot můžeme předat další parametr, který určuje:
styl čáry: - -- -. :
barvu: b g r c m y k w
styl vykreslení bodu: . , o v ^ < > s p h H * d D _ | + x
chci vědět víc | plot(x,y,'g<')
plot(x,y,'b+:')
plot(x,y,'r*', markersize=15)
plot(x,y,'y--') | Matplotlib--zaklady_pro_tvorbu_grafu.ipynb | tlapicka/IPythonNotebooks | gpl-2.0 |
Příklad s exponenciální funkcí
Nejprve vytvoříme hodnoty na hodnoty pro osu x:... | x=linspace(-10,2,200) | Matplotlib--zaklady_pro_tvorbu_grafu.ipynb | tlapicka/IPythonNotebooks | gpl-2.0 |
... a poté pro osu y:... | y=exp(x) | Matplotlib--zaklady_pro_tvorbu_grafu.ipynb | tlapicka/IPythonNotebooks | gpl-2.0 |
...závyslot si můžeme vykreslit:... | plot(x,y) | Matplotlib--zaklady_pro_tvorbu_grafu.ipynb | tlapicka/IPythonNotebooks | gpl-2.0 |
Můžeme si zobrazit mřížku, popsat osy a upravit rozsah os:... | plot(x,y)
grid(True)
xlabel('x')
ylabel('y')
xlim( [-11,3] )
ylim( [-1,10] ) | Matplotlib--zaklady_pro_tvorbu_grafu.ipynb | tlapicka/IPythonNotebooks | gpl-2.0 |
Příklad s funkcí sinus, f=50 Hz
Nejpve si vytvoříme časovou osu:.. | f=50
t=linspace(0,0.08,200) | Matplotlib--zaklady_pro_tvorbu_grafu.ipynb | tlapicka/IPythonNotebooks | gpl-2.0 |
... vypočítáme hodnoty napětí:.. | u=1.2*cos(2*pi*f*t) | Matplotlib--zaklady_pro_tvorbu_grafu.ipynb | tlapicka/IPythonNotebooks | gpl-2.0 |
... a proudu: | i=0.7*sin(2*pi*f*t-pi/4) | Matplotlib--zaklady_pro_tvorbu_grafu.ipynb | tlapicka/IPythonNotebooks | gpl-2.0 |
... a vyneseme do grafu: | plot(t,u,t,i)
grid(True) | Matplotlib--zaklady_pro_tvorbu_grafu.ipynb | tlapicka/IPythonNotebooks | gpl-2.0 |
Vypočítáme výkon:.. | p=u*i | Matplotlib--zaklady_pro_tvorbu_grafu.ipynb | tlapicka/IPythonNotebooks | gpl-2.0 |
Vyneseme vše do grafu, popíšeme osy, uděláme nadpis a legendu: | figure(figsize=(10,7))
plot(t,u,':',label=u'elektrické napětí')
plot(t,i,'--',label=u'elektrický proud')
plot(t,p,label=u'elektrický výkon')
xlim([0,0.08])
ylim([-1.3,1.8])
title(u'Časový průběh napětí proudu a výkonu')
minorticks_on()
grid(True)
xlabel('t [s]')
ylabel('u [V], i [A], p [W]')
legend(loc='upper right')... | Matplotlib--zaklady_pro_tvorbu_grafu.ipynb | tlapicka/IPythonNotebooks | gpl-2.0 |
Data
We are going to use the Pascal dataset for object detection. There is a version from 2007 and a bigger version from 2012. We'll use the 2007 version here. | path = untar_data(URLs.PASCAL_2007) | nbs/dl2/pascal.ipynb | fastai/course-v3 | apache-2.0 |
The annotations for the images are stored in json files that give the bounding boxes for each class. | import json
annots = json.load(open(path/'train.json'))
annots.keys()
annots['annotations'][0] | nbs/dl2/pascal.ipynb | fastai/course-v3 | apache-2.0 |
This first annotation is a bounding box on the image with id 12, and the corresponding object is the category with id 7. We can read the correspondance in the 'images' and the 'categories' keys. | annots['categories'] | nbs/dl2/pascal.ipynb | fastai/course-v3 | apache-2.0 |
There is a convenience method in fastai to extract all the annotations and map them with the right images/categories directly, as long as they are in the format we just saw (called the COCO format). | train_images, train_lbl_bbox = get_annotations(path/'train.json')
val_images, val_lbl_bbox = get_annotations(path/'valid.json')
#tst_images, tst_lbl_bbox = get_annotations(path/'test.json') | nbs/dl2/pascal.ipynb | fastai/course-v3 | apache-2.0 |
Here we will directly find the same image as before at the beginning of the training set, with the corresponding bounding box and category. | train_images[0], train_lbl_bbox[0] | nbs/dl2/pascal.ipynb | fastai/course-v3 | apache-2.0 |
To see it, we open the image properly and we create an ImageBBox object from the list of bounding boxes. This will allow us to apply data augmentation to our bounding box. To create an ImageBBox, we need to give it the height and the width of the original picture, the list of bounding boxes, the list of category ids an... | img = open_image(path/'train'/train_images[0])
bbox = ImageBBox.create(*img.size, train_lbl_bbox[0][0], [0], classes=['car'])
img.show(figsize=(6,4), y=bbox) | nbs/dl2/pascal.ipynb | fastai/course-v3 | apache-2.0 |
This works with one or several bounding boxes: | train_images[1], train_lbl_bbox[1]
img = open_image(path/'train'/train_images[1])
bbox = ImageBBox.create(*img.size, train_lbl_bbox[1][0], [0, 1], classes=['person', 'horse'])
img.show(figsize=(6,4), y=bbox) | nbs/dl2/pascal.ipynb | fastai/course-v3 | apache-2.0 |
And if we apply a transform to our image and the ImageBBox object, they stay aligned: | img = img.rotate(-10)
bbox = bbox.rotate(-10)
img.show(figsize=(6,4), y=bbox) | nbs/dl2/pascal.ipynb | fastai/course-v3 | apache-2.0 |
We group all the image filenames and annotations together, to use the data block API to load the dataset in a DataBunch. | images, lbl_bbox = train_images+val_images,train_lbl_bbox+val_lbl_bbox
img2bbox = dict(zip(images, lbl_bbox))
get_y_func = lambda o:img2bbox[o.name]
def get_data(bs, size):
src = ObjectItemList.from_folder(path/'train')
src = src.split_by_files(val_images)
src = src.label_from_func(get_y_func)
src = sr... | nbs/dl2/pascal.ipynb | fastai/course-v3 | apache-2.0 |
Model
The architecture we will use is a RetinaNet, which is based on a Feature Pyramid Network.
This is a bit like a Unet in the sense we have a branch where the image is progressively reduced then another one where we upsample it again, and there are lateral connections, but we will use the feature maps produced at ... | #Grab the convenience functions that helps us buil the Unet
from fastai.vision.models.unet import _get_sfs_idxs, model_sizes, hook_outputs
class LateralUpsampleMerge(nn.Module):
"Merge the features coming from the downsample path (in `hook`) with the upsample path."
def __init__(self, ch, ch_lat, hook):
... | nbs/dl2/pascal.ipynb | fastai/course-v3 | apache-2.0 |
The model is a bit complex, but that's not the hardest part. It will spit out an absurdly high number of predictions: for the features P3 to P7 with an image size of 256, we have 32*32 + 16*16 + 8*8 + 4*4 +2*2 locations possible in one of the five feature maps, which gives 1,364 possible detections, multiplied by the n... | torch.arange(0,16).long().view(4,4) | nbs/dl2/pascal.ipynb | fastai/course-v3 | apache-2.0 |
The most basic way to map one of these features with an actual area inside the image is to create the regular 4 by 4 grid. Our convention is that y is first (like in numpy or PyTorch), and that all coordinates are scaled from -1 to 1 (-1 being top/right, 1 being bottom/left). | def create_grid(size):
"Create a grid of a given `size`."
H, W = size if is_tuple(size) else (size,size)
grid = FloatTensor(H, W, 2)
linear_points = torch.linspace(-1+1/W, 1-1/W, W) if W > 1 else tensor([0.])
grid[:, :, 1] = torch.ger(torch.ones(H), linear_points).expand_as(grid[:, :, 0])
linear... | nbs/dl2/pascal.ipynb | fastai/course-v3 | apache-2.0 |
Let's use a helper function to draw those anchors: | def show_anchors(ancs, size):
_,ax = plt.subplots(1,1, figsize=(5,5))
ax.set_xticks(np.linspace(-1,1, size[1]+1))
ax.set_yticks(np.linspace(-1,1, size[0]+1))
ax.grid()
ax.scatter(ancs[:,1], ancs[:,0]) #y is first
ax.set_yticklabels([])
ax.set_xticklabels([])
ax.set_xlim(-1,1)
ax.set_... | nbs/dl2/pascal.ipynb | fastai/course-v3 | apache-2.0 |
In practice, we use different ratios and scales of that basic grid to build our anchors, because bounding boxes aren't always a perfect square inside a grid. | def create_anchors(sizes, ratios, scales, flatten=True):
"Create anchor of `sizes`, `ratios` and `scales`."
aspects = [[[s*math.sqrt(r), s*math.sqrt(1/r)] for s in scales] for r in ratios]
aspects = torch.tensor(aspects).view(-1,2)
anchors = []
for h,w in sizes:
#4 here to have the anchors o... | nbs/dl2/pascal.ipynb | fastai/course-v3 | apache-2.0 |
That's a bit less than in our computation earlier, but this is because it's for the case of (128,128) images (sizes go from (1,1) to (32,32) instead of (2,2) to (64,64)). | import matplotlib.cm as cmx
import matplotlib.colors as mcolors
from cycler import cycler
def get_cmap(N):
color_norm = mcolors.Normalize(vmin=0, vmax=N-1)
return cmx.ScalarMappable(norm=color_norm, cmap='Set3').to_rgba
num_color = 12
cmap = get_cmap(num_color)
color_list = [cmap(float(x)) for x in range(num... | nbs/dl2/pascal.ipynb | fastai/course-v3 | apache-2.0 |
Here is an example of the 9 anchor boxes with different scales/ratios on one region of the image. Now imagine we have this at every location of each of the feature maps. | show_boxes(anchors[900:909]) | nbs/dl2/pascal.ipynb | fastai/course-v3 | apache-2.0 |
For each anchor, we have one class predicted by the classifier and 4 floats p_y,p_x,p_h,p_w predicted by the regressor. If the corresponding anchor as a center in anc_y, anc_x with dimensions anc_h, anc_w, the predicted bounding box has those characteristics:
center = [p_y * anc_h + anc_y, p_x * anc_w + anc_x]
height =... | def activ_to_bbox(acts, anchors, flatten=True):
"Extrapolate bounding boxes on anchors from the model activations."
if flatten:
acts.mul_(acts.new_tensor([[0.1, 0.1, 0.2, 0.2]])) #Can't remember where those scales come from, but they help regularize
centers = anchors[...,2:] * acts[...,:2] + anc... | nbs/dl2/pascal.ipynb | fastai/course-v3 | apache-2.0 |
Here is an example with the 3 by 4 regular grid and random predictions. | size=(3,4)
anchors = create_grid(size)
anchors = torch.cat([anchors, torch.tensor([2/size[0],2/size[1]]).expand_as(anchors)], 1)
activations = torch.randn(size[0]*size[1], 4) * 0.1
bboxes = activ_to_bbox(activations, anchors)
show_boxes(bboxes) | nbs/dl2/pascal.ipynb | fastai/course-v3 | apache-2.0 |
This helper function changes boxes in the format center/height/width to top/left/bottom/right. | def cthw2tlbr(boxes):
"Convert center/size format `boxes` to top/left bottom/right corners."
top_left = boxes[:,:2] - boxes[:,2:]/2
bot_right = boxes[:,:2] + boxes[:,2:]/2
return torch.cat([top_left, bot_right], 1) | nbs/dl2/pascal.ipynb | fastai/course-v3 | apache-2.0 |
Now to decide which predicted bounding box will match a given ground truth object, we will compute the intersection over unions ratios between all the anchors and all the targets, then we will keep the ones that have an overlap greater than a given threshold (0.5). | def intersection(anchors, targets):
"Compute the sizes of the intersections of `anchors` by `targets`."
ancs, tgts = cthw2tlbr(anchors), cthw2tlbr(targets)
a, t = ancs.size(0), tgts.size(0)
ancs, tgts = ancs.unsqueeze(1).expand(a,t,4), tgts.unsqueeze(0).expand(a,t,4)
top_left_i = torch.max(ancs[...,... | nbs/dl2/pascal.ipynb | fastai/course-v3 | apache-2.0 |
Let's see some results, if we have our 12 anchors from before... | show_boxes(anchors) | nbs/dl2/pascal.ipynb | fastai/course-v3 | apache-2.0 |
... and those targets (0. is the whole image) | targets = torch.tensor([[0.,0.,2.,2.], [-0.5,-0.5,1.,1.], [1/3,0.5,0.5,0.5]])
show_boxes(targets) | nbs/dl2/pascal.ipynb | fastai/course-v3 | apache-2.0 |
Then the intersections of each bboxes by each targets are: | intersection(anchors, targets)
def IoU_values(anchors, targets):
"Compute the IoU values of `anchors` by `targets`."
inter = intersection(anchors, targets)
anc_sz, tgt_sz = anchors[:,2] * anchors[:,3], targets[:,2] * targets[:,3]
union = anc_sz.unsqueeze(1) + tgt_sz.unsqueeze(0) - inter
return inte... | nbs/dl2/pascal.ipynb | fastai/course-v3 | apache-2.0 |
And then the IoU values are. | IoU_values(anchors, targets) | nbs/dl2/pascal.ipynb | fastai/course-v3 | apache-2.0 |
Then we match a anchor to targets with the following rules:
- for each anchor we take the maximum overlap possible with any of the targets.
- if that maximum overlap is less than 0.4, we match the anchor box to background, the classifier's target will be that class
- if the maximum overlap is greater than 0.5, we match... | def match_anchors(anchors, targets, match_thr=0.5, bkg_thr=0.4):
"Match `anchors` to targets. -1 is match to background, -2 is ignore."
matches = anchors.new(anchors.size(0)).zero_().long() - 2
if targets.numel() == 0: return matches
ious = IoU_values(anchors, targets)
vals,idxs = torch.max(ious,1)
... | nbs/dl2/pascal.ipynb | fastai/course-v3 | apache-2.0 |
In our previous example, no one had an overlap > 0.5, so unless we use the special rule commented out, there are no matches. | match_anchors(anchors, targets) | nbs/dl2/pascal.ipynb | fastai/course-v3 | apache-2.0 |
With anchors very close to the targets. | size=(3,4)
anchors = create_grid(size)
anchors = torch.cat([anchors, torch.tensor([2/size[0],2/size[1]]).expand_as(anchors)], 1)
activations = 0.1 * torch.randn(size[0]*size[1], 4)
bboxes = activ_to_bbox(activations, anchors)
match_anchors(anchors,bboxes) | nbs/dl2/pascal.ipynb | fastai/course-v3 | apache-2.0 |
With anchors in the grey area. | anchors = create_grid((2,2))
anchors = torch.cat([anchors, torch.tensor([1.,1.]).expand_as(anchors)], 1)
targets = anchors.clone()
anchors = torch.cat([anchors, torch.tensor([[-0.5,0.,1.,1.8]])], 0)
match_anchors(anchors,targets) | nbs/dl2/pascal.ipynb | fastai/course-v3 | apache-2.0 |
Does the opposite of cthw2tbr. | def tlbr2cthw(boxes):
"Convert top/left bottom/right format `boxes` to center/size corners."
center = (boxes[:,:2] + boxes[:,2:])/2
sizes = boxes[:,2:] - boxes[:,:2]
return torch.cat([center, sizes], 1) | nbs/dl2/pascal.ipynb | fastai/course-v3 | apache-2.0 |
Does the opposite of activ_to_bbox. | def bbox_to_activ(bboxes, anchors, flatten=True):
"Return the target of the model on `anchors` for the `bboxes`."
if flatten:
t_centers = (bboxes[...,:2] - anchors[...,:2]) / anchors[...,2:]
t_sizes = torch.log(bboxes[...,2:] / anchors[...,2:] + 1e-8)
return torch.cat([t_centers, t_siz... | nbs/dl2/pascal.ipynb | fastai/course-v3 | apache-2.0 |
We will one-hot encode our targets with the convention that the class of index 0 is the background, which is the absence of any other classes. That is coded by a row of zeros. | def encode_class(idxs, n_classes):
target = idxs.new_zeros(len(idxs), n_classes).float()
mask = idxs != 0
i1s = LongTensor(list(range(len(idxs))))
target[i1s[mask],idxs[mask]-1] = 1
return target
encode_class(LongTensor([1,2,0,1,3]),3) | nbs/dl2/pascal.ipynb | fastai/course-v3 | apache-2.0 |
And now we are ready to build the loss function. It has two parts, one for the classifier and one for the regressor. For the regression, we will use the L1 (potentially smoothed) loss between the predicted activations for an anchor that matches a given object (we ignore the no match or matches to background) and the co... | class RetinaNetFocalLoss(nn.Module):
def __init__(self, gamma:float=2., alpha:float=0.25, pad_idx:int=0, scales:Collection[float]=None,
ratios:Collection[float]=None, reg_loss:LossFunction=F.smooth_l1_loss):
super().__init__()
self.gamma,self.alpha,self.pad_idx,self.reg_loss ... | nbs/dl2/pascal.ipynb | fastai/course-v3 | apache-2.0 |
This is a variant of the L1 loss used in several implementations: | class SigmaL1SmoothLoss(nn.Module):
def forward(self, output, target):
reg_diff = torch.abs(target - output)
reg_loss = torch.where(torch.le(reg_diff, 1/9), 4.5 * torch.pow(reg_diff, 2), reg_diff - 1/18)
return reg_loss.mean() | nbs/dl2/pascal.ipynb | fastai/course-v3 | apache-2.0 |
Defining the Learner | ratios = [1/2,1,2]
scales = [1,2**(-1/3), 2**(-2/3)]
#scales = [1,2**(1/3), 2**(2/3)] for bigger size
encoder = create_body(models.resnet50, cut=-2)
model = RetinaNet(encoder, data.c, final_bias=-4)
crit = RetinaNetFocalLoss(scales=scales, ratios=ratios)
learn = Learner(data, model, loss_func=crit) | nbs/dl2/pascal.ipynb | fastai/course-v3 | apache-2.0 |
Why final_bias=-4? That's because we want the network to predict background easily at the beginning (since it's the most common class). At first the final convolution of the classifier is initialized with weights=0 and that bias, so it will return -4 for everyone. If go though a sigmoid | torch.sigmoid(tensor([-4.])) | nbs/dl2/pascal.ipynb | fastai/course-v3 | apache-2.0 |
We see it'll give a corresponding probability of 0.02 roughly.
Then, for transfer learning/discriminative LRs, we need to define how to split between body and custom head. | def retina_net_split(model):
groups = [list(model.encoder.children())[:6], list(model.encoder.children())[6:]]
return groups + [list(model.children())[1:]]
learn = learn.split(retina_net_split) | nbs/dl2/pascal.ipynb | fastai/course-v3 | apache-2.0 |
And now we can train as usual! | learn.freeze()
learn.lr_find()
learn.recorder.plot(skip_end=5)
learn.fit_one_cycle(5, 1e-4)
learn.save('stage1-128')
learn.unfreeze()
learn.fit_one_cycle(10, slice(1e-6, 5e-5))
learn.save('stage2-128')
learn.data = get_data(32,192)
learn.freeze()
learn.lr_find()
learn.recorder.plot()
learn.fit_one_cycle(5, 1... | nbs/dl2/pascal.ipynb | fastai/course-v3 | apache-2.0 |
Results | learn = learn.load('stage2-256')
img,target = next(iter(data.valid_dl))
with torch.no_grad():
output = learn.model(img) | nbs/dl2/pascal.ipynb | fastai/course-v3 | apache-2.0 |
First we need to remove the padding that was added to collate our targets together. | def unpad(tgt_bbox, tgt_clas, pad_idx=0):
i = torch.min(torch.nonzero(tgt_clas-pad_idx))
return tlbr2cthw(tgt_bbox[i:]), tgt_clas[i:]-1+pad_idx | nbs/dl2/pascal.ipynb | fastai/course-v3 | apache-2.0 |
Then we process the outputs of the model: we convert the activations of the regressor to bounding boxes and the predictions to probabilities, only keeping those above a given threshold. | def process_output(output, i, detect_thresh=0.25):
"Process `output[i]` and return the predicted bboxes above `detect_thresh`."
clas_pred,bbox_pred,sizes = output[0][i], output[1][i], output[2]
anchors = create_anchors(sizes, ratios, scales).to(clas_pred.device)
bbox_pred = activ_to_bbox(bbox_pred, anch... | nbs/dl2/pascal.ipynb | fastai/course-v3 | apache-2.0 |
Helper functions to plot the results | def _draw_outline(o:Patch, lw:int):
"Outline bounding box onto image `Patch`."
o.set_path_effects([patheffects.Stroke(
linewidth=lw, foreground='black'), patheffects.Normal()])
def draw_rect(ax:plt.Axes, b:Collection[int], color:str='white', text=None, text_size=14):
"Draw bounding box on `ax`."
... | nbs/dl2/pascal.ipynb | fastai/course-v3 | apache-2.0 |
And let's have a look at one picture. | idx = 0
img = data.valid_ds[idx][0]
show_preds(img, output, idx, detect_thresh=0.3, classes=data.classes) | nbs/dl2/pascal.ipynb | fastai/course-v3 | apache-2.0 |
It looks like a lot of our anchors are detecting kind of the same object. We use an algorithm called Non-Maximum Suppression to remove near-duplicates: going from the biggest score predicted to the lowest, we take the corresponding bounding boxes and remove all the bounding boxes down the list that have an IoU > 0.5 wi... | def nms(boxes, scores, thresh=0.3):
idx_sort = scores.argsort(descending=True)
boxes, scores = boxes[idx_sort], scores[idx_sort]
to_keep, indexes = [], torch.LongTensor(range_of(scores))
while len(scores) > 0:
to_keep.append(idx_sort[indexes[0]])
iou_vals = IoU_values(boxes, boxes[:1]).s... | nbs/dl2/pascal.ipynb | fastai/course-v3 | apache-2.0 |
mAP
A metric often used for this kind of task is the mean Average Precision (our mAP). It relies on computing the cumulated precision and recall for each class, then tries to compute the area under the precision/recall curve we can draw. | def get_predictions(output, idx, detect_thresh=0.05):
bbox_pred, scores, preds = process_output(output, idx, detect_thresh)
if len(scores) == 0: return [],[],[]
to_keep = nms(bbox_pred, scores)
return bbox_pred[to_keep], preds[to_keep], scores[to_keep]
def compute_ap(precision, recall):
"Compute th... | nbs/dl2/pascal.ipynb | fastai/course-v3 | apache-2.0 |
Basic Poisson Model
I won't spend too long on this model, as it was the subject of the previous post. Essentially, you treat the number of goals scored by each team as two independent Poisson distributions (henceforth called the Basic Poisson (BP) model). The shape of each distribution is determined by the average numb... | # construct Poisson for each mean goals value
poisson_pred = np.column_stack([[poisson.pmf(i, epl_1718.mean()[j]) for i in range(8)] for j in range(2)])
fig, ax = plt.subplots(figsize=(9,4))
# plot histogram of actual goals
plt.hist(epl_1718[['HomeGoals', 'AwayGoals']].values, range(9),
alpha=0.7, label=[... | Jupyter/2018-09-13-predicting-football-results-with-statistical-modelling-dixon-coles-and-time-weighting.ipynb | dashee87/blogScripts | mit |
We can formulate the model in mathematical terms:
$$
P\left(X_{i,j} = x, Y_{j,i} = y \right) = \frac{e^{-\lambda} \lambda^x }{x!} \frac{e^{-\mu} \mu^y }{y!}
\ \text{where } \quad \lambda = \alpha_i \beta_j \gamma \quad \mu = \alpha_j \beta_i
$$
In this equation, $i$ and $j$ refer to the home and away teams, respectivel... | # importing the tools required for the Poisson regression model
import statsmodels.api as sm
import statsmodels.formula.api as smf
goal_model_data = pd.concat([epl_1718[['HomeTeam','AwayTeam','HomeGoals']].assign(home=1).rename(
columns={'HomeTeam':'team', 'AwayTeam':'opponent','HomeGoals':'goals'}),
... | Jupyter/2018-09-13-predicting-football-results-with-statistical-modelling-dixon-coles-and-time-weighting.ipynb | dashee87/blogScripts | mit |
As an example, Arsenal (playing at home) would be expected to score 2.43 goals against Southampton, while their opponents would get about 0.86 goals on average (I'm using the terms average and expected interchangeably). As each team is treated independently, we can construct a match score probability matrix. | def simulate_match(foot_model, homeTeam, awayTeam, max_goals=10):
home_goals_avg = foot_model.predict(pd.DataFrame(data={'team': homeTeam,
'opponent': awayTeam,'home':1},
index=[1])).values[0]
away... | Jupyter/2018-09-13-predicting-football-results-with-statistical-modelling-dixon-coles-and-time-weighting.ipynb | dashee87/blogScripts | mit |
First published by Maher in 1982, the BP model still serves a good starting point from which you can add features that more closely reflect the reality. That brings us onto the Dixon Coles (DC) model.
Dixon-Coles Model
In their 1997 paper, Mark Dixon and Stuart Coles proposed two specific improvements to the BP model:
... | def poiss_actual_diff(football_url, max_goals):
epl_1718 = pd.read_csv(football_url)
epl_1718 = epl_1718[['HomeTeam','AwayTeam','FTHG','FTAG']]
epl_1718 = epl_1718.rename(columns={'FTHG': 'HomeGoals', 'FTAG': 'AwayGoals'})
team_pred = [[poisson.pmf(i, team_avg) for i in range(0, max_goals)] \
... | Jupyter/2018-09-13-predicting-football-results-with-statistical-modelling-dixon-coles-and-time-weighting.ipynb | dashee87/blogScripts | mit |
There does seem to be an issue around low scoring draws, though it is less apparent with 1-0 and 0-1 results. The Dixon-Coles (DC) model applies a correction to the BP model. It can be written in these mathematical terms:
$$
P\left(X_{i,j} = x, Y_{j,i} = y \right) = \tau_{\lambda, \mu}(x) \frac{e^{-\lambda} \lambda^x }... | def rho_correction(x, y, lambda_x, mu_y, rho):
if x==0 and y==0:
return 1- (lambda_x * mu_y * rho)
elif x==0 and y==1:
return 1 + (lambda_x * rho)
elif x==1 and y==0:
return 1 + (mu_y * rho)
elif x==1 and y==1:
return 1 - rho
else:
return 1.0 | Jupyter/2018-09-13-predicting-football-results-with-statistical-modelling-dixon-coles-and-time-weighting.ipynb | dashee87/blogScripts | mit |
Unfortunately, you can't just update your match score matrix with this function; you need to recalculate the various coefficients that go into the model. And unfortunately again, you can't just implement an off the shelf generalised linear model, as we did before. We have to construct the likelihood function and find t... | def dc_log_like(x, y, alpha_x, beta_x, alpha_y, beta_y, rho, gamma):
lambda_x, mu_y = np.exp(alpha_x + beta_y + gamma), np.exp(alpha_y + beta_x)
return (np.log(rho_correction(x, y, lambda_x, mu_y, rho)) +
np.log(poisson.pmf(x, lambda_x)) + np.log(poisson.pmf(y, mu_y))) | Jupyter/2018-09-13-predicting-football-results-with-statistical-modelling-dixon-coles-and-time-weighting.ipynb | dashee87/blogScripts | mit |
You may have noticed that dc_log_like included a transformation of $\lambda$ and $\mu$, where $\lambda = \exp(\alpha_i + \beta_j + \gamma)$ and $\mu = \exp(\alpha_j + \beta_i)$, so that we're essentially trying to calculate expected log goals. This is equivalent to the log link function in the previous BP glm implemen... | def solve_parameters(dataset, debug = False, init_vals=None, options={'disp': True, 'maxiter':100},
constraints = [{'type':'eq', 'fun': lambda x: sum(x[:20])-20}] , **kwargs):
teams = np.sort(dataset['HomeTeam'].unique())
# check for no weirdness in dataset
away_teams = np.sort(dataset[... | Jupyter/2018-09-13-predicting-football-results-with-statistical-modelling-dixon-coles-and-time-weighting.ipynb | dashee87/blogScripts | mit |
The optimal rho value (-0.1285) returned by the model fits quite nicely with the value (-0.13) given in the equivalent opisthokonta blog post. We can now start making some predictions by constructing match score matrices based on these model parameters. This part is quite similar to BP model, except for the correction ... | def calc_means(param_dict, homeTeam, awayTeam):
return [np.exp(param_dict['attack_'+homeTeam] + param_dict['defence_'+awayTeam] + param_dict['home_adv']),
np.exp(param_dict['defence_'+homeTeam] + param_dict['attack_'+awayTeam])]
def dixon_coles_simulate_match(params_dict, homeTeam, awayTeam, max_goals=... | Jupyter/2018-09-13-predicting-football-results-with-statistical-modelling-dixon-coles-and-time-weighting.ipynb | dashee87/blogScripts | mit |
As you can see, the DC model reports a higher probability of a draw compared to the BP model. In fact, you can plot the difference in the match score probability matrices between the two models. | cmap = sns.diverging_palette(10, 133, as_cmap=True)
fig, ax = plt.subplots(figsize=(5,5))
with sns.axes_style("white"):
ax = sns.heatmap(simulate_match(poisson_model, 'Arsenal', 'Southampton', max_goals=5) - \
dixon_coles_simulate_match(params, 'Arsenal', 'Southampton', max_goals=5),
... | Jupyter/2018-09-13-predicting-football-results-with-statistical-modelling-dixon-coles-and-time-weighting.ipynb | dashee87/blogScripts | mit |
In one way, this is a good plot. The correction was only intended to have an effect on 4 specific match results (0-0, 1-0, 0-1 and 1-1) and that's what has happened. On the other hand, that was alot of hard work to essentially tweak the existing model. And that's without even considering whether it was a beneficial adj... | fig,(ax1,ax2) = plt.subplots(2, 1, figsize=(10,5))
ax1.plot(range(1000), [0 if y >600 else 1 for y in range(1000)], label='Component 1', color='#38003c', marker='')
ax2.plot(range(1000), np.exp([y*-0.005 for y in range(1000)]), label='Component 1', color='#07F2F2', marker='')
ax2.plot(range(1000), np.exp([y*-0.003 for... | Jupyter/2018-09-13-predicting-football-results-with-statistical-modelling-dixon-coles-and-time-weighting.ipynb | dashee87/blogScripts | mit |
The first option forces the model to only consider matches within some predefined period (e.g. since the start of the season), while the negative exponential downweights match results more strongly going further into the past. The refined model can be written in these mathematical terms:
$$
L(\alpha_i, \beta_i, \rho, \... | def dc_log_like_decay(x, y, alpha_x, beta_x, alpha_y, beta_y, rho, gamma, t, xi=0):
lambda_x, mu_y = np.exp(alpha_x + beta_y + gamma), np.exp(alpha_y + beta_x)
return np.exp(-xi*t) * (np.log(rho_correction(x, y, lambda_x, mu_y, rho)) +
np.log(poisson.pmf(x, lambda_x)) + np.log(p... | Jupyter/2018-09-13-predicting-football-results-with-statistical-modelling-dixon-coles-and-time-weighting.ipynb | dashee87/blogScripts | mit |
To determine the optimal value of $\xi$, we'll select the model that makes the best predictions. Repeating the process in the Dixon-Coles paper, rather working on match score predictions, the models will be assessed on match result predictions. Essentially, the model that predicted the actual match results with the hig... | epl_1718 = pd.read_csv("http://www.football-data.co.uk/mmz4281/1718/E0.csv")
epl_1718['Date'] = pd.to_datetime(epl_1718['Date'], format='%d/%m/%y')
epl_1718['time_diff'] = (max(epl_1718['Date']) - epl_1718['Date']).dt.days
epl_1718 = epl_1718[['HomeTeam','AwayTeam','FTHG','FTAG', 'FTR', 'time_diff']]
epl_1718 = epl_17... | Jupyter/2018-09-13-predicting-football-results-with-statistical-modelling-dixon-coles-and-time-weighting.ipynb | dashee87/blogScripts | mit |
With this dataframe, we're now ready to compare different values of $\xi$. To speed up this process even further, I made the code parallelisable and ran it across my computer's multiple (4) cores (see Python file).
Here's an example of how you would build a model for a given value of $\xi$. | def solve_parameters_decay(dataset, xi=0.001, debug = False, init_vals=None, options={'disp': True, 'maxiter':100},
constraints = [{'type':'eq', 'fun': lambda x: sum(x[:20])-20}] , **kwargs):
teams = np.sort(dataset['HomeTeam'].unique())
# check for no weirdness in dataset
away_teams = ... | Jupyter/2018-09-13-predicting-football-results-with-statistical-modelling-dixon-coles-and-time-weighting.ipynb | dashee87/blogScripts | mit |
It seems that $S(\xi)$ is minimised at $\xi$=0 (remember that $\xi \geq 0$), which is simply the standard non-weighted DC model. I suppose this makes sense: If you only have data for the season in question, then you don't have the luxury of down-weighting older results. In the Dixon-Coles paper, they actually compiled ... | epl_1318 = pd.DataFrame()
for year in range(13,18):
epl_1318 = pd.concat((epl_1318, pd.read_csv("http://www.football-data.co.uk/mmz4281/{}{}/E0.csv".format(year, year+1))))
epl_1318['Date'] = pd.to_datetime(epl_1318['Date'], format='%d/%m/%y')
epl_1318['time_diff'] = (max(epl_1318['Date']) - epl_1318['Date']).dt.d... | Jupyter/2018-09-13-predicting-football-results-with-statistical-modelling-dixon-coles-and-time-weighting.ipynb | dashee87/blogScripts | mit |
Same procedure as before, with varying values of $\xi$, we'll quanitfy how well the model predicted the match results of the second half of the 17/18 EPL season. Again, I ran the program across multiple cores (see Python file). | xi_vals = [0.0, 0.0005, 0.001, 0.0015, 0.002, 0.0025, 0.00275, 0.003, 0.00325,
0.0035, 0.00375, 0.004, 0.00425, 0.0045, 0.005, 0.0055, 0.006]
# I pulled the scores from files on my computer that had been generated seperately
#xi_scores = []
#for xi in xi_vals:
# with open ('find_xi_5season_{}.txt'.form... | Jupyter/2018-09-13-predicting-football-results-with-statistical-modelling-dixon-coles-and-time-weighting.ipynb | dashee87/blogScripts | mit |
Open the Dataset | monthly_mean_file = 'RASM_example_data.nc'
ds = xr.open_dataset(monthly_mean_file, decode_coords=False)
print(ds) | notebooks/norman/xarray-ex-3.ipynb | CCI-Tools/sandbox | gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.