markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
The exponentially-weighted moving average gives more weight to more recent points. | def PlotEWMA(daily, name):
"""Plots rolling mean.
daily: DataFrame of daily prices
"""
dates = pd.date_range(daily.index.min(), daily.index.max())
reindexed = daily.reindex(dates)
thinkplot.Scatter(reindexed.ppg, s=15, alpha=0.2, label=name)
roll_mean = reindexed.ppg.ewm(30).mean()
thi... | code/chap12ex.ipynb | AllenDowney/ThinkStats2 | gpl-3.0 |
We can use resampling to generate missing values with the right amount of noise. | def FillMissing(daily, span=30):
"""Fills missing values with an exponentially weighted moving average.
Resulting DataFrame has new columns 'ewma' and 'resid'.
daily: DataFrame of daily prices
span: window size (sort of) passed to ewma
returns: new DataFrame of daily prices
"""
dates = pd... | code/chap12ex.ipynb | AllenDowney/ThinkStats2 | gpl-3.0 |
Here's what the EWMA model looks like with missing values filled. | PlotFilled(daily, name) | code/chap12ex.ipynb | AllenDowney/ThinkStats2 | gpl-3.0 |
Serial correlation
The following function computes serial correlation with the given lag. | def SerialCorr(series, lag=1):
xs = series[lag:]
ys = series.shift(lag)[lag:]
corr = thinkstats2.Corr(xs, ys)
return corr | code/chap12ex.ipynb | AllenDowney/ThinkStats2 | gpl-3.0 |
Before computing correlations, we'll fill missing values. | filled_dailies = {}
for name, daily in dailies.items():
filled_dailies[name] = FillMissing(daily, span=30) | code/chap12ex.ipynb | AllenDowney/ThinkStats2 | gpl-3.0 |
Here are the serial correlations for raw price data. | for name, filled in filled_dailies.items():
corr = thinkstats2.SerialCorr(filled.ppg, lag=1)
print(name, corr) | code/chap12ex.ipynb | AllenDowney/ThinkStats2 | gpl-3.0 |
It's not surprising that there are correlations between consecutive days, because there are obvious trends in the data.
It is more interested to see whether there are still correlations after we subtract away the trends. | for name, filled in filled_dailies.items():
corr = thinkstats2.SerialCorr(filled.resid, lag=1)
print(name, corr) | code/chap12ex.ipynb | AllenDowney/ThinkStats2 | gpl-3.0 |
Even if the correlations between consecutive days are weak, there might be correlations across intervals of one week, one month, or one year. | rows = []
for lag in [1, 7, 30, 365]:
print(lag, end="\t")
for name, filled in filled_dailies.items():
corr = SerialCorr(filled.resid, lag)
print("%.2g" % corr, end="\t")
print() | code/chap12ex.ipynb | AllenDowney/ThinkStats2 | gpl-3.0 |
The strongest correlation is a weekly cycle in the medium quality category.
Autocorrelation
The autocorrelation function is the serial correlation computed for all lags.
We can use it to replicate the results from the previous section. | # NOTE: acf throws a FutureWarning because we need to replace `unbiased` with `adjusted`,
# just as soon as Colab gets updated :)
import warnings
warnings.simplefilter(action="ignore", category=FutureWarning)
import statsmodels.tsa.stattools as smtsa
filled = filled_dailies["high"]
acf = smtsa.acf(filled.resid, nla... | code/chap12ex.ipynb | AllenDowney/ThinkStats2 | gpl-3.0 |
To get a sense of how much autocorrelation we should expect by chance, we can resample the data (which eliminates any actual autocorrelation) and compute the ACF. | def SimulateAutocorrelation(daily, iters=1001, nlags=40):
"""Resample residuals, compute autocorrelation, and plot percentiles.
daily: DataFrame
iters: number of simulations to run
nlags: maximum lags to compute autocorrelation
"""
# run simulations
t = []
for _ in range(iters):
... | code/chap12ex.ipynb | AllenDowney/ThinkStats2 | gpl-3.0 |
The following function plots the actual autocorrelation for lags up to 40 days.
The flag add_weekly indicates whether we should add a simulated weekly cycle. | def PlotAutoCorrelation(dailies, nlags=40, add_weekly=False):
"""Plots autocorrelation functions.
dailies: map from category name to DataFrame of daily prices
nlags: number of lags to compute
add_weekly: boolean, whether to add a simulated weekly pattern
"""
thinkplot.PrePlot(3)
daily = dai... | code/chap12ex.ipynb | AllenDowney/ThinkStats2 | gpl-3.0 |
To show what a strong weekly cycle would look like, we have the option of adding a price increase of 1-2 dollars on Friday and Saturdays. | def AddWeeklySeasonality(daily):
"""Adds a weekly pattern.
daily: DataFrame of daily prices
returns: new DataFrame of daily prices
"""
fri_or_sat = (daily.index.dayofweek == 4) | (daily.index.dayofweek == 5)
fake = daily.ppg.copy()
fake[fri_or_sat] += np.random.uniform(0, 2, fri_or_sat.sum... | code/chap12ex.ipynb | AllenDowney/ThinkStats2 | gpl-3.0 |
Here's what the real ACFs look like. The gray regions indicate the levels we expect by chance. | axis = [0, 41, -0.2, 0.2]
PlotAutoCorrelation(dailies, add_weekly=False)
thinkplot.Config(axis=axis, loc="lower right", ylabel="correlation", xlabel="lag (day)") | code/chap12ex.ipynb | AllenDowney/ThinkStats2 | gpl-3.0 |
Here's what it would look like if there were a weekly cycle. | PlotAutoCorrelation(dailies, add_weekly=True)
thinkplot.Config(axis=axis, loc="lower right", xlabel="lag (days)") | code/chap12ex.ipynb | AllenDowney/ThinkStats2 | gpl-3.0 |
Prediction
The simplest way to generate predictions is to use statsmodels to fit a model to the data, then use the predict method from the results. | def GenerateSimplePrediction(results, years):
"""Generates a simple prediction.
results: results object
years: sequence of times (in years) to make predictions for
returns: sequence of predicted values
"""
n = len(years)
inter = np.ones(n)
d = dict(Intercept=inter, years=years, years2=... | code/chap12ex.ipynb | AllenDowney/ThinkStats2 | gpl-3.0 |
Here's what the prediction looks like for the high quality category, using the linear model. | name = "high"
daily = dailies[name]
_, results = RunLinearModel(daily)
years = np.linspace(0, 5, 101)
PlotSimplePrediction(results, years) | code/chap12ex.ipynb | AllenDowney/ThinkStats2 | gpl-3.0 |
When we generate predictions, we want to quatify the uncertainty in the prediction. We can do that by resampling. The following function fits a model to the data, computes residuals, then resamples from the residuals to general fake datasets. It fits the same model to each fake dataset and returns a list of results. | def SimulateResults(daily, iters=101, func=RunLinearModel):
"""Run simulations based on resampling residuals.
daily: DataFrame of daily prices
iters: number of simulations
func: function that fits a model to the data
returns: list of result objects
"""
_, results = func(daily)
fake = d... | code/chap12ex.ipynb | AllenDowney/ThinkStats2 | gpl-3.0 |
To generate predictions, we take the list of results fitted to resampled data. For each model, we use the predict method to generate predictions, and return a sequence of predictions.
If add_resid is true, we add resampled residuals to the predicted values, which generates predictions that include predictive uncertain... | def GeneratePredictions(result_seq, years, add_resid=False):
"""Generates an array of predicted values from a list of model results.
When add_resid is False, predictions represent sampling error only.
When add_resid is True, they also include residual error (which is
more relevant to prediction).
... | code/chap12ex.ipynb | AllenDowney/ThinkStats2 | gpl-3.0 |
To visualize predictions, I show a darker region that quantifies modeling uncertainty and a lighter region that quantifies predictive uncertainty. | def PlotPredictions(daily, years, iters=101, percent=90, func=RunLinearModel):
"""Plots predictions.
daily: DataFrame of daily prices
years: sequence of times (in years) to make predictions for
iters: number of simulations
percent: what percentile range to show
func: function that fits a model ... | code/chap12ex.ipynb | AllenDowney/ThinkStats2 | gpl-3.0 |
Here are the results for the high quality category. | years = np.linspace(0, 5, 101)
thinkplot.Scatter(daily.years, daily.ppg, alpha=0.1, label=name)
PlotPredictions(daily, years)
xlim = years[0] - 0.1, years[-1] + 0.1
thinkplot.Config(
title="Predictions", xlabel="Years", xlim=xlim, ylabel="Price per gram ($)"
) | code/chap12ex.ipynb | AllenDowney/ThinkStats2 | gpl-3.0 |
But there is one more source of uncertainty: how much past data should we use to build the model?
The following function generates a sequence of models based on different amounts of past data. | def SimulateIntervals(daily, iters=101, func=RunLinearModel):
"""Run simulations based on different subsets of the data.
daily: DataFrame of daily prices
iters: number of simulations
func: function that fits a model to the data
returns: list of result objects
"""
result_seq = []
starts... | code/chap12ex.ipynb | AllenDowney/ThinkStats2 | gpl-3.0 |
And this function plots the results. | def PlotIntervals(daily, years, iters=101, percent=90, func=RunLinearModel):
"""Plots predictions based on different intervals.
daily: DataFrame of daily prices
years: sequence of times (in years) to make predictions for
iters: number of simulations
percent: what percentile range to show
func: ... | code/chap12ex.ipynb | AllenDowney/ThinkStats2 | gpl-3.0 |
Here's what the high quality category looks like if we take into account uncertainty about how much past data to use. | name = "high"
daily = dailies[name]
thinkplot.Scatter(daily.years, daily.ppg, alpha=0.1, label=name)
PlotIntervals(daily, years)
PlotPredictions(daily, years)
xlim = years[0] - 0.1, years[-1] + 0.1
thinkplot.Config(
title="Predictions", xlabel="Years", xlim=xlim, ylabel="Price per gram ($)"
) | code/chap12ex.ipynb | AllenDowney/ThinkStats2 | gpl-3.0 |
Exercises
Exercise: The linear model I used in this chapter has the obvious drawback that it is linear, and there is no reason to expect prices to change linearly over time. We can add flexibility to the model by adding a quadratic term, as we did in Section 11.3.
Use a quadratic model to fit the time series of daily... | name = "high"
daily = dailies[name]
filled = FillMissing(daily)
diffs = filled.ppg.diff()
thinkplot.plot(diffs)
plt.xticks(rotation=30)
thinkplot.Config(ylabel="Daily change in price per gram ($)")
filled["slope"] = diffs.ewm(span=365).mean()
thinkplot.plot(filled.slope[-365:])
plt.xticks(rotation=30)
thinkplot.Conf... | code/chap12ex.ipynb | AllenDowney/ThinkStats2 | gpl-3.0 |
Create fake trajectories
The input trajectories for the one-way shooting version must
not include the shooting point (which is shared between the two trajectories)
be in forward-time order (so reversed paths, which are created as time goes backward, need to be reversed) | from openpathsampling.tests.test_helpers import make_1d_traj
traj1 = make_1d_traj([-0.9, 0.1, 1.1, 2.1, 3.1, 4.1, 5.1, 6.1, 7.1, 8.1, 9.1, 10.1])
traj2 = make_1d_traj([-0.8, 1.2])
traj3 = make_1d_traj([5.3, 8.3, 11.3])
traj4 = make_1d_traj([-0.6, 1.4, 3.4, 5.4, 7.4])
traj5 = make_1d_traj([-0.5, 0.5, 1.5, 2.5, 3.5, 4.5... | examples/example_one_way_shooting.ipynb | dwhswenson/OPSPiggybacker | lgpl-2.1 |
Make list of move data
The input to the pseudo-simulator is a list of data related to the move. For one-way shooting, you need the following information with each move:
the replica this move applies to (for TPS, just use 0)
the single-direction trajectory (as described in the previous section)
the index of the shootin... | moves = [
(0, traj2, 3, True, -1),
(0, traj3, 4, True, +1),
(0, traj4, 6, False, -1),
(0, traj5, 6, True, -1)
] | examples/example_one_way_shooting.ipynb | dwhswenson/OPSPiggybacker | lgpl-2.1 |
From here, you've already done everything that needs to be done to reshape your already-run simulation. Now you just need to create the fake OPS simulations.
Create OPS objects | # volumes
cv = paths.FunctionCV("x", lambda snap: snap.xyz[0][0])
left_state = paths.CVDefinedVolume(cv, float("-inf"), 0.0)
right_state = paths.CVDefinedVolume(cv, 10.0, float("inf"))
# network
network = paths.TPSNetwork(left_state, right_state)
ensemble = network.sampling_ensembles[0] # the only one | examples/example_one_way_shooting.ipynb | dwhswenson/OPSPiggybacker | lgpl-2.1 |
Create initial conditions | initial_conditions = paths.SampleSet([
paths.Sample(replica=0,
trajectory=traj1,
ensemble=ensemble)
]) | examples/example_one_way_shooting.ipynb | dwhswenson/OPSPiggybacker | lgpl-2.1 |
Create OPSPiggybacker objects
Note that the big difference here is that you use pre_joined=False. This is essential for the automated one-way shooting treatment. | shoot = oink.ShootingStub(ensemble, pre_joined=False)
sim = oink.ShootingPseudoSimulator(storage=paths.Storage('one_way.nc', 'w'),
initial_conditions=initial_conditions,
mover=shoot,
network=network) | examples/example_one_way_shooting.ipynb | dwhswenson/OPSPiggybacker | lgpl-2.1 |
Run the pseudo-simulator | sim.run(moves)
sim.storage.close() | examples/example_one_way_shooting.ipynb | dwhswenson/OPSPiggybacker | lgpl-2.1 |
Analyze with OPS | analysis_file = paths.AnalysisStorage("one_way.nc")
scheme = analysis_file.schemes[0]
scheme.move_summary(analysis_file.steps)
import openpathsampling.visualize as ops_vis
from IPython.display import SVG
history = ops_vis.PathTree(
analysis_file.steps,
ops_vis.ReplicaEvolution(replica=0)
)
# switch to the "bo... | examples/example_one_way_shooting.ipynb | dwhswenson/OPSPiggybacker | lgpl-2.1 |
The XMM Image Data
Recall that we downloaded some XMM data in the "First Look" notebook.
We downloaded three files, and just looked at one - the "science" image. | imfits = pyfits.open('a1835_xmm/P0098010101M2U009IMAGE_3000.FTZ')
im = imfits[0].data | examples/XrayImage/Modeling.ipynb | enoordeh/StatisticalMethods | gpl-2.0 |
im is the image, our observed data, presented after some "standard processing." The numbers in the pixels are counts (i.e. numbers of photoelectrons recorded by the CCD during the exposure).
We display the image on a log scale, which allows us to simultaneously see both the cluster of galaxies in the center, and th... | plt.imshow(viz.scale_image(im, scale='log', max_cut=40), cmap='gray', origin='lower'); | examples/XrayImage/Modeling.ipynb | enoordeh/StatisticalMethods | gpl-2.0 |
A Model for the Cluster of Galaxies
We will use a common parametric model for the surface brightness of galaxy clusters: the azimuthally symmetric beta model:
$S(r) = S_0 \left[1.0 + \left(\frac{r}{r_c}\right)^2\right]^{-3\beta + 1/2}$,
where $r$ is projected distance from the cluster center.
The parameters of thi... | pbfits = pyfits.open('a1835_xmm/P0098010101M2X000BKGMAP3000.FTZ')
pb = pbfits[0].data
exfits = pyfits.open('a1835_xmm/P0098010101M2U009EXPMAP3000.FTZ')
ex = exfits[0].data | examples/XrayImage/Modeling.ipynb | enoordeh/StatisticalMethods | gpl-2.0 |
The "Exposure Map"
The ex image is in units of seconds, and represents the effective exposure time at each pixel position.
This is actually the product of the exposure time that the detector was exposed for, and a relative sensitivity map accounting for the vignetting of the telescope, dithering, and bad pixels w... | plt.imshow(ex, cmap='gray', origin='lower');
plt.savefig("figures/cluster_expmap.png") | examples/XrayImage/Modeling.ipynb | enoordeh/StatisticalMethods | gpl-2.0 |
The "Particle Background Map"
pb is not data at all, but rather a model for the expected counts/pixel in this specific observation due to the "quiescent particle background."
This map comes out of a blackbox in the processing pipeline. Even though there are surely uncertainties in it, we have no quantitative descr... | plt.imshow(pb, cmap='gray', origin='lower');
plt.savefig("figures/cluster_pbmap.png") | examples/XrayImage/Modeling.ipynb | enoordeh/StatisticalMethods | gpl-2.0 |
Masking out the other sources
There are non-cluster sources in this field. To simplify the model-building exercise, we will crudely mask them out for the moment.
A convenient way to do this is by setting the exposure map to zero in these locations - as if a set of tiny little shutters in front of each of those pix... | mask = np.loadtxt('a1835_xmm/M2ptsrc.txt')
for reg in mask:
# this is inefficient but effective
for i in np.round(reg[1]+np.arange(-np.ceil(reg[2]),np.ceil(reg[2]))):
for j in np.round(reg[0]+np.arange(-np.ceil(reg[2]),np.ceil(reg[2]))):
if (i-reg[1])**2 + (j-reg[0])**2 <= reg[2]**2:
... | examples/XrayImage/Modeling.ipynb | enoordeh/StatisticalMethods | gpl-2.0 |
As a sanity check, let's have a look at the modified exposure map.
Compare the location of the "holes" to the science image above. | plt.imshow(ex, cmap='gray', origin='lower');
plt.savefig("figures/cluster_expmap_masked.png") | examples/XrayImage/Modeling.ipynb | enoordeh/StatisticalMethods | gpl-2.0 |
A Generative Model for the X-ray Image
All of the discussion above was in terms of predicting the expected number of counts in each pixel, $\mu_k$. This is not what we observe: we observe counts.
To be able to generate a mock dataset, we need to make an assumption about the form of the sampling distribution for the... | # import cluster_pgm
# cluster_pgm.forward()
from IPython.display import Image
Image(filename="cluster_pgm_forward.png")
def beta_model_profile(r, S0, rc, beta):
'''
The fabled beta model, radial profile S(r)
'''
return S0 * (1.0 + (r/rc)**2)**(-3.0*beta + 0.5)
def beta_model_image(x, y, x0, y0, S0, ... | examples/XrayImage/Modeling.ipynb | enoordeh/StatisticalMethods | gpl-2.0 |
Points in SimpleITK
Utility functions
A number of functions that deal with point data in a uniform manner. | import numpy as np
def point2str(point, precision=1):
"""
Format a point for printing, based on specified precision with trailing zeros. Uniform printing for vector-like data
(tuple, numpy array, list).
Args:
point (vector-like): nD point with floating point coordinates.
precision... | 22_Transforms.ipynb | thewtex/SimpleITK-Notebooks | apache-2.0 |
In SimpleITK points can be represented by any vector-like data type. In Python these include Tuple, Numpy array, and List. In general Python will treat these data types differently, as illustrated by the print function below. | # SimpleITK points represented by vector-like data structures.
point_tuple = (9.0, 10.531, 11.8341)
point_np_array = np.array([9.0, 10.531, 11.8341])
point_list = [9.0, 10.531, 11.8341]
print(point_tuple)
print(point_np_array)
print(point_list)
# Uniform printing with specified precision.
precision = 2
print(point2s... | 22_Transforms.ipynb | thewtex/SimpleITK-Notebooks | apache-2.0 |
Global Transformations
All global transformations <i>except translation</i> are of the form:
$$T(\mathbf{x}) = A(\mathbf{x}-\mathbf{c}) + \mathbf{t} + \mathbf{c}$$
In ITK speak (when printing your transformation):
<ul>
<li>Matrix: the matrix $A$</li>
<li>Center: the point $\mathbf{c}$</li>
<li>Translation: the vector $... | # A 3D translation. Note that you need to specify the dimensionality, as the sitk TranslationTransform
# represents both 2D and 3D translations.
dimension = 3
offset =(1,2,3) # offset can be any vector-like data
translation = sitk.TranslationTransform(dimension, offset)
print(translation)
# Transform a poin... | 22_Transforms.ipynb | thewtex/SimpleITK-Notebooks | apache-2.0 |
Euler2DTransform | point = [10, 11]
rotation2D = sitk.Euler2DTransform()
rotation2D.SetTranslation((7.2, 8.4))
rotation2D.SetAngle(np.pi/2)
print('original point: ' + point2str(point) + '\n'
'transformed point: ' + point2str(rotation2D.TransformPoint(point)))
# Change the center of rotation so that it coincides with the point we w... | 22_Transforms.ipynb | thewtex/SimpleITK-Notebooks | apache-2.0 |
VersorTransform | # Rotation only, parametrized by Versor (vector part of unit quaternion),
# quaternion defined by rotation of theta around axis n:
# q = [n*sin(theta/2), cos(theta/2)]
# 180 degree rotation around z axis
# Use a versor:
rotation1 = sitk.VersorTransform([0,0,1,0])
# Use axis-angle:
rotation2 = sitk.V... | 22_Transforms.ipynb | thewtex/SimpleITK-Notebooks | apache-2.0 |
We applied the "same" transformation to the same point, so why are the results slightly different for the second initialization method?
This is where theory meets practice. Using the axis-angle initialization method involves trigonometric functions which on a fixed precision machine lead to these slight differences. In... | dimension = 3
t =(1,2,3)
translation = sitk.TranslationTransform(dimension, t)
# Only need to copy the translational component.
rigid_euler = sitk.Euler3DTransform()
rigid_euler.SetTranslation(translation.GetOffset())
rigid_versor = sitk.VersorRigid3DTransform()
rigid_versor.SetTranslation(translation.GetOff... | 22_Transforms.ipynb | thewtex/SimpleITK-Notebooks | apache-2.0 |
Rotation to Rigid [3D]
Copy the matrix or versor and <b>center of rotation</b>. | rotationCenter = (10, 10, 10)
rotation = sitk.VersorTransform([0,0,1,0], rotationCenter)
rigid_euler = sitk.Euler3DTransform()
rigid_euler.SetMatrix(rotation.GetMatrix())
rigid_euler.SetCenter(rotation.GetCenter())
rigid_versor = sitk.VersorRigid3DTransform()
rigid_versor.SetRotation(rotation.GetVersor())
#rigid_vers... | 22_Transforms.ipynb | thewtex/SimpleITK-Notebooks | apache-2.0 |
Similarity [2D]
When the center of the similarity transformation is not at the origin the effect of the transformation is not what most of us expect. This is readily visible if we limit the transformation to scaling: $T(\mathbf{x}) = s\mathbf{x}-s\mathbf{c} + \mathbf{c}$. Changing the transformation's center results in... | def display_center_effect(x, y, tx, point_list, xlim, ylim):
tx.SetCenter((x,y))
transformed_point_list = [ tx.TransformPoint(p) for p in point_list]
plt.scatter(list(np.array(transformed_point_list).T)[0],
list(np.array(transformed_point_list).T)[1],
marker='^',
... | 22_Transforms.ipynb | thewtex/SimpleITK-Notebooks | apache-2.0 |
Rigid to Similarity [3D]
Copy the translation, center, and matrix or versor. | rotation_center = (100, 100, 100)
theta_x = 0.0
theta_y = 0.0
theta_z = np.pi/2.0
translation = (1,2,3)
rigid_euler = sitk.Euler3DTransform(rotation_center, theta_x, theta_y, theta_z, translation)
similarity = sitk.Similarity3DTransform()
similarity.SetMatrix(rigid_euler.GetMatrix())
similarity.SetTranslation(rigid_e... | 22_Transforms.ipynb | thewtex/SimpleITK-Notebooks | apache-2.0 |
Similarity to Affine [3D]
Copy the translation, center and matrix. | rotation_center = (100, 100, 100)
axis = (0,0,1)
angle = np.pi/2.0
translation = (1,2,3)
scale_factor = 2.0
similarity = sitk.Similarity3DTransform(scale_factor, axis, angle, translation, rotation_center)
affine = sitk.AffineTransform(3)
affine.SetMatrix(similarity.GetMatrix())
affine.SetTranslation(similarity.GetTran... | 22_Transforms.ipynb | thewtex/SimpleITK-Notebooks | apache-2.0 |
Scale Transform
Just as the case was for the similarity transformation above, when the transformations center is not at the origin, instead of a pure anisotropic scaling we also have translation ($T(\mathbf{x}) = \mathbf{s}^T\mathbf{x}-\mathbf{s}^T\mathbf{c} + \mathbf{c}$). | # 2D square centered on (0,0).
points = [np.array((-1,-1)), np.array((-1,1)), np.array((1,1)), np.array((1,-1))]
# Scale by half in x and 2 in y.
scale = sitk.ScaleTransform(2, (0.5,2));
# Interactively change the location of the center.
interact(display_center_effect, x=(-10,10), y=(-10,10),tx = fixed(scale), point_... | 22_Transforms.ipynb | thewtex/SimpleITK-Notebooks | apache-2.0 |
Scale Versor
This is not what you would expect from the name (composition of anisotropic scaling and rigid). This is:
$$T(x) = (R+S)(\mathbf{x}-\mathbf{c}) + \mathbf{t} + \mathbf{c},\;\; \textrm{where } S= \left[\begin{array}{ccc} s_0-1 & 0 & 0 \ 0 & s_1-1 & 0 \ 0 & 0 & s_2-1 \end{array}\right]$$
There is no natural w... | scales = (0.5,0.7,0.9)
translation = (1,2,3)
axis = (0,0,1)
angle = 0.0
scale_versor = sitk.ScaleVersor3DTransform(scales, axis, angle, translation)
print(scale_versor) | 22_Transforms.ipynb | thewtex/SimpleITK-Notebooks | apache-2.0 |
Scale Skew Versor
Again, not what you expect based on the name, this is not a composition of transformations. This is:
$$T(x) = (R+S+K)(\mathbf{x}-\mathbf{c}) + \mathbf{t} + \mathbf{c},\;\; \textrm{where } S = \left[\begin{array}{ccc} s_0-1 & 0 & 0 \ 0 & s_1-1 & 0 \ 0 & 0 & s_2-1 \end{array}\right]\;\; \textrm{and } K ... | scale = (2,2.1,3)
skew = np.linspace(start=0.0, stop=1.0, num=6) #six eqaully spaced values in[0,1], an arbitrary choice
translation = (1,2,3)
versor = (0,0,0,1.0)
scale_skew_versor = sitk.ScaleSkewVersor3DTransform(scale, skew, versor, translation)
print(scale_skew_versor) | 22_Transforms.ipynb | thewtex/SimpleITK-Notebooks | apache-2.0 |
Bounded Transformations
SimpleITK supports two types of bounded non-rigid transformations, BSplineTransform (sparse represntation) and DisplacementFieldTransform (dense representation).
Transforming a point that is outside the bounds will return the original point - identity transform. | #
# This function displays the effects of the deformable transformation on a grid of points by scaling the
# initial displacements (either of control points for bspline or the deformation field itself). It does
# assume that all points are contained in the range(-2.5,-2.5), (2.5,2.5).
#
def display_displacement_scaling... | 22_Transforms.ipynb | thewtex/SimpleITK-Notebooks | apache-2.0 |
BSpline
Using a sparse set of control points to control a free form deformation. | # Create the transformation (when working with images it is easier to use the BSplineTransformInitializer function
# or its object oriented counterpart BSplineTransformInitializerFilter).
dimension = 2
spline_order = 3
direction_matrix_row_major = [1.0,0.0,0.0,1.0] # identity, mesh is axis aligned
origin = [-1.0,-1.0] ... | 22_Transforms.ipynb | thewtex/SimpleITK-Notebooks | apache-2.0 |
DisplacementField
A dense set of vectors representing the displacment inside the given domain. The most generic representation of a transformation. | # Create the displacment field.
# When working with images the safer thing to do is use the image based constructor,
# sitk.DisplacementFieldTransform(my_image), all the fixed parameters will be set correctly and the displacement
# field is initialized using the vectors stored in the image. SimpleITK requires tha... | 22_Transforms.ipynb | thewtex/SimpleITK-Notebooks | apache-2.0 |
Displacement field transform created from an image. Remember that SimpleITK will clear the image you provide, as shown in the cell below. | displacement_image = sitk.Image([64,64], sitk.sitkVectorFloat64)
# The only point that has any displacement is (0,0)
displacement = (0.5,0.5)
displacement_image[0,0] = displacement
print('Original displacement image size: ' + point2str(displacement_image.GetSize()))
displacement_field_transform = sitk.DisplacementFie... | 22_Transforms.ipynb | thewtex/SimpleITK-Notebooks | apache-2.0 |
Composite transform (Transform)
The generic SimpleITK transform class. This class can represent both a single transformation (global, local), or a composite transformation (multiple transformations applied one after the other). This is the output typed returned by the SimpleITK registration framework.
The choice of wh... | # Create a composite transformation: T_affine(T_rigid(x)).
rigid_center = (100,100,100)
theta_x = 0.0
theta_y = 0.0
theta_z = np.pi/2.0
rigid_translation = (1,2,3)
rigid_euler = sitk.Euler3DTransform(rigid_center, theta_x, theta_y, theta_z, rigid_translation)
affine_center = (20, 20, 20)
affine_translation = (5,6,7) ... | 22_Transforms.ipynb | thewtex/SimpleITK-Notebooks | apache-2.0 |
Composite transforms enable a combination of a global transformation with multiple local/bounded transformations. This is useful if we want to apply deformations only in regions that deform while other regions are only effected by the global transformation.
The following code illustrates this, where the whole region is... | # Global transformation.
translation = sitk.TranslationTransform(2,(1.0,0.0))
# Displacement in region 1.
displacement1 = sitk.DisplacementFieldTransform(2)
field_size = [10,20]
field_origin = [-1.0,-1.0]
field_spacing = [2.0/9.0,2.0/19.0]
field_direction = [1,0,0,1] # direction cosine matrix (row major order) ... | 22_Transforms.ipynb | thewtex/SimpleITK-Notebooks | apache-2.0 |
Writing and Reading
The SimpleITK.ReadTransform() returns a SimpleITK.Transform . The content of the file can be any of the SimpleITK transformations or a composite (set of tranformations). | import os
# Create a 2D rigid transformation, write it to disk and read it back.
basic_transform = sitk.Euler2DTransform()
basic_transform.SetTranslation((1,2))
basic_transform.SetAngle(np.pi/2)
full_file_name = os.path.join(OUTPUT_DIR, 'euler2D.tfm')
sitk.WriteTransform(basic_transform, full_file_name)
# The ReadT... | 22_Transforms.ipynb | thewtex/SimpleITK-Notebooks | apache-2.0 |
Motivating Support Vector Machines
Support Vector Machines (SVMs) are a powerful supervised learning algorithm used for classification or for regression. SVMs are a discriminative classifier: that is, they draw a boundary between clusters of data.
Let's show a quick example of support vector classification. First we ne... | from sklearn.datasets.samples_generator import make_blobs
X, y = make_blobs(n_samples=50, centers=2,
random_state=0, cluster_std=0.60)
plt.figure(figsize=(8,8))
plt.scatter(X[:, 0], X[:, 1], c=y, s=50); | notebooks/05-SVM.ipynb | albahnsen/PracticalMachineLearningClass | mit |
A discriminative classifier attempts to draw a line between the two sets of data. Immediately we see a problem: such a line is ill-posed! For example, we could come up with several possibilities which perfectly discriminate between the classes in this example: | xfit = np.linspace(-1, 3.5)
plt.figure(figsize=(8,8))
plt.scatter(X[:, 0], X[:, 1], c=y, s=50)
for m, b in [(1, 0.65), (0.5, 1.6), (-0.2, 2.9)]:
plt.plot(xfit, m * xfit + b, '-k')
plt.xlim(-1, 3.5); | notebooks/05-SVM.ipynb | albahnsen/PracticalMachineLearningClass | mit |
These are three very different separaters which perfectly discriminate between these samples. Depending on which you choose, a new data point will be classified almost entirely differently!
How can we improve on this?
Support Vector Machines: Maximizing the Margin
Support vector machines are one way to address this.
Wh... | xfit = np.linspace(-1, 3.5)
plt.figure(figsize=(8,8))
plt.scatter(X[:, 0], X[:, 1], c=y, s=50)
for m, b, d in [(1, 0.65, 0.33), (0.5, 1.6, 0.55), (-0.2, 2.9, 0.2)]:
yfit = m * xfit + b
plt.plot(xfit, yfit, '-k')
plt.fill_between(xfit, yfit - d, yfit + d, edgecolor='none', color='#AAAAAA', alpha=0.4)
plt.... | notebooks/05-SVM.ipynb | albahnsen/PracticalMachineLearningClass | mit |
Notice here that if we want to maximize this width, the middle fit is clearly the best.
This is the intuition of support vector machines, which optimize a linear discriminant model in conjunction with a margin representing the perpendicular distance between the datasets.
Fitting a Support Vector Machine
Now we'll fit a... | from sklearn.svm import SVC # "Support Vector Classifier"
clf = SVC(kernel='linear')
clf.fit(X, y) | notebooks/05-SVM.ipynb | albahnsen/PracticalMachineLearningClass | mit |
To better visualize what's happening here, let's create a quick convenience function that will plot SVM decision boundaries for us: | import warnings
warnings.filterwarnings('ignore')
def plot_svc_decision_function(clf, ax=None):
"""Plot the decision function for a 2D SVC"""
if ax is None:
ax = plt.gca()
x = np.linspace(plt.xlim()[0], plt.xlim()[1], 30)
y = np.linspace(plt.ylim()[0], plt.ylim()[1], 30)
Y, X = np.meshgrid(... | notebooks/05-SVM.ipynb | albahnsen/PracticalMachineLearningClass | mit |
Notice that the dashed lines touch a couple of the points: these points are the pivotal pieces of this fit, and are known as the support vectors (giving the algorithm its name).
In scikit-learn, these are stored in the support_vectors_ attribute of the classifier: | plt.figure(figsize=(8,8))
plt.scatter(X[:, 0], X[:, 1], c=y, s=50)
plot_svc_decision_function(clf)
plt.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1],
s=200, facecolors='none'); | notebooks/05-SVM.ipynb | albahnsen/PracticalMachineLearningClass | mit |
Let's use IPython's interact functionality to explore how the distribution of points affects the support vectors and the discriminative fit.
(This is only available in IPython 2.0+, and will not work in a static view) | from IPython.html.widgets import interact
def plot_svm(N=10):
X, y = make_blobs(n_samples=200, centers=2,
random_state=0, cluster_std=0.60)
X = X[:N]
y = y[:N]
clf = SVC(kernel='linear')
clf.fit(X, y)
plt.figure(figsize=(8,8))
plt.scatter(X[:, 0], X[:, 1], c=y, s=50)
... | notebooks/05-SVM.ipynb | albahnsen/PracticalMachineLearningClass | mit |
Notice the unique thing about SVM is that only the support vectors matter: that is, if you moved any of the other points without letting them cross the decision boundaries, they would have no effect on the classification results!
Going further: Kernel Methods
Where SVM gets incredibly exciting is when it is used in con... | from sklearn.datasets.samples_generator import make_circles
X, y = make_circles(100, factor=.1, noise=.1)
clf = SVC(kernel='linear').fit(X, y)
plt.figure(figsize=(8,8))
plt.scatter(X[:, 0], X[:, 1], c=y, s=50)
# plot_svc_decision_function(clf); | notebooks/05-SVM.ipynb | albahnsen/PracticalMachineLearningClass | mit |
Clearly, no linear discrimination will ever separate these data.
One way we can adjust this is to apply a kernel, which is some functional transformation of the input data.
For example, one simple model we could use is a radial basis function | r = np.exp(-(X[:, 0] ** 2 + X[:, 1] ** 2)) | notebooks/05-SVM.ipynb | albahnsen/PracticalMachineLearningClass | mit |
If we plot this along with our data, we can see the effect of it: | from mpl_toolkits import mplot3d
def plot_3D(elev=30, azim=30):
plt.figure(figsize=(8,8))
ax = plt.subplot(projection='3d')
ax.scatter3D(X[:, 0], X[:, 1], r, c=y, s=50)
ax.view_init(elev=elev, azim=azim)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('r')
interact(plot_3D, elev=[-90, ... | notebooks/05-SVM.ipynb | albahnsen/PracticalMachineLearningClass | mit |
We can see that with this additional dimension, the data becomes trivially linearly separable!
This is a relatively simple kernel; SVM has a more sophisticated version of this kernel built-in to the process. This is accomplished by using kernel='rbf', short for radial basis function: | clf = SVC(kernel='rbf')
clf.fit(X, y)
plt.figure(figsize=(8,8))
plt.scatter(X[:, 0], X[:, 1], c=y, s=50)
plot_svc_decision_function(clf)
| notebooks/05-SVM.ipynb | albahnsen/PracticalMachineLearningClass | mit |
Sommer 2015
Datenmodell
Aufgabe
Erstellen Sie eine Abfrage, mit der Sie die Daten aller Kunden, die Anzahl deren Aufträge, die Anzahl der Fahrten und die Summe der Streckenkilometer erhalten. Die Ausgabe soll nach Kunden-PLZ absteigend sortiert sein.
Lösung
mysql
select k.kd_id,
(select count(a.Au_ID) from auftr... | %%sql
select k.kd_id, k.kd_plz,
(select count(a.Au_ID) from auftrag a where a.au_kd_id = k.kd_id ) as AnzahlAuftr,
(select count(f.`f_id`) from fahrten f, auftrag a
where f.f_au_id = a.au_id and a.`au_kd_id` = k.`kd_id`) as AnzahlFahrt,
(select sum(ts.ts_strecke) from teilstrecke ts, fahrten f,... | jup_notebooks/datenbanken/SubSelects.ipynb | steinam/teacher | mit |
Warum geht kein Join ??
mysql
select k.kd_id, k.`kd_firma`, k.`kd_plz`,
count(a.Au_ID) as AnzAuftrag,
count(f.f_id) as AnzFahrt,
sum(ts.ts_strecke) as SumStrecke
from kunde k left join auftrag a
on k.`kd_id` = a.`au_kd_id`
left join fahrten f
on a.`au_id` = f.`f_au_id`
left join teils... | %%sql
select k.kd_id, k.`kd_firma`, k.`kd_plz`,
count(distinct a.Au_ID) as AnzAuftrag,
count(distinct f.f_id) as AnzFahrt,
sum(ts.ts_strecke) as SumStrecke
from kunde k left join auftrag a
on k.`kd_id` = a.`au_kd_id`
left join fahrten f
on a.`au_id` = f.`f_au_id`
left join teilstreck... | jup_notebooks/datenbanken/SubSelects.ipynb | steinam/teacher | mit |
Der Ansatz mit Join funktioniert in dieser Form nicht, da spätestens beim 2. Join die Firma Trappo mit 2 Datensätzen aus dem 1. Join verknüpft wird. Deshalb wird auch die Anzahl der Fahren verdoppelt. Dies wiederholt sich beim 3. Join.
Die folgende Abfrage zeigt ohne die Aggregatfunktionen das jeweilige Ausgangsergebni... | %%sql
SELECT kunde.Kd_ID, kunde.Kd_Firma, kunde.Kd_Strasse, kunde.Kd_PLZ,
kunde.Kd_Ort, COUNT(distinct auftrag.Au_ID) AS AnzahlAuftr, COUNT(distinct fahrten.F_ID) AS AnzahlFahrt, SUM(teilstrecke.Ts_Strecke) AS SumStrecke
FROM kunde
LEFT JOIN auftrag ON auftrag.Au_Kd_ID = kunde.Kd_ID
LEFT JOIN fahrten ON fahrten.F_Au_I... | jup_notebooks/datenbanken/SubSelects.ipynb | steinam/teacher | mit |
Es geht auch mit einem Subselect
``mysql
select kd.Kd_Name,
(select COUNT(*) from Rechnung as R
where R.Rg_KD_ID= KD.Kd_IDand year(R.Rg_Datum`) = 2015)
from Kunde kd inner join `zahlungsbedingung`
on kd.`Kd_Zb_ID` = `zahlungsbedingung`.`Zb_ID`
and zahlungsbedingung.Zb_SkontoProzent > 3.0
``` | %%sql
select kd.`Kd_Name`,
(select COUNT(*) from Rechnung as R
where R.`Rg_KD_ID` = KD.`Kd_ID` and year(R.`Rg_Datum`) = 2015) as Anzahl
from Kunde kd inner join `zahlungsbedingung`
on kd.`Kd_Zb_ID` = `zahlungsbedingung`.`Zb_ID`
and `zahlungsbedingung`.`Zb_SkontoProzent` > 3.0
%%sql
-- wortmann u... | jup_notebooks/datenbanken/SubSelects.ipynb | steinam/teacher | mit |
Lösung | %sql mysql://steinam:steinam@localhost/versicherung_complete
%%sql
select min(`vv`.`Abschlussdatum`) as 'Erster Abschluss', `vv`.`Mitarbeiter_ID`
from `versicherungsvertrag` vv inner join mitarbeiter m
on vv.`Mitarbeiter_ID` = m.`ID`
where vv.`Mitarbeiter_ID` in ( select m.`ID` from mitarbeiter m
inner join... | jup_notebooks/datenbanken/SubSelects.ipynb | steinam/teacher | mit |
Simple Model
This section corresponds to the code in the Running Your First Model section of the tutorial.
First, import the base classes we'll use | from mesa import Agent, Model
from mesa.time import RandomActivation
import random | examples/Tutorial-Boltzmann_Wealth_Model/.ipynb_checkpoints/Introduction to Mesa Tutorial Code-checkpoint.ipynb | projectmesa/mesa-examples | apache-2.0 |
Next, create the agent and model classes: | class MoneyAgent(Agent):
""" An agent with fixed initial wealth."""
def __init__(self, unique_id):
self.unique_id = unique_id
self.wealth = 1
def step(self, model):
if self.wealth == 0:
return
other_agent = random.choice(model.schedule.agents)
other_agent... | examples/Tutorial-Boltzmann_Wealth_Model/.ipynb_checkpoints/Introduction to Mesa Tutorial Code-checkpoint.ipynb | projectmesa/mesa-examples | apache-2.0 |
Create a model and run it for 10 steps: | model = MoneyModel(10)
for i in range(10):
model.step() | examples/Tutorial-Boltzmann_Wealth_Model/.ipynb_checkpoints/Introduction to Mesa Tutorial Code-checkpoint.ipynb | projectmesa/mesa-examples | apache-2.0 |
And display a histogram of agent wealths: | agent_wealth = [a.wealth for a in model.schedule.agents]
plt.hist(agent_wealth) | examples/Tutorial-Boltzmann_Wealth_Model/.ipynb_checkpoints/Introduction to Mesa Tutorial Code-checkpoint.ipynb | projectmesa/mesa-examples | apache-2.0 |
Create and run 100 models, and visualize the wealth distribution across all of them: | all_wealth = []
for j in range(100):
# Run the model
model = MoneyModel(10)
for i in range(10):
model.step()
# Store the results
for agent in model.schedule.agents:
all_wealth.append(agent.wealth)
plt.hist(all_wealth, bins=range(max(all_wealth)+1)) | examples/Tutorial-Boltzmann_Wealth_Model/.ipynb_checkpoints/Introduction to Mesa Tutorial Code-checkpoint.ipynb | projectmesa/mesa-examples | apache-2.0 |
Adding space
This section puts the agents on a grid, corresponding to the Adding Space section of the tutorial.
For this, we need to import the grid class: | from mesa.space import MultiGrid | examples/Tutorial-Boltzmann_Wealth_Model/.ipynb_checkpoints/Introduction to Mesa Tutorial Code-checkpoint.ipynb | projectmesa/mesa-examples | apache-2.0 |
Create the new model object. (Note that this overwrites the MoneyModel object created above) | class MoneyModel(Model):
"""A model with some number of agents."""
def __init__(self, N, width, height):
self.running = True
self.num_agents = N
self.grid = MultiGrid(height, width, True)
self.schedule = RandomActivation(self)
# Create agents
for i in range(self.n... | examples/Tutorial-Boltzmann_Wealth_Model/.ipynb_checkpoints/Introduction to Mesa Tutorial Code-checkpoint.ipynb | projectmesa/mesa-examples | apache-2.0 |
And create the agent to go along with it: | class MoneyAgent(Agent):
""" An agent with fixed initial wealth."""
def __init__(self, unique_id):
self.unique_id = unique_id
self.wealth = 1
def move(self, model):
possible_steps = model.grid.get_neighborhood(self.pos, moore=True, include_center=False)
new_position = random... | examples/Tutorial-Boltzmann_Wealth_Model/.ipynb_checkpoints/Introduction to Mesa Tutorial Code-checkpoint.ipynb | projectmesa/mesa-examples | apache-2.0 |
Create a model with 50 agents and a 10x10 grid, and run for 20 steps | model = MoneyModel(50, 10, 10)
for i in range(20):
model.step() | examples/Tutorial-Boltzmann_Wealth_Model/.ipynb_checkpoints/Introduction to Mesa Tutorial Code-checkpoint.ipynb | projectmesa/mesa-examples | apache-2.0 |
Visualize the number of agents on each grid cell: | import numpy as np
agent_counts = np.zeros((model.grid.width, model.grid.height))
for cell in model.grid.coord_iter():
cell_content, x, y = cell
agent_count = len(cell_content)
agent_counts[x][y] = agent_count
plt.imshow(agent_counts, interpolation='nearest')
plt.colorbar()
| examples/Tutorial-Boltzmann_Wealth_Model/.ipynb_checkpoints/Introduction to Mesa Tutorial Code-checkpoint.ipynb | projectmesa/mesa-examples | apache-2.0 |
Collecting Data
Add a Data Collector to the model, as explained in the corresponding section of the tutorial.
First, import the DataCollector | from mesa.datacollection import DataCollector | examples/Tutorial-Boltzmann_Wealth_Model/.ipynb_checkpoints/Introduction to Mesa Tutorial Code-checkpoint.ipynb | projectmesa/mesa-examples | apache-2.0 |
Compute the agents' Gini coefficient, measuring inequality. | def compute_gini(model):
'''
Compute the current Gini coefficient.
Args:
model: A MoneyModel instance
Returns:
The Gini Coefficient for the model's current step.
'''
agent_wealths = [agent.wealth for agent in model.schedule.agents]
x = sorted(agent_wealths)
N = model... | examples/Tutorial-Boltzmann_Wealth_Model/.ipynb_checkpoints/Introduction to Mesa Tutorial Code-checkpoint.ipynb | projectmesa/mesa-examples | apache-2.0 |
This MoneyModel is identical to the one above, except for the self.datacollector = ... line at the end of the __init__ method, and the collection in step. | class MoneyModel(Model):
"""A model with some number of agents."""
def __init__(self, N, width, height):
self.running = True
self.num_agents = N
self.grid = MultiGrid(height, width, True)
self.schedule = RandomActivation(self)
# Create agents
for i in range(self.n... | examples/Tutorial-Boltzmann_Wealth_Model/.ipynb_checkpoints/Introduction to Mesa Tutorial Code-checkpoint.ipynb | projectmesa/mesa-examples | apache-2.0 |
Now instantiate a model, run it for 100 steps... | model = MoneyModel(50, 10, 10)
for i in range(100):
model.step() | examples/Tutorial-Boltzmann_Wealth_Model/.ipynb_checkpoints/Introduction to Mesa Tutorial Code-checkpoint.ipynb | projectmesa/mesa-examples | apache-2.0 |
... And collect and plot the data it generated: | gini = model.datacollector.get_model_vars_dataframe()
gini.head()
gini.plot()
agent_wealth = model.datacollector.get_agent_vars_dataframe()
agent_wealth.head()
end_wealth = agent_wealth.xs(99, level="Step")["Wealth"]
end_wealth.hist(bins=range(agent_wealth.Wealth.max()+1))
one_agent_wealth = agent_wealth.xs(14, lev... | examples/Tutorial-Boltzmann_Wealth_Model/.ipynb_checkpoints/Introduction to Mesa Tutorial Code-checkpoint.ipynb | projectmesa/mesa-examples | apache-2.0 |
Batch Run
Run a parameter sweep, as explained in the Batch Run tutorial section.
Import the Mesa BatchRunner: | from mesa.batchrunner import BatchRunner | examples/Tutorial-Boltzmann_Wealth_Model/.ipynb_checkpoints/Introduction to Mesa Tutorial Code-checkpoint.ipynb | projectmesa/mesa-examples | apache-2.0 |
Set up the batch run: | parameters = {"height": 10, "width": 10, "N": range(10, 500, 10)}
batch_run = BatchRunner(MoneyModel, parameters, iterations=5, max_steps=100,
model_reporters={"Gini": compute_gini}) | examples/Tutorial-Boltzmann_Wealth_Model/.ipynb_checkpoints/Introduction to Mesa Tutorial Code-checkpoint.ipynb | projectmesa/mesa-examples | apache-2.0 |
Run the parameter sweep; this step might take a while: | batch_run.run_all() | examples/Tutorial-Boltzmann_Wealth_Model/.ipynb_checkpoints/Introduction to Mesa Tutorial Code-checkpoint.ipynb | projectmesa/mesa-examples | apache-2.0 |
Export and plot the results: | run_data = batch_run.get_model_vars_dataframe()
run_data.head()
plt.scatter(run_data.N, run_data.Gini)
plt.xlabel("Number of agents")
plt.ylabel("Gini Coefficient") | examples/Tutorial-Boltzmann_Wealth_Model/.ipynb_checkpoints/Introduction to Mesa Tutorial Code-checkpoint.ipynb | projectmesa/mesa-examples | apache-2.0 |
Dictionary Comprehensions
Just like List Comprehensions, Dictionary Data Types also support their own version of comprehension for quick creation. It is not as commonly used as List Comprehensions, but the syntax is: | {x:x**2 for x in range(10)} | Advanced Dictionaries.ipynb | jserenson/Python_Bootcamp | gpl-3.0 |
One of the reasons it is not as common is the difficulty in structuring the key names that are not based off the values.
Iteration over keys,values, and items
Dictionaries can be iterated over using the iter methods available in a dictionary. For example: | for k in d.iterkeys():
print k
for v in d.itervalues():
print v
for item in d.iteritems():
print item | Advanced Dictionaries.ipynb | jserenson/Python_Bootcamp | gpl-3.0 |
view items,keys and values
You can use the view methods to view items keys and values. For example: | d.viewitems()
d.viewkeys()
d.viewvalues() | Advanced Dictionaries.ipynb | jserenson/Python_Bootcamp | gpl-3.0 |
2. Construindo DFNs com Keras
Reshaping MNIST data | #Achatamos imagem em um vetor
X_train = X_train.reshape(X_train.shape[0], np.prod(X_train.shape[1:]))
X_test = X_test.reshape(X_test.shape[0], np.prod(X_test.shape[1:]))
#Sequential é a API que permite construirmos um modelo ao adicionar incrementalmente layers
from keras.models import Sequential
from keras.layers imp... | src/Keras Tutorial.ipynb | MLIME/12aMostra | gpl-3.0 |
3. Construindo CNNs com Keras
Reshaping MNIST data | X_train = X_train.reshape(X_train.shape[0], 28, 28, 1)
X_test = X_test.reshape(X_test.shape[0], 28, 28, 1) | src/Keras Tutorial.ipynb | MLIME/12aMostra | gpl-3.0 |
Compilando e ajustando CNN | from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import MaxPooling2D
from keras.layers.convolutional import Conv2D
CNN = Sequential()
CNN.add(Conv2D(32, (3, 3), padding='same', activation='relu',
input_shape=(28, 28, 1),))
CNN.add(MaxPooling2D(pool... | src/Keras Tutorial.ipynb | MLIME/12aMostra | gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.