markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Question: What do you do when you get an exception?
You can get information about exceptions. | #1/0
def divide2(numerator, denominator):
try:
result = numerator/denominator
print("result = %f" % result)
except (ZeroDivisionError, TypeError):
print("Got an exception")
divide2(1, "x")
# Why doesn't this catch the exception?
# How do we fix it?
divide2("x", 2)
# Exceptions in file hand... | Spring2018/Debugging-and-Exceptions/Exceptions.ipynb | UWSEDS/LectureNotes | bsd-2-clause |
Generating Exceptions
Why generate exceptions? (Don't I have enough unintentional errors?) | import pandas as pd
def func(df):
""""
:param pd.DataFrame df: should have a column named "hours"
"""
if not "hours" in df.columns:
raise ValueError("DataFrame should have a column named 'hours'.")
df = pd.DataFrame({'hours': range(10) })
func(df)
df = pd.DataFrame({'years': range(10) })
# Gen... | Spring2018/Debugging-and-Exceptions/Exceptions.ipynb | UWSEDS/LectureNotes | bsd-2-clause |
Frequency tables
Ibis provides the value_counts API, just like pandas, for computing a frequency table for a table column or array expression. You might have seen it used already earlier in the tutorial. | lineitem = con.table('tpch_lineitem')
orders = con.table('tpch_orders')
items = (orders.join(lineitem, orders.o_orderkey == lineitem.l_orderkey)
[lineitem, orders])
items.o_orderpriority.value_counts() | docs/source/notebooks/tutorial/8-More-Analytics-Helpers.ipynb | deepfield/ibis | apache-2.0 |
This can be customized, of course: | freq = (items.group_by(items.o_orderpriority)
.aggregate([items.count().name('nrows'),
items.l_extendedprice.sum().name('total $')]))
freq | docs/source/notebooks/tutorial/8-More-Analytics-Helpers.ipynb | deepfield/ibis | apache-2.0 |
Binning and histograms
Numeric array expressions (columns with numeric type and other array expressions) have bucket and histogram methods which produce different kinds of binning. These produce category values (the computed bins) that can be used in grouping and other analytics.
Let's have a look at a few examples
I'l... | items.l_extendedprice.summary() | docs/source/notebooks/tutorial/8-More-Analytics-Helpers.ipynb | deepfield/ibis | apache-2.0 |
Alright then, now suppose we want to split the item prices up into some buckets of our choosing: | buckets = [0, 5000, 10000, 50000, 100000] | docs/source/notebooks/tutorial/8-More-Analytics-Helpers.ipynb | deepfield/ibis | apache-2.0 |
The bucket function creates a bucketed category from the prices: | bucketed = items.l_extendedprice.bucket(buckets).name('bucket') | docs/source/notebooks/tutorial/8-More-Analytics-Helpers.ipynb | deepfield/ibis | apache-2.0 |
The buckets we wrote down define 4 buckets numbered 0 through 3. The NaN is a pandas NULL value (since that's how pandas represents nulls in numeric arrays), so don't worry too much about that. Since the bucketing ends at 100000, we see there are 4122 values that are over 100000. These can be included in the bucketing ... | bucketed = (items.l_extendedprice
.bucket(buckets, include_over=True)
.name('bucket'))
bucketed.value_counts() | docs/source/notebooks/tutorial/8-More-Analytics-Helpers.ipynb | deepfield/ibis | apache-2.0 |
Category values can either have a known or unknown cardinality. In this case, there's either 4 or 5 buckets based on how we used the bucket function.
Labels can be assigned to the buckets at any time using the label function: | bucket_counts = bucketed.value_counts()
labeled_bucket = (bucket_counts.bucket
.label(['0 to 5000', '5000 to 10000', '10000 to 50000',
'50000 to 100000', 'Over 100000'])
.name('bucket_name'))
expr = (bucket_counts[labeled_bucket, bucket_counts]
.so... | docs/source/notebooks/tutorial/8-More-Analytics-Helpers.ipynb | deepfield/ibis | apache-2.0 |
Nice, huh?
histogram is a linear (fixed size bin) equivalent: | t = con.table('functional_alltypes')
d = t.double_col
tier = d.histogram(10).name('hist_bin')
expr = (t.group_by(tier)
.aggregate([d.min(), d.max(), t.count()])
.sort_by('hist_bin'))
expr | docs/source/notebooks/tutorial/8-More-Analytics-Helpers.ipynb | deepfield/ibis | apache-2.0 |
Filtering in aggregations
Suppose that you want to compute an aggregation with a subset of the data for only one of the metrics / aggregates in question, and the complete data set with the other aggregates. Most aggregation functions are thus equipped with a where argument. Let me show it to you in action: | t = con.table('functional_alltypes')
d = t.double_col
s = t.string_col
cond = s.isin(['3', '5', '7'])
metrics = [t.count().name('# rows total'),
cond.sum().name('# selected'),
d.sum().name('total'),
d.sum(where=cond).name('selected total')]
color = (t.float_col
.between(3,... | docs/source/notebooks/tutorial/8-More-Analytics-Helpers.ipynb | deepfield/ibis | apache-2.0 |
Visualization for a single continuous variable | plt.hist(df["mpg"], bins = 30)
plt.title("Histogram plot of mpg")
plt.xlabel("mpg")
plt.ylabel("Frequency")
plt.boxplot(df["mpg"])
plt.title("Boxplot of mpg\n ")
plt.ylabel("mpg")
#plt.figure(figsize = (10, 6))
plt.subplot(2, 1, 1)
n, bins, patches = plt.hist(df["mpg"], bins = 50, normed = True)
plt.title("Histogram ... | Scikit - 02 Visualization.ipynb | abulbasar/machine-learning | apache-2.0 |
Visualization for single categorical variable - frequency plot | counts = df["year"].value_counts().sort_index()
plt.figure(figsize = (10, 4))
plt.bar(range(len(counts)), counts, align = "center")
plt.xticks(range(len(counts)), counts.index)
plt.xlabel("Year")
plt.ylabel("Frequency")
plt.title("Frequency distribution by year") | Scikit - 02 Visualization.ipynb | abulbasar/machine-learning | apache-2.0 |
Bar plot using matplotlib visualization | plt.figure(figsize = (10, 4))
df.year.value_counts().sort_index().plot.bar() | Scikit - 02 Visualization.ipynb | abulbasar/machine-learning | apache-2.0 |
Association plot between two continuous variables
Continuous vs continuous | corr = np.corrcoef(df["weight"], df["mpg"])[0, 1]
plt.scatter(df["weight"], df["mpg"])
plt.xlabel("Weight")
plt.ylabel("Mpg")
plt.title("Mpg vs Weight, correlation: %.2f" % corr) | Scikit - 02 Visualization.ipynb | abulbasar/machine-learning | apache-2.0 |
Scatter plot using pandas dataframe plot function | df.plot.scatter(x= "weight", y = "mpg")
plt.title("Mpg vs Weight, correlation: %.2f" % corr) | Scikit - 02 Visualization.ipynb | abulbasar/machine-learning | apache-2.0 |
Continuous vs Categorical | mpg_by_year = df.groupby("year")["mpg"].agg([np.median, np.std])
mpg_by_year.head()
mpg_by_year["median"].plot.bar(yerr = mpg_by_year["std"], ecolor = "red")
plt.title("MPG by year")
plt.xlabel("year")
plt.ylabel("MPG") | Scikit - 02 Visualization.ipynb | abulbasar/machine-learning | apache-2.0 |
Show the boxplot of MPG by year | plt.figure(figsize=(10, 5))
sns.boxplot("year", "mpg", data = df) | Scikit - 02 Visualization.ipynb | abulbasar/machine-learning | apache-2.0 |
Association plot between 2 categorical variables | plt.figure(figsize=(10, 8))
sns.heatmap(df.corr(), cmap=sns.color_palette("RdBu", 10), annot=True)
plt.figure(figsize=(10, 8))
aggr = df.groupby(["year", "cylinders"])["mpg"].agg(np.mean).unstack()
sns.heatmap(aggr, cmap=sns.color_palette("Blues", n_colors= 10), annot=True) | Scikit - 02 Visualization.ipynb | abulbasar/machine-learning | apache-2.0 |
Classificaition plot | iris = pd.read_csv("https://raw.githubusercontent.com/abulbasar/data/master/iris.csv")
iris.head()
fig, ax = plt.subplots()
x1, x2 = "SepalLengthCm", "PetalLengthCm"
cmap = sns.color_palette("husl", n_colors=3)
for i, c in enumerate(iris.Species.unique()):
iris[iris.Species == c].plot.scatter(x1, x2, color = cmap[... | Scikit - 02 Visualization.ipynb | abulbasar/machine-learning | apache-2.0 |
QQ Plot for normality test | import scipy.stats as stats
p = stats.probplot(df["mpg"], dist="norm", plot=plt) | Scikit - 02 Visualization.ipynb | abulbasar/machine-learning | apache-2.0 |
Loading the Input Data
Next, we must load the data. There are some example datasets that come with Spark by default. Example data related to machine learning in particular is located in the $SPARK_HOME/data/mllib directory. For this part, we will be working with the $SPARK_HOME/data/mllib/als/test.data file. This is a ... | data = sc.textFile("/Users/george/Panzer/Softwares/spark-1.5.2-bin-hadoop2.6/data/mllib/als/test.data") | tutorial_spark.ipynb | ADBI-george2/Spark-Tutorial | apache-2.0 |
Even though, we have the environment $SPARK_HOME defined, but it can't be used here. You must specify the full path, or the relative path based off where you initiated IPython.
The textFile command will create an RDD where each element is a line of the input file. In the below cell, write some code to (1) print the num... | rows = data.collect()
x = len(rows)
y = rows[4]
print("There are %d elements. The fifth element is : %s"%(x,y)) | tutorial_spark.ipynb | ADBI-george2/Spark-Tutorial | apache-2.0 |
Transforming the Input Data
This data isn't in a great format, since each element is in the RDD is currently a string. However, we will assume that the first column of the string represents a user ID, the second column represents a product ID, and the third column represents a user-specified rating of that product.
In ... | def parser(line):
splits = line.strip().split(",")
return (int(splits[0]), int(splits[1]), float(splits[2]))
ratings = data.map(parser).map(lambda l: Rating(*l))
ratings.collect() | tutorial_spark.ipynb | ADBI-george2/Spark-Tutorial | apache-2.0 |
Your output should look like the following:
[Rating(user=1, product=1, rating=5.0),
Rating(user=1, product=2, rating=1.0),
Rating(user=1, product=3, rating=5.0),
Rating(user=1, product=4, rating=1.0),
Rating(user=2, product=1, rating=5.0),
Rating(user=2, product=2, rating=1.0),
Rating(user=2, product=3, rating=5.... | rank = 10
numIterations = 10
model = ALS.train(ratings, rank, numIterations)
# Let's define some test data
testdata = ratings.map(lambda p: (p[0], p[1]))
# Running the model on all possible user->product predictions
predictions = model.predictAll(testdata)
predictions.collect() | tutorial_spark.ipynb | ADBI-george2/Spark-Tutorial | apache-2.0 |
Transforming the Model Output
This result is not really in a nice format. Write some code that will transform the RDD so that each element is a user ID and a dictionary of product->rating pairs. Note that for the a Ratings object (which is what the elements of the RDD are), you can access the different fields by via th... | def format_ratings(lst):
ratings = {}
for rating in lst:
ratings[rating.product] = rating.rating
return ratings
userPredictions = predictions.groupBy(lambda r: r.user).mapValues(format_ratings)
userPredictions.collect() | tutorial_spark.ipynb | ADBI-george2/Spark-Tutorial | apache-2.0 |
Evaluating the Model
Now, lets calculate the mean squared error. | userPredictions = predictions.map(lambda r: ((r[0],r[1]), r[2]))
ratesAndPreds = ratings.map(lambda r: ((r[0],r[1]), r[2])).join(predictions)
MSE = ratesAndPreds.map(lambda r: (r[1][0] - r[1][1])**2).mean()
print("Mean Squared Error = " + str(MSE)) | tutorial_spark.ipynb | ADBI-george2/Spark-Tutorial | apache-2.0 |
Running Sampling
The next cell is the first piece of code that differs substantially from other work flows. In it, we create the model and likelihood as normal, and then register priors to each of the parameters of the model. Note that we directly can register priors to transformed parameters (e.g., "lengthscale") rath... | # this is for running the notebook in our testing framework
import os
smoke_test = ('CI' in os.environ)
num_samples = 2 if smoke_test else 100
warmup_steps = 2 if smoke_test else 200
from gpytorch.priors import LogNormalPrior, NormalPrior, UniformPrior
# Use a positive constraint instead of usual GreaterThan(1e-4) so... | examples/01_Exact_GPs/GP_Regression_Fully_Bayesian.ipynb | jrg365/gpytorch | mit |
Loading Samples
In the next cell, we load the samples generated by NUTS in to the model. This converts model from a single GP to a batch of num_samples GPs, in this case 100. | model.pyro_load_from_samples(mcmc_run.get_samples())
model.eval()
test_x = torch.linspace(0, 1, 101).unsqueeze(-1)
test_y = torch.sin(test_x * (2 * math.pi))
expanded_test_x = test_x.unsqueeze(0).repeat(num_samples, 1, 1)
output = model(expanded_test_x) | examples/01_Exact_GPs/GP_Regression_Fully_Bayesian.ipynb | jrg365/gpytorch | mit |
Plot Mean Functions
In the next cell, we plot the first 25 mean functions on the samep lot. This particular example has a fairly large amount of data for only 1 dimension, so the hyperparameter posterior is quite tight and there is relatively little variance. | with torch.no_grad():
# Initialize plot
f, ax = plt.subplots(1, 1, figsize=(4, 3))
# Plot training data as black stars
ax.plot(train_x.numpy(), train_y.numpy(), 'k*', zorder=10)
for i in range(min(num_samples, 25)):
# Plot predictive means as blue line
ax.plot(test_x.numpy(... | examples/01_Exact_GPs/GP_Regression_Fully_Bayesian.ipynb | jrg365/gpytorch | mit |
Simulate Loading Model from Disk
Loading a fully Bayesian model from disk is slightly different from loading a standard model because the process of sampling changes the shapes of the model's parameters. To account for this, you'll need to call load_strict_shapes(False) on the model before loading the state dict. In th... | state_dict = model.state_dict()
model = ExactGPModel(train_x, train_y, likelihood)
# Load parameters without standard shape checking.
model.load_strict_shapes(False)
model.load_state_dict(state_dict) | examples/01_Exact_GPs/GP_Regression_Fully_Bayesian.ipynb | jrg365/gpytorch | mit |
We need to download parameter values for the pretrained network | !wget https://s3.amazonaws.com/lasagne/recipes/pretrained/imagenet/blvc_googlenet.pkl | examples/imagecaption/COCO Preprocessing.ipynb | ebenolson/Recipes | mit |
The Neverending Search for Periodicity: Techniques Beyond Lomb-Scargle
Version 0.1
By AA Miller 28 Apr 2018
In this lecture we will examine alternative methods to search for periodic signals in astronomical time series. The problems will provide a particular focus on a relatively new technique, which is to model the p... | ncores = # adjust to number of CPUs on your machine
np.random.seed(23) | Sessions/Session06/Day1/GaussianProcessPeriodicity.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Problem 1b
Create a function gen_periodic_data that returns
$$y = C + A\cos\left(\frac{2\pi x}{P}\right) + \sigma_y$$
where $C$, $A$, and $P$ are constants, $x$ is input data and $\sigma_y$ represents Gaussian noise.
Hint - this should only require a minor adjustment to your function from lecture 1. | def gen_periodic_data( # complete
y = # complete
return y | Sessions/Session06/Day1/GaussianProcessPeriodicity.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Problem 1c
Later, we will be using MCMC. Execute the following cell which will plot the chains from emcee to follow the MCMC walkers. | def plot_chains(sampler, nburn, paramsNames):
Nparams = len(paramsNames) # + 1
fig, ax = plt.subplots(Nparams,1, figsize = (8,2*Nparams), sharex = True)
fig.subplots_adjust(hspace = 0)
ax[0].set_title('Chains')
xplot = range(len(sampler.chain[0,:,0]))
for i,p in enumerate(paramsNames):
... | Sessions/Session06/Day1/GaussianProcessPeriodicity.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Problem 1d
Using gen_periodic_data generate 250 observations taken at random times between 0 and 10, with $C = 10$, $A = 2$, $P = 0.4$, and variance of the noise = 0.1. Create an uncertainty array dy with the same length as y and each value equal to $\sqrt{0.1}$.
Plot the resulting data over the exact (noise-free) sig... | x = # complete
y = # complete
dy = # complete
# complete
fig, ax = plt.subplots()
ax.errorbar( # complete
ax.plot( # complete
# complete
# complete
fig.tight_layout() | Sessions/Session06/Day1/GaussianProcessPeriodicity.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Problem 2) Maximum-Likelihood Optimization
A common approach$^\dagger$ in the literature for problems where there is good reason to place a strong prior on the signal (i.e. to only try and fit a single model) is maximum likelihood optimization [this is sometimes also called $\chi^2$ minimization].
$^\dagger$The fact th... | def correct_model( # complete
# complete
return # complete | Sessions/Session06/Day1/GaussianProcessPeriodicity.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
For these data the log likelihood of the data can be written as:
$$\ln \mathcal{L} = -\frac{1}{2} \sum \left(\frac{y - f(t)}{\sigma_y}\right)^2$$
Ultimately, it is easier to minimize the negative log likelihood, so we will do that.
Problem 2b
Write a function, lnlike1, that returns the log likelihood for the data giv... | def lnlike1( # complete
return # complete
def nll( # complete
return # complete | Sessions/Session06/Day1/GaussianProcessPeriodicity.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Problem 2c
Use the minimize function from scipy.optimize to determine maximum likelihood estimates for the model parameters for the data simulated in problem 1d. What is the best fit period?
The optimization routine requires an initial guess for the model parameters, use 10 for the offset, 1 for the amplitude of variat... | initial_theta = # complete
res = minimize( # complete
print("The maximum likelihood estimate for the period is: {:.5f}".format( # complete | Sessions/Session06/Day1/GaussianProcessPeriodicity.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Problem 2d
Plot the input model, the noisy data, and the maximum likelihood model.
How does the model fit look? | fig, ax = plt.subplots()
ax.errorbar( # complete
ax.plot( # complete
ax.plot( # complete
ax.set_xlabel('x')
ax.set_ylabel('y')
fig.tight_layout() | Sessions/Session06/Day1/GaussianProcessPeriodicity.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Problem 2e
Repeat the maximum likelihood optimization, but this time use an initial guess of 10 for the offset, 1 for the amplitude of variations, and 0.393 for the period. | initial_theta = # complete
res = minimize( # complete
print("The ML estimate for a, b, c is: {:.5f}, {:.5f}, {:.5f}".format( # complete | Sessions/Session06/Day1/GaussianProcessPeriodicity.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Given the lecture order this is a little late, but we have now identified the fundamental challenge in identifying periodic signals in astrophysical observations:
periodic models are highly non-linear!
This can easily be seen in the LS periodograms from the previous lecture: period estimates essentially need to be per... | def lnprior1( # complete
a, b, c = # complete
if # complete
return 0.0
return -np.inf | Sessions/Session06/Day1/GaussianProcessPeriodicity.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Problem 3b
Write a function lnprob1 to calculate the log of the posterior probability. This function should take $\theta$ and x, y, dy as inputs. | def lnprob1( # complete
lp = lnprior1(theta)
if np.isfinite(lp):
return # complete
return -np.inf | Sessions/Session06/Day1/GaussianProcessPeriodicity.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Problem 3c
Initialize the walkers for emcee, which we will use to draw samples from the posterior. Like before, we need to include an initial guess (the parameters of which don't matter much beyond the period). Start with a guess of 0.6 for the period.
As a quick reminder, emcee is a pure python implementation of Goodm... | guess = [10, 1, 0.6]
ndim = len(guess)
nwalkers = 100
p0 = [np.array(guess) + 1e-8 * np.random.randn(ndim)
for i in range(nwalkers)]
sampler = emcee.EnsembleSampler(nwalkers, ndim, lnprob1, args=(x, y, dy), threads = ncores) | Sessions/Session06/Day1/GaussianProcessPeriodicity.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Problem 3d
Run the walkers through 1000 steps.
Hint - The run_mcmc method on the sampler object may be useful. | sampler.run_mcmc( # complete | Sessions/Session06/Day1/GaussianProcessPeriodicity.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Problem 3e
Use the previous created plot_chains helper funtion to plot the chains from the MCMC sampling. Note - you may need to adjust nburn after examining the chains.
Have your chains converged? Will extending the chains improve this? | params_names = # complete
nburn = # complete
plot_chains( # complete | Sessions/Session06/Day1/GaussianProcessPeriodicity.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Problem 3f
Make a corner plot (use corner) to examine the post burn-in samples from the MCMC chains. | samples = sampler.chain[:, nburn:, :].reshape((-1, ndim))
fig = # complete | Sessions/Session06/Day1/GaussianProcessPeriodicity.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
As you can see - force feeding this problem into a Bayesian framework does not automatically generate more reasonable answers. While some of the chains appear to have identified periods close to the correct period most of them are suck in local minima.
There are sampling techniques designed to handle multimodal poster... | def model2( # complete
# complete
return # complete | Sessions/Session06/Day1/GaussianProcessPeriodicity.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
To model the GP in this problem we will use the george package (first introduced during session 4) written by Dan Foreman-Mackey. george is a fast and flexible tool for GP regression in python. It includes several built-in kernel functions, which we will take advantage of.
Problem 4b
Write a function lnlike2 to calcula... | def lnlike2(theta, t, y, yerr):
lnper, lna = theta[:2]
gp = george.GP(np.exp(lna) * kernels.CosineKernel(lnper))
gp.compute(t, yerr)
return gp.lnlikelihood(y - model2(theta, t), quiet=True) | Sessions/Session06/Day1/GaussianProcessPeriodicity.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Problem 4c
Write a function lnprior2 to calculte $\ln P(\theta)$, the log prior for the model parameters. Use a wide flat prior for the parameters.
Note - a flat prior in log space is not flat in the parameters. | def lnprior2( # complete
# complete
# complete
# complete
# complete
# complete
# complete | Sessions/Session06/Day1/GaussianProcessPeriodicity.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Problem 4d
Write a function lnprob2 to calculate the log posterior given the model parameters and data. | def lnprob2(# complete
# complete
# complete
# complete
# complete
# complete
# complete | Sessions/Session06/Day1/GaussianProcessPeriodicity.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Problem 4e
Intialize 100 walkers in an emcee.EnsembleSampler variable called sampler. For you initial guess at the parameter values set $\ln a = 1$, $\ln P = 1$, and $b = 8$.
Note - this is very similar to what you did previously. | initial = # complete
ndim = len(initial)
p0 = [np.array(initial) + 1e-4 * np.random.randn(ndim)
for i in range(nwalkers)]
sampler = emcee.EnsembleSampler( # complete | Sessions/Session06/Day1/GaussianProcessPeriodicity.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Problem 4f
Run the chains for 200 steps.
Hint - you'll notice these are shorter chains than we previously used. That is because the computational time is longer, as will be the case for this and all the remaining problems. | p0, _, _ = sampler.run_mcmc( # complete | Sessions/Session06/Day1/GaussianProcessPeriodicity.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Problem 4g
Plot the chains from the MCMC. | params_names = ['ln(P)', 'ln(a)', 'b']
nburn = # complete
plot_chains( # complete | Sessions/Session06/Day1/GaussianProcessPeriodicity.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
It should be clear that the chains have not, in this case, converged. This will be true even if you were to continue to run them for a very long time.
Nevertheless, if we treat this entire run as a burn in, we can actually extract some useful information from this initial run. In particular, we will look at the poster... | chain_lnp_end = sampler.chain[:,-1,0]
chain_lnprob_end = sampler.lnprobability[:,-1]
fig, ax = plt.subplots()
ax.scatter( # complete
# complete
# complete
fig.tight_layout() | Sessions/Session06/Day1/GaussianProcessPeriodicity.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Problem 4i
Reinitialize the walkers in a ball around the maximum log posterior value from the walkers in the previous burn in. Then run the MCMC sampler for 200 steps.
Hint - you'll want to run sampler.reset() prior to the running the MCMC, but after selecting the new starting point for the walkers. | p = # complete
sampler.reset()
p0 = # complete
p0, _, _ = sampler.run_mcmc( # complete | Sessions/Session06/Day1/GaussianProcessPeriodicity.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Problem 4j
Plot the chains. Have they converged? | paramsNames = ['ln(P)', 'ln(a)', 'b']
nburn = # complete
plot_chains( # complete | Sessions/Session06/Day1/GaussianProcessPeriodicity.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Problem 4k
Make a corner plot of the samples. Does the marginalized distribution on $P$ make sense? | fig = | Sessions/Session06/Day1/GaussianProcessPeriodicity.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
If you run the cell below, you will see random samples from the posterior overplotted on the data. Do the posterior samples seem reasonable in this case? | fig, ax = plt.subplots()
ax.errorbar(x, y, dy, fmt='o')
ax.set_xlabel('x')
ax.set_ylabel('y')
for s in samples[np.random.randint(len(samples), size=5)]:
# Set up the GP for this sample.
lnper, lna = s[:2]
gp = george.GP(np.exp(lna) * kernels.CosineKernel(lnper))
gp.compute(x, dy)
# Compute the pred... | Sessions/Session06/Day1/GaussianProcessPeriodicity.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Problem 4l
What is the marginalized best period estimate, including uncertainties? | # complete
print('ln(P) = {:.6f} +{:.6f} -{:.6f}'.format( # complete
print('True period = 0.4, GP Period = {:.4f}'.format( # complete | Sessions/Session06/Day1/GaussianProcessPeriodicity.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
In this way - it is possible to use GPs + MCMC to determine the period in noisy irregular data. Furthermore, unlike with LS, we actually have a direct estimate on the uncertainty for that period.
As I previously alluded to, however, the solution does depend on how we initialize the walkers. Because this is simulated d... | # complete
# complete
# complete
def lnprob3( # complete
# complete
# complete | Sessions/Session06/Day1/GaussianProcessPeriodicity.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Problem 5b
Initialize 100 walkers around a reasonable starting point. Be sure that $\ln P = 0$ in this initialization.
Run the MCMC for 200 steps.
Hint - it may be helpful to run this second step in a separate cell. | # complete
# complete
# complete
sampler = emcee.EnsembleSampler( # complete
p0, _, _ = sampler.run_mcmc( # complete | Sessions/Session06/Day1/GaussianProcessPeriodicity.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Problem 5c
Plot the chains from the MCMC. Did the chains converge? | paramsNames = ['ln(P)', 'ln(a)', 'b', '$ln(\gamma)$']
nburn = # complete
plot_chains( # complete | Sessions/Session06/Day1/GaussianProcessPeriodicity.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Problem 5d
Plot the final $\ln P$ vs. log posterior for each of the walkers. Do you notice anything interesting?
Hint - recall that you are plotting the log posterior, and not the posterior. | # complete
# complete
# complete
# complete
# complete
# complete | Sessions/Session06/Day1/GaussianProcessPeriodicity.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Problem 5e
Re-initialize the walkers around the chain with the maximum log posterior value.
Run the MCMC for 500 steps. | p = # complete
sampler.reset()
# complete
sampler.run_mcmc( # complete | Sessions/Session06/Day1/GaussianProcessPeriodicity.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Problem 5f
Plot the chains for the MCMC.
Hint - you may need to adjust the length of the burn in. | paramsNames = ['ln(P)', 'ln(a)', 'b', '$ln(\gamma)$']
nburn = # complete
plot_chains( # complete | Sessions/Session06/Day1/GaussianProcessPeriodicity.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Problem 5g
Make a corner plot for the samples.
Is the marginalized estimate for the period reasonable? | # complete
fig = # complete | Sessions/Session06/Day1/GaussianProcessPeriodicity.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Problem 6) GPs + MCMC for actual astronomical data
We will now apply this model to the same light curve that we studied in the LS lecture.
In this case we do not know the actual period (that's only sorta true), so we will have to be even more careful about initializing the walkers and performing burn in than we were pr... | # complete | Sessions/Session06/Day1/GaussianProcessPeriodicity.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Problem 6b
Adjust the prior from problem 5 to be appropriate for this data set. | def lnprior3( # complete
# complete
# complete
# complete
# complete
# complete
# complete
# complete | Sessions/Session06/Day1/GaussianProcessPeriodicity.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Because we have no idea where to initialize our walkers in this case, we are going to use an ad hoc common sense + brute force approach.
Problem 6c
Run LombScarge on the data and determine the top three peaks in the periodogram. Set nterms = 2, and the maximum frequency to 5 (this is arbitrary but sufficient in this c... | from astropy.stats import LombScargle
frequency, power = # complete
print('Top LS period is {}'.format(# complete
print( # complete | Sessions/Session06/Day1/GaussianProcessPeriodicity.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Problem 6d
Initialize one third of your 100 walkers around each of the periods identified in the previous problem (note - the total number of walkers must be an even number, so use 34 walkers around one of the top 3 frequency peaks).
Run the MCMC for 500 steps following this initialization. | initial1 = # complete
# complete
# complete
initial2 = # complete
# complete
# complete
initial3 = # complete
# complete
# complete
# complete
sampler = emcee.EnsembleSampler( # complete
p0, _, _ = sampler.run_mcmc( # complete | Sessions/Session06/Day1/GaussianProcessPeriodicity.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Problem 6e
Plot the chains. | paramsNames = ['ln(P)', 'ln(a)', 'b', '$ln(\gamma)$']
nburn = # complete
plot_chains( # complete | Sessions/Session06/Day1/GaussianProcessPeriodicity.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Problem 6f
Plot $\ln P$ vs. log posterior. | # complete
# complete
# complete
# complete
# complete
# complete | Sessions/Session06/Day1/GaussianProcessPeriodicity.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Problem 6g
Reinitialize the walkers around the previous walker with the maximum posterior value.
Run the MCMC for 500 steps. Plot the chains. Have they converged? | # complete
sampler.reset()
# complete
# complete
sampler.run_mcmc( # complete
paramsNames = ['ln(P)', 'ln(a)', 'b', '$ln(\gamma)$']
nburn = # complete
plot_chains( # complete | Sessions/Session06/Day1/GaussianProcessPeriodicity.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Problem 6h
Make a corner plot of the samples. What is the marginalized estimate for the period of this source?
How does this estimate compare to LS? | # complete
fig = corner.corner( # complete
# complete
print('ln(P) = {:.6f} +{:.6f} -{:.6f}'.format( # complete
print('GP Period = {:.6f}'.format( # complete | Sessions/Session06/Day1/GaussianProcessPeriodicity.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
The cell below shows marginalized samples overplotted on the actual data. How well does the model perform? | fig, ax = plt.subplots()
ax.errorbar(lc['hjd'], lc['mag'], lc['mag_unc'], fmt='o')
ax.set_xlabel('HJD (d)')
ax.set_ylabel('mag')
hjd_grid = np.linspace(2800, 3000,3000)
for s in samples[np.random.randint(len(samples), size=5)]:
# Set up the GP for this sample.
lnper, lna, b, lngamma = s
gp = george.GP(np.... | Sessions/Session06/Day1/GaussianProcessPeriodicity.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Data pre-processing
Now we need to do data cleaning and preprocessing on the raw data. Note that this part could vary for different dataset.
For the machine_usage data, the pre-processing contains 2 parts:
1. Convert the time step in seconds to timestamp starting from 2018-01-01
2. Generate a built-in TSDataset to res... | df_1932["time_step"] = pd.to_datetime(df_1932["time_step"], unit='s', origin=pd.Timestamp('2018-01-01'))
from bigdl.chronos.data import TSDataset
tsdata = TSDataset.from_pandas(df_1932, dt_col="time_step", target_col="cpu_usage")
df = tsdata.resample(interval='1min', merge_mode="mean")\
.impute(mode="last"... | python/chronos/use-case/AIOps/AIOps_anomaly_detect_unsupervised.ipynb | intel-analytics/BigDL | apache-2.0 |
Anomaly Detection by DBScan Detector
DBScanDetector uses DBSCAN clustering for anomaly detection. The DBSCAN algorithm tries to cluster the points and label the points that do not belong to any clusters as -1. It thus detects outliers detection in the input time series. DBScanDetector assigns anomaly score 1 to anomaly... | from bigdl.chronos.detector.anomaly import DBScanDetector
ad = DBScanDetector(eps=0.1, min_samples=6)
ad.fit(df['cpu_usage'].to_numpy())
anomaly_scores = ad.score()
anomaly_indexes = ad.anomaly_indexes()
print("The anomaly scores are:", anomaly_scores)
print("The anomaly indexes are:", anomaly_indexes) | python/chronos/use-case/AIOps/AIOps_anomaly_detect_unsupervised.ipynb | intel-analytics/BigDL | apache-2.0 |
Anomaly Detection by AutoEncoder Detector
AEDetector is unsupervised anomaly detector. It builds an autoencoder network, try to fit the model to the input data, and calcuates the reconstruction error. The samples with larger reconstruction errors are more likely the anomalies. | from bigdl.chronos.detector.anomaly import AEDetector
ad = AEDetector(roll_len=10, ratio=0.05)
ad.fit(df['cpu_usage'].to_numpy())
anomaly_scores = ad.score()
anomaly_indexes = ad.anomaly_indexes()
print("The anomaly scores are:", anomaly_scores)
print("The anomaly indexes are:", anomaly_indexes) | python/chronos/use-case/AIOps/AIOps_anomaly_detect_unsupervised.ipynb | intel-analytics/BigDL | apache-2.0 |
Anomaly Detection by Threshold Detector
ThresholdDetector is a simple anomaly detector that detectes anomalies based on threshold. The target value for anomaly testing can be either 1) the sample value itself or 2) the difference between the forecasted value and the actual value. In this notebook we demostrate the firs... | from bigdl.chronos.detector.anomaly import ThresholdDetector
thd=ThresholdDetector()
thd.set_params(threshold=(20, 80))
thd.fit(df['cpu_usage'].to_numpy())
anomaly_scores = thd.score()
anomaly_indexes = thd.anomaly_indexes()
print("The anomaly scores are:", anomaly_scores)
print("The anomaly indexes are:", anomaly_i... | python/chronos/use-case/AIOps/AIOps_anomaly_detect_unsupervised.ipynb | intel-analytics/BigDL | apache-2.0 |
Palettable API | from palettable.colorbrewer.qualitative import Set1_9
Set1_9.name
Set1_9.type
Set1_9.number
Set1_9.colors
Set1_9.hex_colors
Set1_9.mpl_colors
Set1_9.mpl_colormap
# requires ipythonblocks
Set1_9.show_as_blocks()
Set1_9.show_continuous_image()
Set1_9.show_discrete_image() | demo/Palettable Demo.ipynb | mikecharles/palettable | mit |
Setting the matplotlib Color Cycle
Adapted from the example at http://matplotlib.org/examples/color/color_cycle_demo.html.
Use the .mpl_colors attribute to change the color cycle used by matplotlib
when colors for plots are not specified. | from palettable.wesanderson import Aquatic1_5, Moonrise4_5
x = np.linspace(0, 2 * np.pi)
offsets = np.linspace(0, 2*np.pi, 4, endpoint=False)
# Create array with shifted-sine curve along each column
yy = np.transpose([np.sin(x + phi) for phi in offsets])
plt.rc('lines', linewidth=4)
plt.rc('axes', color_cycle=Aquatic... | demo/Palettable Demo.ipynb | mikecharles/palettable | mit |
Using a Continuous Palette
Adapted from http://matplotlib.org/examples/pylab_examples/hist2d_log_demo.html.
Use the .mpl_colormap attribute any place you need a matplotlib colormap. | from palettable.colorbrewer.sequential import YlGnBu_9
from matplotlib.colors import LogNorm
#normal distribution center at x=0 and y=5
x = np.random.randn(100000)
y = np.random.randn(100000)+5
plt.hist2d(x, y, bins=40, norm=LogNorm(), cmap=YlGnBu_9.mpl_colormap)
plt.colorbar() | demo/Palettable Demo.ipynb | mikecharles/palettable | mit |
1. Read structure | st = smart_structure_read('Cu/POSCARCU.vasp') # read required structure | tutorials/surfaces.ipynb | dimonaks/siman | gpl-2.0 |
2. Choose new vectors
The initial structure is FCC lattice in conventianal setting i.e. cubic unit cell.
As a first step we create orthogonal supercell with {111}cub surface on one side.
Below the directions orthogonal to {111} are shown.
We will choose [-1-1-1], [01-1] and [2-1-1]. | Image(filename='figs/Thompson-tetrahedron-notation-for-FCC-slip-systems.png') | tutorials/surfaces.ipynb | dimonaks/siman | gpl-2.0 |
3. Build supercell with new vectors | # create supercell using chosen directions, the *mul* allows to choose one half of the third vector
sc = create_supercell(st, [ [-1,-1,-1], [0,1,-1], [2,-1,-1]], mul = (1,1,0.5)) | tutorials/surfaces.ipynb | dimonaks/siman | gpl-2.0 |
4. Build slab
Now we need to create vacuum and rotate the cell. This can be done using create_surface2 function | # here we choose [100] normal in supercell, which is equivalent to [111]cub
# combinations of *min_slab_size* and *cut_thickness* (small cut of slab from one side) allows create symmetrical slab
st_suf = create_surface2(sc, [1, 0, 0], min_vacuum_size = 10,
min_slab_size = 16, cut_thickness = 3, oxidation = {'Cu':'... | tutorials/surfaces.ipynb | dimonaks/siman | gpl-2.0 |
5. Scale slab
Above the slab with minimum surface area was obtained. If you need larger surface you can use supercell() function for which you need to provide required sizes in Angstrems | st_sufsc112 = supercell(st_suf, [10,10,32]) # make 2x2 slab
st_sufsc112.write_poscar() # save file as POSCAR for VASP | tutorials/surfaces.ipynb | dimonaks/siman | gpl-2.0 |
Implement Preprocessing Function
Text to Word Ids
As you did with other RNNs, you must turn the text into a number so the computer can understand it. In the function text_to_ids(), you'll turn source_text and target_text from words to ids. However, you need to add the <EOS> word id at the end of target_text. Th... | def text_to_ids(source_text, target_text, source_vocab_to_int, target_vocab_to_int):
"""
Convert source and target text to proper word ids
:param source_text: String that contains all the source text.
:param target_text: String that contains all the target text.
:param source_vocab_to_int: Dictionar... | language-translation/dlnd_language_translation.ipynb | rishizek/deep-learning | mit |
Build the Neural Network
You'll build the components necessary to build a Sequence-to-Sequence model by implementing the following functions below:
- model_inputs
- process_decoder_input
- encoding_layer
- decoding_layer_train
- decoding_layer_infer
- decoding_layer
- seq2seq_model
Input
Implement the model_inputs() fu... | def model_inputs():
"""
Create TF Placeholders for input, targets, learning rate, and lengths of source and target sequences.
:return: Tuple (input, targets, learning rate, keep probability, target sequence length,
max target sequence length, source sequence length)
"""
# TODO: Implement Functio... | language-translation/dlnd_language_translation.ipynb | rishizek/deep-learning | mit |
Encoding
Implement encoding_layer() to create a Encoder RNN layer:
* Embed the encoder input using tf.contrib.layers.embed_sequence
* Construct a stacked tf.contrib.rnn.LSTMCell wrapped in a tf.contrib.rnn.DropoutWrapper
* Pass cell and embedded input to tf.nn.dynamic_rnn() | from imp import reload
reload(tests)
def encoding_layer(rnn_inputs, rnn_size, num_layers, keep_prob,
source_sequence_length, source_vocab_size,
encoding_embedding_size):
"""
Create encoding layer
:param rnn_inputs: Inputs for the RNN
:param rnn_size: RNN Size
... | language-translation/dlnd_language_translation.ipynb | rishizek/deep-learning | mit |
Decoding - Training
Create a training decoding layer:
* Create a tf.contrib.seq2seq.TrainingHelper
* Create a tf.contrib.seq2seq.BasicDecoder
* Obtain the decoder outputs from tf.contrib.seq2seq.dynamic_decode | def decoding_layer_train(encoder_state, dec_cell, dec_embed_input,
target_sequence_length, max_summary_length,
output_layer, keep_prob):
"""
Create a decoding layer for training
:param encoder_state: Encoder State
:param dec_cell: Decoder RNN Cell
... | language-translation/dlnd_language_translation.ipynb | rishizek/deep-learning | mit |
Decoding - Inference
Create inference decoder:
* Create a tf.contrib.seq2seq.GreedyEmbeddingHelper
* Create a tf.contrib.seq2seq.BasicDecoder
* Obtain the decoder outputs from tf.contrib.seq2seq.dynamic_decode | def decoding_layer_infer(encoder_state, dec_cell, dec_embeddings, start_of_sequence_id,
end_of_sequence_id, max_target_sequence_length,
vocab_size, output_layer, batch_size, keep_prob):
"""
Create a decoding layer for inference
:param encoder_state: Encoder ... | language-translation/dlnd_language_translation.ipynb | rishizek/deep-learning | mit |
Build the Decoding Layer
Implement decoding_layer() to create a Decoder RNN layer.
Embed the target sequences
Construct the decoder LSTM cell (just like you constructed the encoder cell above)
Create an output layer to map the outputs of the decoder to the elements of our vocabulary
Use the your decoding_layer_train(e... | def decoding_layer(dec_input, encoder_state,
target_sequence_length, max_target_sequence_length,
rnn_size,
num_layers, target_vocab_to_int, target_vocab_size,
batch_size, keep_prob, decoding_embedding_size):
"""
Create decoding layer
... | language-translation/dlnd_language_translation.ipynb | rishizek/deep-learning | mit |
Build the Neural Network
Apply the functions you implemented above to:
Encode the input using your encoding_layer(rnn_inputs, rnn_size, num_layers, keep_prob, source_sequence_length, source_vocab_size, encoding_embedding_size).
Process target data using your process_decoder_input(target_data, target_vocab_to_int, bat... | def seq2seq_model(input_data, target_data, keep_prob, batch_size,
source_sequence_length, target_sequence_length,
max_target_sentence_length,
source_vocab_size, target_vocab_size,
enc_embedding_size, dec_embedding_size,
rnn_size, ... | language-translation/dlnd_language_translation.ipynb | rishizek/deep-learning | mit |
Neural Network Training
Hyperparameters
Tune the following parameters:
Set epochs to the number of epochs.
Set batch_size to the batch size.
Set rnn_size to the size of the RNNs.
Set num_layers to the number of layers.
Set encoding_embedding_size to the size of the embedding for the encoder.
Set decoding_embedding_siz... | # Number of Epochs
epochs = 7
# Batch Size
batch_size = 100
# RNN Size
rnn_size = 256
# Number of Layers
num_layers = 2
# Embedding Size
encoding_embedding_size = 300
decoding_embedding_size = 300
# Learning Rate
learning_rate = 0.001
# Dropout Keep Probability
keep_probability = 1.0
display_step = 100 | language-translation/dlnd_language_translation.ipynb | rishizek/deep-learning | mit |
Funciones anónimas
Hasta ahora, a todas las funciones que creamos les poníamos un nombre al momento de crearlas, pero cuando tenemos que crear funciones que sólo tienen una línea y no se usan en una gran cantidad de lugares se pueden usar las funciones lambda: | help("lambda")
mi_funcion = lambda x, y: x+y
resultado = mi_funcion(1,2)
print resultado | Clase 04 - Excepciones, funciones lambda, búsquedas y ordenamientos.ipynb | gsorianob/fiuba-python | apache-2.0 |
Todos los casos son distintos y no hay UN lugar ideal dónde capturar la excepción; es cuestión del desarrollador decidir dónde conviene ponerlo para cada problema.
Capturar múltiples excepciones
Una única línea puede lanzar distintas excepciones, por lo que capturar un tipo de excepción en particular no me asegura que ... | def dividir_numeros(x, y):
try:
resultado = x/y
print 'El resultado es: %s' % resultado
except ZeroDivisionError:
print 'ERROR: Ha ocurrido un error por mezclar tipos de datos'
dividir_numeros(1, 0)
dividir_numeros(10, 2)
dividir_numeros("10", 2) | Clase 04 - Excepciones, funciones lambda, búsquedas y ordenamientos.ipynb | gsorianob/fiuba-python | apache-2.0 |
The next step would be to create an instance of the System class and to seed espresso. This instance is used as a handle to the simulation system. At any time, only one instance of the System class can exist. | system = espressomd.System(box_l=BOX_L)
system.seed = 42 | doc/tutorials/01-lennard_jones/01-lennard_jones.ipynb | psci2195/espresso-ffans | gpl-3.0 |
At this point, we have set the necessary environment and warmed up our system. Now, we integrate the equations of motion and take measurements. We first plot the radial distribution function which describes how the density varies as a function of distance from a tagged particle. The radial distribution function is aver... | # Integration parameters
sampling_interval = 100
sampling_iterations = 100
from espressomd.observables import ParticlePositions
from espressomd.accumulators import Correlator
# Pass the ids of the particles to be tracked to the observable.
part_pos = ParticlePositions(ids=range(N_PART))
# Initialize MSD correlator
msd... | doc/tutorials/01-lennard_jones/01-lennard_jones.ipynb | psci2195/espresso-ffans | gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.