markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Step 2: Putting in the Operations
Load the word embeddings for the word ids. You can do this using tf.nn.embedding_lookup. Remember to use your embeddings placeholder. You should end up with a Tensor of dimensions batch_size * sentence_length * embedding size.
To represent a whole tweet, let's use a neural bag of word... | "TODO" | draft/part1.ipynb | yala/introdeeplearning | mit |
Set up loss function, and optimizer to minimize it. We'll be using Adam as our optimizer | ## Make sure to call your output embedding logits, and your sentiments placeholder sentiments in python
loss = tf.nn.sigmoid_cross_entropy_with_logits(logits, sentiments)
loss = tf.reduce_sum(loss)
optimizer = tf.train.AdamOptimizer(1e-2).minimize(loss) | draft/part1.ipynb | yala/introdeeplearning | mit |
Run the Graph
Step 3: Set up training, and fetch optimizer at each iteration to train the model
First initialize all variables as in the toy example
Sample 20 random tweet,sentiment pairs for our feed_dict dictionary. Remember to feed in the embedding matrix.
fetch dictionary, the ops we want to run and tensors we wan... | trainSet = p.load( open('data/trainTweets_preprocessed.p','rb'))
random.shuffle(trainSet)
" TODO Init vars"
losses = []
for i in range(5000):
trainTweet = np.array( [ t[0] for t in trainSet[i: i+ minibatch_size]])
trainLabels = np.array( [int(t[1]) for t in trainSet[i: i+ minibatch_size] ])
results ... | draft/part1.ipynb | yala/introdeeplearning | mit |
Step 4: Check validation results, and tune
Try running the graph on validation data, without fetching the train op.
See how the results compare. If the train loss is much lower than the development loss, we may be overfitting. If the train loss is still high, try experimenting with the model archetecture to increase i... | validationSet = p.load( open('data/devTweets_preprocessed.p','rb'))
random.shuffle(validationSet)
losses = []
for i in range(20000/20):
valTweet = np.array( [ t[0] for t in validationSet[i: i+ minibatch_size]])
valLabels = np.array( [int(t[1]) for t in validationSet[i: i+ minibatch_size] ])
results = "TO... | draft/part1.ipynb | yala/introdeeplearning | mit |
Future Steps:
Things to try on your own:
- Adding in a tensor for accuracy, and log it at each step.
- Iterate over whole validation dataset to get more stable validation score
- Try tensorboard and graphing accuracy over both sets time.
- experiment with different archetectures that maximize validation score. Maybe ba... | # Step 1:
tf.reset_default_graph()
session = tf.Session()
minibatch_size = 20
tweet_length = 20
embedding_size = 100
hidden_dim_size = 100
output_size = 1
init_bias = 0
tweets = tf.placeholder(tf.int32, shape=[minibatch_size,tweet_length])
sentiments = tf.placeholder(tf.float32, shape=[minibatch_size])... | draft/part1.ipynb | yala/introdeeplearning | mit |
TOC Thematic Report - February 2019 (Part 2: Annual trends)
1. Get list of stations | # Select projects
prj_grid = nivapy.da.select_resa_projects(eng)
prj_grid
prj_df = prj_grid.get_selected_df()
print (len(prj_df))
prj_df
# Get stations
stn_df = nivapy.da.select_resa_project_stations(prj_df, eng)
print(len(stn_df))
stn_df.head()
# Map
nivapy.spatial.quickmap(stn_df, popup='station_code') | toc_report_feb_2019_part2.ipynb | JamesSample/icpw | mit |
2. Calculate annual trends | # User input
# Specify projects of interest
proj_list = ['ICPWaters US', 'ICPWaters NO', 'ICPWaters CA',
'ICPWaters UK', 'ICPWaters FI', 'ICPWaters SE',
'ICPWaters CZ', 'ICPWaters IT', 'ICPWaters PL',
'ICPWaters CH', 'ICPWaters LV', 'ICPWaters EE',
'ICPWaters IE', 'IC... | toc_report_feb_2019_part2.ipynb | JamesSample/icpw | mit |
1. 1990 to 2016 | # Specify period of interest
st_yr, end_yr = 1990, 2016
# Build output paths
plot_fold = os.path.join(res_fold, 'trends_plots_%s-%s' % (st_yr, end_yr))
res_csv = os.path.join(res_fold, 'res_%s-%s.csv' % (st_yr, end_yr))
dup_csv = os.path.join(res_fold, 'dup_%s-%s.csv' % (st_yr, end_yr))
nd_csv = os.path.join(res_fold,... | toc_report_feb_2019_part2.ipynb | JamesSample/icpw | mit |
There are lots of warnings printed above, but the main one of interest is:
Some stations have no relevant data in the period specified.
Which station(s) are missing data? | # Get stations with no data
stn_df[stn_df['station_id'].isin(nd_df['station_id'])] | toc_report_feb_2019_part2.ipynb | JamesSample/icpw | mit |
It seems that one Irish station has no associated data. This is as expected, because all the data supplied by Julian for this site comes from "near-shore" sampling (rather than "open water") and these have been omitted from the data upload - see here for details.
3. Basic checking
3.1. Boxplots | # Set up plot
fig = plt.figure(figsize=(20,10))
sn.set(style="ticks", palette="muted",
color_codes=True, font_scale=2)
# Horizontal boxplots
ax = sn.boxplot(x="mean", y="par_id", data=res_df,
whis=np.inf, color="c")
# Add "raw" data points for each observation, with some "jitter"
# to make the... | toc_report_feb_2019_part2.ipynb | JamesSample/icpw | mit |
4. Data restructuring
The code below is taken from here. It is used to generate output files in the format requested by Heleen.
4.1. Combine datasets | # Change 'period' col to 'data_period' and add 'analysis_period'
res_df['data_period'] = res_df['period']
del res_df['period']
res_df['analysis_period'] = '1990-2016'
# Join
df = pd.merge(res_df, stn_df, how='left', on='station_id')
# Re-order columns
df = df[['station_id',
'station_code', 'station_name', ... | toc_report_feb_2019_part2.ipynb | JamesSample/icpw | mit |
4.3. SO4 at Abiskojaure
SO4 for this station ('station_id=36458' in the "core" dataset) should be removed. See here. | # Remove sulphate-related series at Abiskojaure
df = df.query('not((station_id==36458) and ((par_id=="ESO4") or '
'(par_id=="ESO4X") or '
'(par_id=="ESO4_ECl")))') | toc_report_feb_2019_part2.ipynb | JamesSample/icpw | mit |
7.5. Tidy | # Remove unwanted cols
df.drop(labels=['mean', 'n_end', 'n_start', 'mk_stat', 'norm_mk_stat'],
axis=1, inplace=True)
# Reorder columns
df = df[['station_id', 'station_code',
'station_name', 'latitude', 'longitude', 'analysis_period',
'data_period', 'par_id', 'non_missing', 'median', 'std_dev... | toc_report_feb_2019_part2.ipynb | JamesSample/icpw | mit |
7.6. Convert to "wide" format | del df['data_period']
# Melt to "long" format
melt_df = pd.melt(df,
id_vars=['station_id', 'station_code',
'station_name', 'latitude', 'longitude',
'analysis_period', 'par_id', 'include'],
var_name='stat')
# Get only values w... | toc_report_feb_2019_part2.ipynb | JamesSample/icpw | mit |
Throughout the tutorial we'll want to visualize GPs. So we define a helper function for plotting: | # note that this helper function does three different things:
# (i) plots the observed data;
# (ii) plots the predictions from the learned GP after conditioning on data;
# (iii) plots samples from the GP prior (with no conditioning on observed data)
def plot(plot_observed_data=False, plot_predictions=False, n_prior... | tutorial/source/gp.ipynb | uber/pyro | apache-2.0 |
Data
The data consist of $20$ points sampled from
$$ y = 0.5\sin(3x) + \epsilon, \quad \epsilon \sim \mathcal{N}(0, 0.2).$$
with $x$ sampled uniformly from the interval $[0, 5]$. | N = 20
X = dist.Uniform(0.0, 5.0).sample(sample_shape=(N,))
y = 0.5 * torch.sin(3*X) + dist.Normal(0.0, 0.2).sample(sample_shape=(N,))
plot(plot_observed_data=True) # let's plot the observed data | tutorial/source/gp.ipynb | uber/pyro | apache-2.0 |
Define model
First we define a RBF kernel, specifying the values of the two hyperparameters variance and lengthscale. Then we construct a GPRegression object. Here we feed in another hyperparameter, noise, that corresponds to $\epsilon$ above. | kernel = gp.kernels.RBF(input_dim=1, variance=torch.tensor(5.),
lengthscale=torch.tensor(10.))
gpr = gp.models.GPRegression(X, y, kernel, noise=torch.tensor(1.)) | tutorial/source/gp.ipynb | uber/pyro | apache-2.0 |
Let's see what samples from this GP function prior look like. Note that this is before we've conditioned on the data. The shape these functions take—their smoothness, their vertical scale, etc.—is controlled by the GP kernel. | plot(model=gpr, kernel=kernel, n_prior_samples=2) | tutorial/source/gp.ipynb | uber/pyro | apache-2.0 |
For example, if we make variance and noise smaller we will see function samples with smaller vertical amplitude: | kernel2 = gp.kernels.RBF(input_dim=1, variance=torch.tensor(0.1),
lengthscale=torch.tensor(10.))
gpr2 = gp.models.GPRegression(X, y, kernel2, noise=torch.tensor(0.1))
plot(model=gpr2, kernel=kernel2, n_prior_samples=2) | tutorial/source/gp.ipynb | uber/pyro | apache-2.0 |
Inference
In the above we set the kernel hyperparameters by hand. If we want to learn the hyperparameters from the data, we need to do inference. In the simplest (conjugate) case we do gradient ascent on the log marginal likelihood. In pyro.contrib.gp, we can use any PyTorch optimizer to optimize parameters of a model.... | optimizer = torch.optim.Adam(gpr.parameters(), lr=0.005)
loss_fn = pyro.infer.Trace_ELBO().differentiable_loss
losses = []
num_steps = 2500 if not smoke_test else 2
for i in range(num_steps):
optimizer.zero_grad()
loss = loss_fn(gpr.model, gpr.guide)
loss.backward()
optimizer.step()
losses.append(l... | tutorial/source/gp.ipynb | uber/pyro | apache-2.0 |
Let's see if we're learned anything reasonable: | plot(model=gpr, plot_observed_data=True, plot_predictions=True) | tutorial/source/gp.ipynb | uber/pyro | apache-2.0 |
Here the thick red curve is the mean prediction and the blue band represents the 2-sigma uncertainty around the mean. It seems we learned reasonable kernel hyperparameters, as both the mean and uncertainty give a reasonable fit to the data. (Note that learning could have easily gone wrong if we e.g. chose too large of ... | gpr.kernel.variance.item()
gpr.kernel.lengthscale.item()
gpr.noise.item() | tutorial/source/gp.ipynb | uber/pyro | apache-2.0 |
The period of the sinusoid that generated the data is $T = 2\pi/3 \approx 2.09$ so learning a lengthscale that's approximiately equal to a quarter period makes sense.
Fit the model using MAP
We need to define priors for the hyperparameters. | # Define the same model as before.
pyro.clear_param_store()
kernel = gp.kernels.RBF(input_dim=1, variance=torch.tensor(5.),
lengthscale=torch.tensor(10.))
gpr = gp.models.GPRegression(X, y, kernel, noise=torch.tensor(1.))
# note that our priors have support on the positive reals
gpr.kernel.leng... | tutorial/source/gp.ipynb | uber/pyro | apache-2.0 |
Let's inspect the hyperparameters we've learned: | # tell gpr that we want to get samples from guides
gpr.set_mode('guide')
print('variance = {}'.format(gpr.kernel.variance))
print('lengthscale = {}'.format(gpr.kernel.lengthscale))
print('noise = {}'.format(gpr.noise)) | tutorial/source/gp.ipynb | uber/pyro | apache-2.0 |
Note that the MAP values are different from the MLE values due to the prior.
Sparse GPs
For large datasets computing the log marginal likelihood is costly due to the expensive matrix operations involved (e.g. see Section 2.2 of [1]). A variety of so-called 'sparse' variational methods have been developed to make GPs vi... | N = 1000
X = dist.Uniform(0.0, 5.0).sample(sample_shape=(N,))
y = 0.5 * torch.sin(3*X) + dist.Normal(0.0, 0.2).sample(sample_shape=(N,))
plot(plot_observed_data=True) | tutorial/source/gp.ipynb | uber/pyro | apache-2.0 |
Using the sparse GP is very similar to using the basic GP used above. We just need to add an extra parameter $X_u$ (the inducing points). | # initialize the inducing inputs
Xu = torch.arange(20.) / 4.0
# initialize the kernel and model
pyro.clear_param_store()
kernel = gp.kernels.RBF(input_dim=1)
# we increase the jitter for better numerical stability
sgpr = gp.models.SparseGPRegression(X, y, kernel, Xu=Xu, jitter=1.0e-5)
# the way we setup inference is ... | tutorial/source/gp.ipynb | uber/pyro | apache-2.0 |
We can see that the model learns a reasonable fit to the data. There are three different sparse approximations that are currently implemented in Pyro:
"DTC" (Deterministic Training Conditional)
"FITC" (Fully Independent Training Conditional)
"VFE" (Variational Free Energy)
By default, SparseGPRegression will u... | # initialize the inducing inputs
Xu = torch.arange(10.) / 2.0
# initialize the kernel, likelihood, and model
pyro.clear_param_store()
kernel = gp.kernels.RBF(input_dim=1)
likelihood = gp.likelihoods.Gaussian()
# turn on "whiten" flag for more stable optimization
vsgp = gp.models.VariationalSparseGP(X, y, kernel, Xu=Xu... | tutorial/source/gp.ipynb | uber/pyro | apache-2.0 |
<span class="exercize">Exercise: RGB intensity plot</span>
Plot the intensity of each channel of the image along a given row.
Start with the following template: | def plot_intensity(image, row):
# Fill in the three lines below
red_values = ...
green_values = ...
blue_values = ...
plt.figure()
plt.plot(red_values)
plt.plot(green_values)
plt.plot(blue_values)
pass | scikit_image/lectures/00_images_are_arrays.v3.ipynb | M-R-Houghton/euroscipy_2015 | mit |
K-Means Clustering
Motivation
Given a set of objects, we specify that we want $k$ clusters. Each cluster has a mean representing it, and we assign each point to the clusters based on which cluster mean its closest to. For each point, the reconstruction error is defined to be its distance to its cluster mean. This gives... | import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn.cluster import KMeans
from sklearn.cluster import AgglomerativeClustering
from sklearn import datasets
centers = [[1, 1], [-1, -1], [1, -1]]
iris = datasets.load_iris()
X = iris.data
y = iris.target
estimators = {'... | 3/1-Clustering.ipynb | dataventures/workshops | mit |
Hierarchical Clustering
Motivation
K-Means is one of the most common and simple clustering methods, but it has a couple of key limitations. First off, it is nondeterministic as it depends on the initial choice of cluster means, and Lloyd's Algorithm only arrives upon local minima rather than the global minimum. Further... | estimators = {'Hierarchical 3': AgglomerativeClustering(n_clusters=3)}
fignum = 1
for name, est in estimators.items():
fig = plt.figure(fignum, figsize=(4, 3))
plt.clf()
ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=48, azim=134)
plt.cla()
est.fit(X)
labels = est.labels_
ax.scatter(X[:, 3], ... | 3/1-Clustering.ipynb | dataventures/workshops | mit |
Challenge
Look at the other clustering methods provided by SKLearn, and consider their use cases. Pick three to run on the sample iris dataset that you think will produce the most accurate clusters. Tune parameters and look at the different options to try and get your clusters as close to the ground truth as possible. ... | np.random.seed(5)
centers = [[1, 1], [-1, -1], [1, -1]]
iris = datasets.load_iris()
X = iris.data
y = iris.target
# TODO: choose three additional estimators here that will give the best results.
estimators = {'Hierarchical 3': AgglomerativeClustering(n_clusters=3),
'K-Means 3': KMeans(n_clusters=3),
... | 3/1-Clustering.ipynb | dataventures/workshops | mit |
Visualize Data
View a sample from the dataset.
You do not need to modify this section. | import random
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
index = random.randint(1, len(X_train))
image = X_train[index].squeeze()
plt.figure(figsize=(1,1))
plt.imshow(image, cmap="gray")
print(y_train[index]) | CarND-LetNet/LeNet-Lab.ipynb | swirlingsand/self-driving-car-nanodegree-nd013 | mit |
Setup TensorFlow
The EPOCH and BATCH_SIZE values affect the training speed and model accuracy.
You do not need to modify this section. | import tensorflow as tf
EPOCHS = 20
BATCH_SIZE = 64 | CarND-LetNet/LeNet-Lab.ipynb | swirlingsand/self-driving-car-nanodegree-nd013 | mit |
TODO: Implement LeNet-5
Implement the LeNet-5 neural network architecture.
This is the only cell you need to edit.
Input
The LeNet architecture accepts a 32x32xC image as input, where C is the number of color channels. Since MNIST images are grayscale, C is 1 in this case.
Architecture
Layer 1: Convolutional. The outpu... | from tensorflow.contrib.layers import flatten
def LeNet(x):
# Hyperparameters
mu = 0
sigma = 0.1
# Layer 1: Convolutional. Input = 32x32x1. Output = 28x28x6.
convolutional_1_weights = tf.Variable(tf.truncated_normal(shape=(5,5,1,6), mean = mu, stddev = sigma))
convolutional_1_bias = tf... | CarND-LetNet/LeNet-Lab.ipynb | swirlingsand/self-driving-car-nanodegree-nd013 | mit |
Features and Labels
Train LeNet to classify MNIST data.
x is a placeholder for a batch of input images.
y is a placeholder for a batch of output labels.
You do not need to modify this section. | x = tf.placeholder(tf.float32, (None, 32, 32, 1))
y = tf.placeholder(tf.int32, (None))
# added this to fix bug CUDA_ERROR_ILLEGAL_ADDRESS / kernal crash
with tf.device('/cpu:0'):
one_hot_y = tf.one_hot(y, 10) | CarND-LetNet/LeNet-Lab.ipynb | swirlingsand/self-driving-car-nanodegree-nd013 | mit |
Exercício 2: Crie uma função para determinar se um ano é bissexto.
O ano é bissexto se for múltiplo de 400 ou múltiplo de 4 e não múltiplo de 100. Utilize o operador de resto da divisão (%) para determinar se um número é múltiplo de outro. |
print (Bissexto(2000)) # True
print (Bissexto(2004)) # True
print (Bissexto(1900)) # False | ListaEX_02.ipynb | folivetti/PIPYTHON | mit |
Exercício 3: Crie uma função que receba três valores x, y, z como parâmetros e retorne-os em ordem crescente.
O Python permite que você faça comparações relacionais entre as 3 variáveis em uma única instrução:
Python
x < y < z |
print (Crescente(1,2,3))
print (Crescente(1,3,2))
print (Crescente(2,1,3))
print (Crescente(2,3,1))
print (Crescente(3,1,2))
print (Crescente(3,2,1))
print (Crescente(1,2,2)) | ListaEX_02.ipynb | folivetti/PIPYTHON | mit |
Exercício 4: O peso ideial de uma pessoa segue a seguinte tabela:
|Altura|Peso Homem|Peso Mulher|
|--|--|--|
|1,5 m|50 kg|48 kg|
|1,7 m|74 kg|68 kg|
|1,9 m|98 kg|88 kg|
|2,1 m|122 kg|108 kg|
Faça uma função que receba como parâmetro o gênero, altura e peso da pessoa e retorne True se ela está com o peso ideal. |
print (PesoIdeal("masculino", 1.87, 75)) # True
print (PesoIdeal("masculino", 1.92, 200)) # False
print (PesoIdeal("feminino", 1.87, 90)) # False
print (PesoIdeal("feminino", 1.6, 40)) # True | ListaEX_02.ipynb | folivetti/PIPYTHON | mit |
Exercício 5: Crie uma função que receba as coordenadas cx, cy, o raio r correspondentes ao centro e raio de uma circunferência e receba também coordenadas x, y de um ponto.
A função deve retornar True se o ponto está dentro da circunferência e False, caso contrário. |
print (Circunferencia(0,0,10,5,5) ) # True
print (Circunferencia(0,0,10,15,5)) # False | ListaEX_02.ipynb | folivetti/PIPYTHON | mit |
Exercício 5b: Crie uma função chamada Circunferencia que recebe como entrada as coordenadas do centro cx e cy e o raio r da circunferência. Essa função deve criar uma outra função chamada VerificaPonto que recebe como entrada as coordenadas x e y de um ponto e retorna True caso o ponto esteja dentro da circunferência, ... |
Verifica = Circunferencia(0,0,10)
print (Verifica(5,5))
print (Verifica(15,5)) | ListaEX_02.ipynb | folivetti/PIPYTHON | mit |
Exercício 6:
A Estrela da Morte é uma arma desenvolvida pelo império para dominar o universo.
Um telescópio digital foi desenvolvido pelas forças rebeldes para detectar o local dela.
Mas tal telescópio só consegue mostrar o contorno das circunferências encontradas indicando o centro e o raio delas.
Sabendo que uma Est... | import math
print (EstrelaMorte(0,0,20,3,3,10))
print (EstrelaMorte(0,0,200,3,3,10))
print (EstrelaMorte(0,0,200,195,3,10)) | ListaEX_02.ipynb | folivetti/PIPYTHON | mit |
Exercício 7: Crie uma função para determinar as raízes reais da equação do segundo grau:
$$
a.x^{2} + b.x + c = 0
$$
Faça com que a função retorne:
Uma raíz quando $b^2 = 4ac$
Raízes complexas quando $b^2 < 4ac$
Raízes reais, caso contrário
Utilize a biblioteca cmath para calcular a raíz quadrada para números complex... | import math, cmath
print (RaizSegundoGrau(2,4,2) ) # -1.0
print (RaizSegundoGrau(2,2,2)) # -0.5 - 0.9j, -0.5+0.9j
print (RaizSegundoGrau(2,6,2)) # -2.6, -0.38 | ListaEX_02.ipynb | folivetti/PIPYTHON | mit |
Discriminator and Generator Losses
Now we need to calculate the losses, which is a little tricky. For the discriminator, the total loss is the sum of the losses for real and fake images, d_loss = d_loss_real + d_loss_fake. The losses will by sigmoid cross-entropys, which we can get with tf.nn.sigmoid_cross_entropy_with... | # Calculate losses
d_loss_real = tf.reduce_mean(
tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_real,
labels=tf.ones_like(d_logits_real) * (1 - smooth)))
d_loss_fake = tf.reduce_mean(
tf.nn.sigmoid_cross_entropy_with... | gan_mnist/Intro_to_GANs_Solution.ipynb | udacity/deep-learning | mit |
1. Data
We should now have all the data loaded, named as it was before. As a reminder, these are the NGC numbers of the galaxies in the data set: | ngc_numbers | tutorials/cepheids_all_galaxies.ipynb | KIPAC/StatisticalMethods | gpl-2.0 |
2. Independent fits for each galaxy
This class will package up the fitting using the "4b" method from the previous notebook (emcee plus analytic integration). In particular, it relies on the log_prior, log_posterior and log_likelihood_B functions (as well as the data, among other previous global-scope definitions). If ... | class singleFitter:
def __init__(self, ngc):
'''
ngc: NGC identifier of the galaxy to fit
'''
self.ngc = ngc
self.data = data[ngc] # from global scope
# reproducing this for paranoia's sake
self.param_names = ['a', 'b', 'sigma']
self.param_labels = [r'... | tutorials/cepheids_all_galaxies.ipynb | KIPAC/StatisticalMethods | gpl-2.0 |
Let's set up and run each of these fits, which hopefully shouldn't take too long. As always, you are responsible for looking over the trace plots and making sure everything is ok. | independent_fits = [singleFitter(ngc) for ngc in ngc_numbers]
independent_fits[0].fit(guessvec)
independent_fits[1].fit(guessvec)
independent_fits[2].fit(guessvec)
independent_fits[3].fit(guessvec)
independent_fits[4].fit(guessvec)
independent_fits[5].fit(guessvec)
independent_fits[6].fit(guessvec)
independent_... | tutorials/cepheids_all_galaxies.ipynb | KIPAC/StatisticalMethods | gpl-2.0 |
Based on the plots above, remove some burn-in. Check that the quantitative diagnostics are acceptable as they are printed out. | TBC(1) # burn = ...
for f in independent_fits:
print('NGC', f.ngc)
f.burnin(burn=burn) # optionally, set maxlag here also
print('') | tutorials/cepheids_all_galaxies.ipynb | KIPAC/StatisticalMethods | gpl-2.0 |
Now we'll use pygtc to plot all the individual posteriors, and see how they compare. | plotGTC([f.samples for f in independent_fits], paramNames=param_labels,
chainLabels=['NGC'+str(f.ngc) for f in independent_fits],
figureSize=8, customLabelFont={'size':12}, customTickFont={'size':12}, customLegendFont={'size':16}); | tutorials/cepheids_all_galaxies.ipynb | KIPAC/StatisticalMethods | gpl-2.0 |
Visually, would you say that it's likely that all the scaling parameters, or some subset, are universal?
TBC commentary
2. A hierarchical model for all galaxies
On the basis of the last section, it should be clear that at least one of the scaling parameters in question is not universal amongst galaxies in the data se... | param_names_all = ['mu_a', 'tau_a', 'mu_b', 'tau_b', 'mu_s', 'tau_s']
param_labels_all = [r'$\mu_a$', r'$\tau_a$', r'$\mu_b$', r'$\tau_b$', r'$\mu_\sigma$', r'$\tau_\sigma$'] | tutorials/cepheids_all_galaxies.ipynb | KIPAC/StatisticalMethods | gpl-2.0 |
Complete the log-likelihood function for this part. Similarly to the way we dealt with Mtrue before, the galparams argument will end up being an array containing $(a_1,b_1,\sigma_1,a_2,b_2,\sigma_2,\ldots)$, from which we can extract arrays of $a_i$, $b_i$ and $\sigma_i$ if we want. The line given to you accounts for t... | def log_likelihood_all_A(mu_a, tau_a, mu_b, tau_b, mu_s, tau_s, galparams):
lnp = np.sum([f._logpost_vecarg_B(galparams[(0+3*i):(3+3*i)]) for i,f in enumerate(independent_fits)])
TBC() # lnp += ... more stuff ...
return lnp
TBC_above() | tutorials/cepheids_all_galaxies.ipynb | KIPAC/StatisticalMethods | gpl-2.0 |
As a consequence of the code above calling _logpost_vecarg_B (note post), the old priors for the $a_i$, $b_i$ and $\sigma_i$ will be included in the return value. This is ok only because we're using uniform priors, so in the log those priors are either a finite constant or $-\infty$. In general, we would need to divide... | def log_prior_all(mu_a, tau_a, mu_b, tau_b, mu_s, tau_s, galparams=None):
TBC()
TBC_above() | tutorials/cepheids_all_galaxies.ipynb | KIPAC/StatisticalMethods | gpl-2.0 |
You can have the log-posterior functions. | def log_posterior_all(loglike, **params):
lnp = log_prior_all(**params)
if lnp != -np.inf:
lnp += loglike(**params)
return lnp
def logpost_vecarg_all_A(pvec):
params = {name:pvec[i] for i,name in enumerate(param_names_all)}
params['galparams'] = pvec[len(param_names_all):]
return log_po... | tutorials/cepheids_all_galaxies.ipynb | KIPAC/StatisticalMethods | gpl-2.0 |
Based on the triangle plot in the first section, guess rough starting values for $(\mu_a,\tau_a,\mu_b,\tau_b,\mu_\sigma,\tau_\sigma)$. (NB: make this a list rather than the usual dictionary.) We'll re-use the previous guess for the galaxy-specific parameters. | TBC() # guess_all = [list of hyperparameter starting values]
guess_all_A = np.array(guess_all + guessvec*9) | tutorials/cepheids_all_galaxies.ipynb | KIPAC/StatisticalMethods | gpl-2.0 |
Quick check that the functions above work: | logpost_vecarg_all_A(guess_all_A) | tutorials/cepheids_all_galaxies.ipynb | KIPAC/StatisticalMethods | gpl-2.0 |
Below, we run emcee as before.
IMPORTANT
You should find this to be more tractable than the "brute force" solution in the previous notebook, but still very slow compared to what we normally see in class. Again, you do not need to run this version long enough to get what we would normally consider acceptable results, in... | %%time
nsteps = 100 # or whatever
npars = len(guess_all_A)
nwalkers = 2*npars
sampler = emcee.EnsembleSampler(nwalkers, npars, logpost_vecarg_all_A)
start = np.array([np.array(guess_all_A)*(1.0 + 0.01*np.random.randn(npars)) for j in range(nwalkers)])
sampler.run_mcmc(start, nsteps)
print('Yay!') | tutorials/cepheids_all_galaxies.ipynb | KIPAC/StatisticalMethods | gpl-2.0 |
Look at the traces (we'll only include one of the galaxy's scaling parameters). | npars = len(guess_all)+3
plt.rcParams['figure.figsize'] = (16.0, 3.0*npars)
fig, ax = plt.subplots(npars, 1);
cr.plot_traces(sampler.chain[:min(8,nwalkers),:,:npars], ax, labels=param_labels_all+param_labels);
npars = len(guess_all_A) | tutorials/cepheids_all_galaxies.ipynb | KIPAC/StatisticalMethods | gpl-2.0 |
Go through the usual motions, making sure to set burn and maxlag to something appropriate for the length of the chain. | TBC()
# burn = ...
# maxlag = ...
tmp_samples = [sampler.chain[i,burn:,:9] for i in range(nwalkers)]
print('R =', cr.GelmanRubinR(tmp_samples))
print('neff =', cr.effective_samples(tmp_samples, maxlag=maxlag))
print('NB: Since walkers are not independent, these will be optimistic!')
print("Plus, there's a good chance ... | tutorials/cepheids_all_galaxies.ipynb | KIPAC/StatisticalMethods | gpl-2.0 |
As before, we'll be comparing the posteriors from the methods we attempt: | samples_all_A = sampler.chain[:,burn:,:].reshape(nwalkers*(nsteps-burn), npars)
plotGTC([samples_all_A[:,:9]], paramNames=param_labels_all+param_labels, chainLabels=['emcee/brute'],
figureSize=12, customLabelFont={'size':12}, customTickFont={'size':12}, customLegendFont={'size':16}); | tutorials/cepheids_all_galaxies.ipynb | KIPAC/StatisticalMethods | gpl-2.0 |
To be more thorough, we would also want to see how well the new hierarchical part of the model fits, meaning whether the posteriors of $a_i$, $b_i$ and $\sigma_i$ are collectively consistent with being drawn from their respective fitted Gaussians. Things might look slightly different than the plots we made above, since... | def log_likelihood_all_B(mu_a, tau_a, mu_b, tau_b, mu_s, tau_s):
TBC()
TBC_above() | tutorials/cepheids_all_galaxies.ipynb | KIPAC/StatisticalMethods | gpl-2.0 |
This is for free: | def logpost_vecarg_all_B(pvec):
params = {name:pvec[i] for i,name in enumerate(param_names_all)}
return log_posterior_all(log_likelihood_all_B, **params) | tutorials/cepheids_all_galaxies.ipynb | KIPAC/StatisticalMethods | gpl-2.0 |
The usual sanity check: | logpost_vecarg_all_B(guess_all) | tutorials/cepheids_all_galaxies.ipynb | KIPAC/StatisticalMethods | gpl-2.0 |
Let's get an idea of how computationally expensive all these sums are by running a very short chain. | nsteps = 10
npars = len(guess_all)
nwalkers = 2*npars
sampler = emcee.EnsembleSampler(nwalkers, npars, logpost_vecarg_all_B)
start = np.array([np.array(guess_all)*(1.0 + 0.01*np.random.randn(npars)) for j in range(nwalkers)])
%time sampler.run_mcmc(start, nsteps)
print('Yay?') | tutorials/cepheids_all_galaxies.ipynb | KIPAC/StatisticalMethods | gpl-2.0 |
For me this comes out to about 7 seconds for 10 steps - slower than we'd ideally like, at least without more serious computing resources than my laptop. (If you run longer, though, you should see performance better than in part A.)
However, its worth asking if we can get away with using fewer samples. In principle, we ... | for f in independent_fits:
f.thin(500) | tutorials/cepheids_all_galaxies.ipynb | KIPAC/StatisticalMethods | gpl-2.0 |
With only 500 samples left in the sum for each galaxy, it should be possible to get results that appear basically converged with a couple of minutes runtime (and you should do so). Nevertheless, before turning in the notebook, please reduce the number of steps such that the sampling cell below takes longer than $\sim30... | %%time
TBC() # nsteps =
npars = len(guess_all)
nwalkers = 2*npars
sampler = emcee.EnsembleSampler(nwalkers, npars, logpost_vecarg_all_B)
start = np.array([np.array(guess_all)*(1.0 + 0.01*np.random.randn(npars)) for j in range(nwalkers)])
sampler.run_mcmc(start, nsteps);
print('Yay!') | tutorials/cepheids_all_galaxies.ipynb | KIPAC/StatisticalMethods | gpl-2.0 |
Let's see how it does: | plt.rcParams['figure.figsize'] = (16.0, 3.0*npars)
fig, ax = plt.subplots(npars, 1);
cr.plot_traces(sampler.chain[:min(8,nwalkers),:,:npars], ax, labels=param_labels_all); | tutorials/cepheids_all_galaxies.ipynb | KIPAC/StatisticalMethods | gpl-2.0 |
The sampler is probably struggling to move around efficiently, but you could imagine running patiently for a while and ending up with something useful. Let's call this approach viable, but not ideal. Still, make sure you have reasonable convergence before continuing. | TBC()
# burn = ...
# maxlag = ...
tmp_samples = [sampler.chain[i,burn:,:] for i in range(nwalkers)]
print('R =', cr.GelmanRubinR(tmp_samples))
print('neff =', cr.effective_samples(tmp_samples, maxlag=maxlag))
print('NB: Since walkers are not independent, these will be optimistic!') | tutorials/cepheids_all_galaxies.ipynb | KIPAC/StatisticalMethods | gpl-2.0 |
And now the burning question: how does the posterior compare with the brute force version? | samples_all_B = sampler.chain[:,burn:,:].reshape(nwalkers*(nsteps-burn), npars)
plotGTC([samples_all_A[:,:len(param_names_all)], samples_all_B], paramNames=param_labels_all, chainLabels=['emcee/brute', 'emcee/SMC'],
figureSize=10, customLabelFont={'size':12}, customTickFont={'size':12}, customLegendFont={'size'... | tutorials/cepheids_all_galaxies.ipynb | KIPAC/StatisticalMethods | gpl-2.0 |
Checkpoint: Your posterior is compared with our solution by the cell below. Keep in mind they may have very different numbers of samples - we let ours run for several minutes. | sol = np.loadtxt('solutions/ceph2.dat.gz')
plotGTC([sol, samples_all_B], paramNames=param_labels_all, chainLabels=['solution', 'my emcee/SMC'],
figureSize=8, customLabelFont={'size':12}, customTickFont={'size':12}, customLegendFont={'size':16}); | tutorials/cepheids_all_galaxies.ipynb | KIPAC/StatisticalMethods | gpl-2.0 |
Setup
This example depends on the following software:
IPython
NumPy
SciPy
SymPy >= 0.7.6
matplotlib
The easiest way to install the Python packages it is to use conda:
$ conda install ipython-notebook numpy scipy sympy matplotlib
To create animations you need a video encoder like ffmpeg installed.
Equations of Motion... | from __future__ import division, print_function
import sympy as sm
import sympy.physics.mechanics as me | examples/npendulum/n-pendulum-control.ipynb | oliverlee/pydy | bsd-3-clause |
The coordinate trajectories are plotted below. | lines = plt.plot(t, x[:, :x.shape[1] // 2])
lab = plt.xlabel('Time [sec]')
leg = plt.legend(dynamic[:x.shape[1] // 2]) | examples/npendulum/n-pendulum-control.ipynb | oliverlee/pydy | bsd-3-clause |
And the generalized speed trajectories. | lines = plt.plot(t, x[:, x.shape[1] // 2:])
lab = plt.xlabel('Time [sec]')
leg = plt.legend(dynamic[x.shape[1] // 2:]) | examples/npendulum/n-pendulum-control.ipynb | oliverlee/pydy | bsd-3-clause |
The following function was modeled from Jake Vanderplas's post on matplotlib animations. The default animation writer is used (typically ffmpeg), you can change it by adding writer argument to anim.save call. | def animate_pendulum(t, states, length, filename=None):
"""Animates the n-pendulum and optionally saves it to file.
Parameters
----------
t : ndarray, shape(m)
Time array.
states: ndarray, shape(m,p)
State time history.
length: float
The length of the pendulum links.
... | examples/npendulum/n-pendulum-control.ipynb | oliverlee/pydy | bsd-3-clause |
Also convert equilibrium_point to a numeric array: | equilibrium_point = np.asarray([x.evalf() for x in equilibrium_point], dtype=float) | examples/npendulum/n-pendulum-control.ipynb | oliverlee/pydy | bsd-3-clause |
Now that we have a linear system, the SciPy package can be used to design an optimal controller for the system. | from numpy.linalg import matrix_rank
from scipy.linalg import solve_continuous_are | examples/npendulum/n-pendulum-control.ipynb | oliverlee/pydy | bsd-3-clause |
First we can check to see if the system is, in fact, controllable. The rank of the controllability matrix must be equal to the number of rows in $A$, but the matrix_rank algorithm is numerically ill conditioned and for certain values of $n$ this will fail, as seen below for $n=5$. Nevertheless, the system is controllab... | def controllable(a, b):
"""Returns true if the system is controllable and false if not.
Parameters
----------
a : array_like, shape(n,n)
The state matrix.
b : array_like, shape(n,r)
The input matrix.
Returns
-------
controllable : boolean
"""
a = np.matrix(a)
... | examples/npendulum/n-pendulum-control.ipynb | oliverlee/pydy | bsd-3-clause |
So now we can compute the optimal gains with a linear quadratic regulator. I chose identity matrices for the weightings for simplicity. | Q = np.eye(A.shape[0])
R = np.eye(B.shape[1])
S = solve_continuous_are(A, B, Q, R);
K = np.dot(np.dot(np.linalg.inv(R), B.T), S)
K | examples/npendulum/n-pendulum-control.ipynb | oliverlee/pydy | bsd-3-clause |
The plots show that we seem to have a stable system. | lines = plt.plot(t, x[:, :x.shape[1] // 2])
lab = plt.xlabel('Time [sec]')
leg = plt.legend(dynamic[:x.shape[1] // 2])
lines = plt.plot(t, x[:, x.shape[1] // 2:])
lab = plt.xlabel('Time [sec]')
leg = plt.legend(dynamic[x.shape[1] // 2:])
animate_pendulum(t, x, arm_length, filename="closed-loop.mp4")
from IPython.dis... | examples/npendulum/n-pendulum-control.ipynb | oliverlee/pydy | bsd-3-clause |
The video clearly shows that the controller can balance all $n$ of the pendulum links. The weightings in the lqr design can be tweaked to give different performance if needed.
This example shows that the free and open source scientific Python tools for dynamics are easily comparable in ability and quality to a commerci... | # Install with pip install version_information
%load_ext version_information
%version_information numpy, sympy, scipy, matplotlib, control | examples/npendulum/n-pendulum-control.ipynb | oliverlee/pydy | bsd-3-clause |
경우 2
만약
$$
\mu = \begin{bmatrix}2 \ 3 \end{bmatrix}. \;\;\;
\Sigma = \begin{bmatrix}2 & 3 \ 3 & 7 \end{bmatrix}
$$
이면
$$
; \Sigma ; = 5,\;\;\;
\Sigma^{-1} = \begin{bmatrix}1.4 & -0.6 \ -0.6 & 0.4 \end{bmatrix}
$$
$$
(x-\mu)^T \Sigma^{-1} (x-\mu) =
\begin{bmatrix}x_1 - 2 & x_2 - 3 \end{bmatrix}
\begin{bmatrix}1.... | mu = [2, 3]
cov = [[2, 3],[3, 7]]
rv = sp.stats.multivariate_normal(mu, cov)
xx = np.linspace(0, 4, 120)
yy = np.linspace(1, 5, 150)
XX, YY = np.meshgrid(xx, yy)
plt.grid(False)
plt.contourf(XX, YY, rv.pdf(np.dstack([XX, YY])))
plt.axis("equal")
plt.show() | 10. 기초 확률론3 - 확률 분포 모형/13. 다변수 가우시안 정규 분포.ipynb | zzsza/Datascience_School | mit |
Installing django and selenium | # Create a virtual env to load with selenium and django
#!conda create -yn django_env django python=3 # y flag automatically selects yes to install
#!source activate django_eng # activate virtual environment
#!pip install --upgrade selenium # install selenium. | wk9/notebooks/.ipynb_checkpoints/ch.1-getting-started-with-django-checkpoint.ipynb | saashimi/code_guild | mit |
Fixing our failure | # Use django to create a project called 'superlists'
#django-admin.py startproject superlists
!tree ../examples/ | wk9/notebooks/.ipynb_checkpoints/ch.1-getting-started-with-django-checkpoint.ipynb | saashimi/code_guild | mit |
Next, we evaluate scikit-learn accuracy where we predict feed implementation based on latency. | import graphviz
import pandas
from sklearn import tree
from sklearn.model_selection import train_test_split
clf = tree.DecisionTreeClassifier()
input = pandas.read_csv("/home/glenn/git/clojure-news-feed/client/ml/etl/latency.csv")
data = input[input.columns[7:9]]
data['cloud'] = input['cloud'].apply(lambda x: 1.0 if x... | client/ml/dt/accuracy.ipynb | gengstrand/clojure-news-feed | epl-1.0 |
As you can see, scikit-learn has a 99% accuracy rate. We now do the same thing with tensorflow. | import tensorflow as tf
import numpy as np
import pandas
from tensorflow.python.ops import parsing_ops
from tensorflow.contrib.tensor_forest.python import tensor_forest
from tensorflow.contrib.learn.python.learn.utils import input_fn_utils
from sklearn.model_selection import train_test_split
input = pandas.read_csv("/... | client/ml/dt/accuracy.ipynb | gengstrand/clojure-news-feed | epl-1.0 |
Looks like tensorflow has a 98% accuracy rate which is 1% less than scikit-learn algo. Let us use Tensorflow to look at the accuracy of predicting cloud vendor based on throughput. | import tensorflow as tf
import numpy as np
import pandas
from tensorflow.python.ops import parsing_ops
from tensorflow.contrib.tensor_forest.python import tensor_forest
from tensorflow.contrib.learn.python.learn.utils import input_fn_utils
from sklearn.model_selection import train_test_split
input = pandas.read_csv("/... | client/ml/dt/accuracy.ipynb | gengstrand/clojure-news-feed | epl-1.0 |
Using PCA to Plot Datasets
PCA is a useful preprocessing technique for both visualizing data in 2 or 3 dimensions, and for improving the performance of downstream algorithms such as classifiers. We will see more details about using PCA as part of a machine learning pipeline in the net section, but here we will explore ... | import numpy as np
random_state = np.random.RandomState(1999)
X = np.random.randn(500, 2)
red_idx = np.where(X[:, 0] < 0)[0]
blue_idx = np.where(X[:, 0] >= 0)[0]
# Stretching
s_matrix = np.array([[1, 0],
[0, 20]])
# Rotation
r_angle = 33
r_rad = np.pi * r_angle / 180
r_matrix = np.array([[np.cos(r_... | notebooks/03.2 Methods - Unsupervised Preprocessing.ipynb | samstav/scipy_2015_sklearn_tutorial | cc0-1.0 |
We can also use PCA to visualize complex data in low dimensions in order to see how "close" and "far" different datapoints are in a 2D space. There are many different ways to do this visualization, and some common algorithms are found in sklearn.manifold. PCA is one of the simplest and most common methods for quickly v... | from sklearn import datasets
lfw_people = datasets.fetch_lfw_people(min_faces_per_person=70, resize=0.4,
data_home='datasets')
lfw_people.data.shape | notebooks/03.2 Methods - Unsupervised Preprocessing.ipynb | samstav/scipy_2015_sklearn_tutorial | cc0-1.0 |
决策树原理与实现简介
前言
为什么讲决策树?
原理简单,直白易懂。
可解释性好。
变种在工业上应用多:随机森林、GBDT。
深化拓展
理论,考古:ID3, C4.5, CART
工程,实现细节:
demo
scikit-learn
spark
xgboost
应用,调参分析
演示
理论
算法:
ID3
C4.5
C5.0
CART
CHAID
MARS
行业黑话
分类问题 vs 回归问题
样本 = (特征$x$,真实值$y$)
目的:找到模型$h(\cdot)$,使得预测值$\hat{y} = h(x)$ $\to$ 真实值$y$ | from sklearn.datasets import load_iris
data = load_iris()
# 准备特征数据
X = pd.DataFrame(data.data,
columns=["sepal_length", "sepal_width", "petal_length", "petal_width"])
# 准备标签数据
y = pd.DataFrame(data.target, columns=['target'])
y.replace(to_replace=range(3), value=data.target_names, inplace=True)
# 组... | machine_learning/tree/decision_tree/presentation.ipynb | facaiy/book_notes | cc0-1.0 |
三分钟明白决策树 | Image(url="https://upload.wikimedia.org/wikipedia/commons/f/f3/CART_tree_titanic_survivors.png")
Image(url="http://scikit-learn.org/stable/_images/iris.svg")
Image(url="http://scikit-learn.org/stable/_images/sphx_glr_plot_iris_0011.png")
samples = pd.concat([X, y], axis=1)
samples.head(3) | machine_learning/tree/decision_tree/presentation.ipynb | facaiy/book_notes | cc0-1.0 |
工程
Demo实现
其主要问题是在每次决策时找到一个分割点,让生成的子集尽可能地纯净。这里涉及到四个问题:
如何分割样本?
如何评价子集的纯净度?
如何找到单个最佳的分割点,其子集最为纯净?
如何找到最佳的分割点序列,其最终分割子集总体最为纯净? | Image(url="https://upload.wikimedia.org/wikipedia/commons/f/f3/CART_tree_titanic_survivors.png") | machine_learning/tree/decision_tree/presentation.ipynb | facaiy/book_notes | cc0-1.0 |
2. 如何评价子集的纯净度?
常用的评价函数正是计算各标签 $c_k$ 在子集中的占比 $p_k = c_k / \sum (c_k)$,并通过组合 $p_k$ 来描述占比集中或分散。 | def calc_class_proportion(node):
# 计算各标签在集合中的占比
y = node["target"]
return y.value_counts() / y.count()
calc_class_proportion(split["left_nodes"])
calc_class_proportion(split["right_nodes"]) | machine_learning/tree/decision_tree/presentation.ipynb | facaiy/book_notes | cc0-1.0 |
Data setup
We are going to use data from Fermi-LAT, Fermi-GBM and Swift-XRT. Let's go through the process of setting up the data from each instrument. We will work from high energy to low energy.
Fermi-LAT
Once we have obtained the Fermi-LAT data, in this case, the LAT Low Energy (LLE) data, we can reduce the data into... |
lle = TimeSeriesBuilder.from_lat_lle('lle',ft2_file="lle_pt.fit",
lle_file="lle.fit",
rsp_file="lle.rsp")
lle.set_background_interval('-100--10','150-500')
lle.set_active_time_interval('68-110')
lle.view_lightcurve(-200,500);
lle_plugin = ll... | examples/grb_multi_analysis.ipynb | giacomov/3ML | bsd-3-clause |
Fermi-GBM | gbm_detectors = ["n4", "n7", "n8", "b0"]
for det in gbm_detectors:
ts_cspec = TimeSeriesBuilder.from_gbm_cspec_or_ctime(
det, cspec_or_ctime_file=f"cspec_{det}.pha", rsp_file=f"cspec_{det}.rsp2"
)
ts_cspec.set_background_interval("-400--10", "700-1200")
ts_cspec.save_background(filename=f"{det... | examples/grb_multi_analysis.ipynb | giacomov/3ML | bsd-3-clause |
Swift-XRT
For Swift-XRT, we can use the normal OGIPLike plugin, but the energy resolution of the instrument is so fine that we would waste time integrating over the photon bins during forward-folding. Thus, there is a special plugin that overrides the computation of the photon integrals with a simple sum. | xrt = SwiftXRTLike(
"xrt",
observation="awt.pi",
background="awtback.pi",
arf_file="awt.arf",
response="awt.rmf",
)
xrt.display()
xrt.remove_rebinning()
xrt.set_active_measurements('4-10')
xrt.rebin_on_background(1.)
xrt.use_effective_area_correction()
xrt.view_count_spectrum();
| examples/grb_multi_analysis.ipynb | giacomov/3ML | bsd-3-clause |
Combining all the plugins | all_plugins = [lle_plugin, xrt]
for _ , plugin in gbm_plugins.items():
all_plugins.append(plugin)
datalist = DataList(*all_plugins) | examples/grb_multi_analysis.ipynb | giacomov/3ML | bsd-3-clause |
Fitting
Model setup
Band Function | sbpl = SmoothlyBrokenPowerLaw(pivot=1E3)
sbpl.alpha.prior = Truncated_gaussian(lower_bound=-1.5, upper_bound=0, mu=-1, sigma=.5)
sbpl.beta.prior = Truncated_gaussian(lower_bound=-3., upper_bound=-1.6, mu=-2, sigma=.5)
sbpl.break_energy.prior = Log_uniform_prior(lower_bound=1, upper_bound=1E3)
sbpl.break_scale.prior ... | examples/grb_multi_analysis.ipynb | giacomov/3ML | bsd-3-clause |
There are warnings, but that's okay - this happens a lot these days due to the whole ipython/jupyter renaming process. You can ignore them.
Get a database
Using the bash shell (not a notebook!), follow the instructions at the SW Carpentry db lessons discussion page to get the survey.db file. This is a sqlite3 databas... | %sql sqlite:///survey.db
%sql SELECT * FROM Person; | lectures/week-03/sql-demo.ipynb | dchud/warehousing-course | cc0-1.0 |
You should be able to execute all the standard SQL queries from the lesson here now. Note that you can also do this on the command line.
Note specialized sqlite3 commands like ".schema" might not work.
Connecting to a MySQL database
Now that you've explored the survey.db sample database with sqlite3, let's try working... | %sql mysql://mysqluser:mysqlpass@localhost/ | lectures/week-03/sql-demo.ipynb | dchud/warehousing-course | cc0-1.0 |
note if you get an error about MySQLdb not being installed here, enter this back in your bash shell:
% sudo pip install mysql-python
If it asks for your password, it's "vagrant".
After doing this, try executing the above cell again. You should see:
u'Connected: mysqluser@'
...if it works.
Creating a database
Now that ... | %sql CREATE DATABASE week3demo; | lectures/week-03/sql-demo.ipynb | dchud/warehousing-course | cc0-1.0 |
Now that we've created the database week3demo, we need to tell MySQL that we want to use it: | %sql USE week3demo; | lectures/week-03/sql-demo.ipynb | dchud/warehousing-course | cc0-1.0 |
But there's nothing in it: | %sql SHOW TABLES; | lectures/week-03/sql-demo.ipynb | dchud/warehousing-course | cc0-1.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.