markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Build the tree!
Now that all the tests are passing, we will train a tree model on the train_data. Limit the depth to 6 (max_depth = 6) to make sure the algorithm doesn't run for too long. Call this tree my_decision_tree.
Warning: This code block may take 1-2 minutes to learn. | # Make sure to cap the depth at 6 by using max_depth = 6
my_decision_tree = decision_tree_create(train_data, features, 'safe_loans', max_depth = 6)
print(my_decision_tree.keys()) | notebooks/binary-decision-tree.ipynb | leon-adams/datascience | mpl-2.0 |
Making predictions with a decision tree
As discussed in the lecture, we can make predictions from the decision tree with a simple recursive function. Below, we call this function classify, which takes in a learned tree and a test point x to classify. We include an option annotate that describes the prediction path whe... | def classify(tree, x, annotate = False):
# if the node is a leaf node.
if tree['is_leaf']:
if annotate:
print "At leaf, predicting %s" % tree['prediction']
return tree['prediction']
else:
# split on feature.
split_feature_value = x[tree['splitting_feature']]
... | notebooks/binary-decision-tree.ipynb | leon-adams/datascience | mpl-2.0 |
Evaluating your decision tree
Now, we will write a function to evaluate a decision tree by computing the classification error of the tree on the given dataset.
Again, recall that the classification error is defined as follows:
$$
\mbox{classification error} = \frac{\mbox{# mistakes}}{\mbox{# total examples}}
$$
Now, wr... | def evaluate_classification_error(tree, data):
# Apply the classify(tree, x) to each row in your data
prediction = data.apply(lambda x: classify(tree, x))
number_examples = prediction.size()
safe_loans = data['safe_loans']
classification_error = 1 - ( 1.0*(safe_loans == prediction).sum() )... | notebooks/binary-decision-tree.ipynb | leon-adams/datascience | mpl-2.0 |
Printing out a decision stump
As discussed in the lecture, we can print out a single decision stump. | def print_stump(tree, name = 'root'):
split_name = tree['splitting_feature'] # split_name is something like 'term. 36 months'
if split_name is None:
print "(leaf, label: %s)" % tree['prediction']
return None
split_feature, split_value = split_name.split('.')
print ' ... | notebooks/binary-decision-tree.ipynb | leon-adams/datascience | mpl-2.0 |
Exploring the left subtree of the left subtree | print_stump(my_decision_tree['left'], my_decision_tree['splitting_feature'])
print_stump(my_decision_tree['left']['left'], my_decision_tree['left']['splitting_feature'])
print_stump(my_decision_tree['left']['left']['left'], my_decision_tree['left']['left']['splitting_feature']) | notebooks/binary-decision-tree.ipynb | leon-adams/datascience | mpl-2.0 |
Exploring the right subtree of the left subtree | print_stump(my_decision_tree)
print_stump(my_decision_tree['right'], my_decision_tree['splitting_feature'])
print_stump(my_decision_tree['right']['right'], my_decision_tree['right']['splitting_feature']) | notebooks/binary-decision-tree.ipynb | leon-adams/datascience | mpl-2.0 |
Pandas support
After importing vaex.graphql, vaex also installs a pandas accessor, so it is also accessible for Pandas DataFrames. | df_pandas = df.to_pandas_df()
df_pandas.graphql.execute("""
{
df(where: {age: {_gt: 20}}) {
row(offset: 3, limit: 2) {
name
survived
}
}
}
"""
).data | docs/source/example_graphql.ipynb | maartenbreddels/vaex | mit |
GPUが使えるか使えないか確認
使える場合は自動的にGPU上で動かす | use_gpu = torch.cuda.is_available()
if use_gpu:
print('cuda is available!')
# MNIST Dataset (Images and Labels)
train_dataset = dsets.MNIST(root='./data',
train=True,
transform=transforms.ToTensor(),
download=True)
test_dataset ... | pytorch/180202-convolutional-neural-network.ipynb | aidiary/notebooks | mit |
最後のLinearのユニット数がわからなければ途中結果をprintしてみる
7 x 7 x 32 = 1568
GPUモードで動かすには
モデルとテンソルデータをcuda()でGPUに転送する! | model = CNN()
if use_gpu:
model.cuda()
print(model)
# テスト
model = CNN()
images, labels = iter(train_loader).next()
print(images.size())
outputs = model(Variable(images))
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate) | pytorch/180202-convolutional-neural-network.ipynb | aidiary/notebooks | mit |
BatchNormalizationを使っている場合はモデルのモードが重要
model.train() で訓練モード
model.eval() で評価モード | def train(train_loader):
model.train()
running_loss = 0
for batch_idx, (images, labels) in enumerate(train_loader):
if use_gpu:
images = Variable(images.cuda())
labels = Variable(labels.cuda())
else:
images = Variable(images)
labels = Variable(... | pytorch/180202-convolutional-neural-network.ipynb | aidiary/notebooks | mit |
cuda is available!
epoch 0, loss: 0.1666 val_loss: 0.0549 val_acc: 0.9824
epoch 1, loss: 0.0487 val_loss: 0.0372 val_acc: 0.9875
epoch 2, loss: 0.0369 val_loss: 0.0283 val_acc: 0.9905
epoch 3, loss: 0.0295 val_loss: 0.0359 val_acc: 0.9884
epoch 4, loss: 0.0247 val_loss: 0.0302 val_acc: 0.9904
epoch 5, loss: 0.0194 val_... | import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
loss_list = np.load('loss_list.npy')
val_loss_list = np.load('val_loss_list.npy')
val_acc_list = np.load('val_acc_list.npy')
# plot learning curve
plt.figure()
plt.plot(range(num_epochs), loss_list, 'r-', label='train_loss')
plt.plot(range(num_epoc... | pytorch/180202-convolutional-neural-network.ipynb | aidiary/notebooks | mit |
ほぼ最初のエポックで98%を超えるレベル
CIFAR-10
http://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html#sphx-glr-beginner-blitz-cifar10-tutorial-py | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
from torch.autograd import Variable
use_gpu = torch.cuda.is_available()
if use_gpu:
print('cuda is available!')
num_epochs = 30
batch_siz... | pytorch/180202-convolutional-neural-network.ipynb | aidiary/notebooks | mit |
データ表示テスト
http://pytorch.org/docs/master/torchvision/utils.html#torchvision.utils.make_grid | import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
def imshow(img):
# unnormalize [-1, 1] => [0, 1]
img = img / 2 + 0.5
npimg = img.numpy()
# [c, h, w] => [h, w, c]
plt.imshow(np.transpose(npimg, (1, 2, 0)))
images, labels = iter(train_loader).next()
images, labels = images[:16]... | pytorch/180202-convolutional-neural-network.ipynb | aidiary/notebooks | mit |
Import the data into H2O
Everything is scalable and distributed from now on. All processing is done on the fully multi-threaded and distributed H2O Java-based backend and can be scaled to large datasets on large compute clusters.
Here, we use a small public dataset (Titanic), but you can use datasets that are hundreds ... | ## 'path' can point to a local file, hdfs, s3, nfs, Hive, directories, etc.
df = h2o.import_file(path = "http://s3.amazonaws.com/h2o-public-test-data/smalldata/gbm_test/titanic.csv")
print(df.dim)
print(df.head)
print(df.tail)
print(df.describe)
## pick a response for the supervised problem
response = "survived"
## t... | h2o-docs/src/product/tutorials/gbm/gbmTuning.ipynb | h2oai/h2o-3 | apache-2.0 |
Establish baseline performance
As the first step, we'll build some default models to see what accuracy we can expect. Let's use the AUC metric for this demo, but you can use h2o.logloss() and stopping_metric="logloss" as well. It ranges from 0.5 for random models to 1 for perfect models.
The first model is a default GB... | #We only provide the required parameters, everything else is default
gbm = H2OGradientBoostingEstimator()
gbm.train(x=predictors, y=response, training_frame=train)
## Show a detailed model summary
print(gbm)
## Get the AUC on the validation set
perf = gbm.model_performance(valid)
print(perf.auc()) | h2o-docs/src/product/tutorials/gbm/gbmTuning.ipynb | h2oai/h2o-3 | apache-2.0 |
The AUC is 95%, so this model is highly predictive!
The second model is another default GBM, but trained on 80% of the data (here, we combine the training and validation splits to get more training data), and cross-validated using 4 folds.
Note that cross-validation takes longer and is not usually done for really large... | ## rbind() makes a copy here, so it's better to use split_frame with `ratios = c(0.8)` instead above
cv_gbm = H2OGradientBoostingEstimator(nfolds = 4, seed = 0xDECAF)
cv_gbm.train(x = predictors, y = response, training_frame = train.rbind(valid)) | h2o-docs/src/product/tutorials/gbm/gbmTuning.ipynb | h2oai/h2o-3 | apache-2.0 |
We see that the cross-validated performance is similar to the validation set performance: | ## Show a detailed summary of the cross validation metrics
## This gives you an idea of the variance between the folds
cv_summary = cv_gbm.cross_validation_metrics_summary().as_data_frame()
#print(cv_summary) ## Full summary of all metrics
#print(cv_summary.iloc[4]) ## get the row with just the AUCs
## Get the cross-v... | h2o-docs/src/product/tutorials/gbm/gbmTuning.ipynb | h2oai/h2o-3 | apache-2.0 |
This model doesn't seem to be better than the previous models: | perf_lucky = gbm_lucky.model_performance(valid)
print(perf_lucky.auc()) | h2o-docs/src/product/tutorials/gbm/gbmTuning.ipynb | h2oai/h2o-3 | apache-2.0 |
For this small dataset, dropping 20% of observations per tree seems too aggressive in terms of adding regularization. For larger datasets, this is usually not a bad idea. But we'll let this parameter tune freshly below, so no worries.
Hyper-Parameter Search
Next, we'll do real hyper-parameter optimization to see if we ... | ## Depth 10 is usually plenty of depth for most datasets, but you never know
hyper_params = {'max_depth' : list(range(1,30,2))}
#hyper_params = {max_depth = [4,6,8,12,16,20]} ##faster for larger datasets
#Build initial GBM Model
gbm_grid = H2OGradientBoostingEstimator(
## more trees is better if the learning r... | h2o-docs/src/product/tutorials/gbm/gbmTuning.ipynb | h2oai/h2o-3 | apache-2.0 |
It appears that max_depth values of 5 to 13 are best suited for this dataset, which is unusally deep! | max_depths = sorted_grid.sorted_metric_table()['max_depth'][0:5]
new_max = int(max(max_depths, key=int))
new_min = int(min(max_depths, key=int))
print("MaxDepth", new_max)
print("MinDepth", new_min) | h2o-docs/src/product/tutorials/gbm/gbmTuning.ipynb | h2oai/h2o-3 | apache-2.0 |
Now that we know a good range for max_depth, we can tune all other parameters in more detail. Since we don't know what combinations of hyper-parameters will result in the best model, we'll use random hyper-parameter search to "let the machine get luckier than a best guess of any human". | # create hyperameter and search criteria lists (ranges are inclusive..exclusive))
hyper_params_tune = {'max_depth' : list(range(new_min,new_max+1,1)),
'sample_rate': [x/100. for x in range(20,101)],
'col_sample_rate' : [x/100. for x in range(20,101)],
'col_sample_rate_per... | h2o-docs/src/product/tutorials/gbm/gbmTuning.ipynb | h2oai/h2o-3 | apache-2.0 |
We can see that the best models have even better validation AUCs than our previous best models, so the random grid search was successful! | ## Sort the grid models by AUC
sorted_final_grid = final_grid.get_grid(sort_by='auc',decreasing=True)
print(sorted_final_grid) | h2o-docs/src/product/tutorials/gbm/gbmTuning.ipynb | h2oai/h2o-3 | apache-2.0 |
You can also see the results of the grid search in Flow:
<img src="files/final_grid.png">
Model Inspection and Final Test Set Scoring
Let's see how well the best model of the grid search (as judged by validation set AUC) does on the held out test set: | #Get the best model from the list (the model name listed at the top of the table)
best_model = h2o.get_model(sorted_final_grid.sorted_metric_table()['model_ids'][0])
performance_best_model = best_model.model_performance(test)
print(performance_best_model.auc()) | h2o-docs/src/product/tutorials/gbm/gbmTuning.ipynb | h2oai/h2o-3 | apache-2.0 |
Good news. It does as well on the test set as on the validation set, so it looks like our best GBM model generalizes well to the unseen test set:
We can inspect the winning model's parameters: | params_list = []
for key, value in best_model.params.items():
params_list.append(str(key)+" = "+str(value['actual']))
params_list | h2o-docs/src/product/tutorials/gbm/gbmTuning.ipynb | h2oai/h2o-3 | apache-2.0 |
Now we can confirm that these parameters are generally sound, by building a GBM model on the whole dataset (instead of the 60%) and using internal 5-fold cross-validation (re-using all other parameters including the seed): | gbm = h2o.get_model(sorted_final_grid.sorted_metric_table()['model_ids'][0])
#get the parameters from the Random grid search model and modify them slightly
params = gbm.params
new_params = {"nfolds":5, "model_id":None, "training_frame":None, "validation_frame":None,
"response_column":None, "ignored_colum... | h2o-docs/src/product/tutorials/gbm/gbmTuning.ipynb | h2oai/h2o-3 | apache-2.0 |
It looks like the winning model performs slightly better on the validation and test sets than during cross-validation on the training set as the mean AUC on the 5 folds is estimated to be only 97.4%, but with a fairly large standard deviation of 0.9%. For small datasets, such a large variance is not unusual. To get a b... | for i in range(5):
gbm = h2o.get_model(sorted_final_grid.sorted_metric_table()['model_ids'][i])
#get the parameters from the Random grid search model and modify them slightly
params = gbm.params
new_params = {"nfolds":5, "model_id":None, "training_frame":None, "validation_frame":None,
"r... | h2o-docs/src/product/tutorials/gbm/gbmTuning.ipynb | h2oai/h2o-3 | apache-2.0 |
Note that the label (survived or not) is predicted as well (in the first predict column), and it uses the threshold with the highest F1 score (here: 0.528098) to make labels from the probabilities for survival (p1). The probability for death (p0) is given for convenience, as it is just 1-p1. | best_model.model_performance(valid)
# Key of best model:
best_model.key | h2o-docs/src/product/tutorials/gbm/gbmTuning.ipynb | h2oai/h2o-3 | apache-2.0 |
You can also see the "best" model in more detail in Flow:
<img src="files/best_gbm1.png">
<img src="files/best_gbm2.png">
The model and the predictions can be saved to file as follows: | # uncomment if you want to export the best model
# h2o.save_model(best_model, "/tmp/bestModel.csv", force=True)
# h2o.export_file(preds, "/tmp/bestPreds.csv", force=True)
# print pojo to screen, or provide path to download location
# h2o.download_pojo(best_model) | h2o-docs/src/product/tutorials/gbm/gbmTuning.ipynb | h2oai/h2o-3 | apache-2.0 |
We can bring those ensemble predictions to our Python session's memory space and use other Python packages. | from sklearn.metrics import roc_auc_score
# convert prob and test[response] h2oframes to pandas' frames and then convert them each to numpy array
np_array_prob = prob.as_data_frame().values
np_array_test = test[response].as_data_frame().values
probInPy = np_array_prob
labeInPy = np_array_test
# compare true scores (tes... | h2o-docs/src/product/tutorials/gbm/gbmTuning.ipynb | h2oai/h2o-3 | apache-2.0 |
Line plot | import pandas as pd
import random
random.seed(42)
data = []
for i in range(20):
data.append({'x': i, 'y': random.uniform(0,1), 'c': int(random.uniform(0,3))}) | multiple_simple_examples.ipynb | stitchfix/d3-jupyter-tutorial | mit |
Based on http://bl.ocks.org/d3noob/b3ff6ae1c120eea654b5 : | HTML(d3_lib.draw_graph('basic_line',{'data': data})) | multiple_simple_examples.ipynb | stitchfix/d3-jupyter-tutorial | mit |
Scatterplot with same data
Based on http://bl.ocks.org/mbostock/3887118 : | HTML(d3_lib.draw_graph('basic_scatter',{'data': data})) | multiple_simple_examples.ipynb | stitchfix/d3-jupyter-tutorial | mit |
Graph visualization
Based on http://bl.ocks.org/mbostock/4062045 | n_nodes = 30
p_edge = 0.05
graph = {"nodes": [], "links": []}
for i in range(n_nodes):
graph["nodes"].append( {"name": "i" + str(i), "group": int(random.uniform(1,11))} )
for i in range(n_nodes):
for j in range(n_nodes):
if random.uniform(0,1) < p_edge:
graph["links"].append( {"source": i, "... | multiple_simple_examples.ipynb | stitchfix/d3-jupyter-tutorial | mit |
Day-Hour heatmap
Based on http://bl.ocks.org/tjdecke/5558084 | data = []
for d in range(1,8):
for h in range(1,25):
data.append({'day': d, 'hour': h, 'value': int(random.gauss(0,100))})
HTML(d3_lib.draw_graph('day-hr-heatmap',{'data': data})) | multiple_simple_examples.ipynb | stitchfix/d3-jupyter-tutorial | mit |
Run simulation | %%bash
if [[ -z "${FAUNUS_EXECUTABLE}" ]]; then
mpirun -np 4 faunus -i input.json
else
echo "Seems we're running CTest - use Faunus target from CMake"
"${MPIEXEC}" -np 4 "${FAUNUS_EXECUTABLE}" -i input.json --nobar
fi | examples/temper/temper.ipynb | mlund/faunus | mit |
matplotlib
interactive vis notes: http://matplotlib.org/users/navigation_toolbar.html | t = arange(0.0, 1.0, 0.01)
y1 = sin(2*pi*t)
y2 = sin(2*2*pi*t)
import pandas as pd
df = pd.DataFrame({'t': t, 'y1': y1, 'y2': y2})
df.head(10)
fig = figure(1, figsize = (10,10))
ax1 = fig.add_subplot(211)
ax1.plot(t, y1)
ax1.grid(True)
ax1.set_ylim((-2, 2))
ax1.set_ylabel('Gentle Lull')
ax1.set_title('I can plot w... | notebooks/HELLO WORLD | matplotlib + seaborn + ipywidgets.ipynb | morningc/pyladies-interactive-planetary | mit |
+ seaborn | import seaborn as sns
sns.set(color_codes=True)
sns.distplot(y1)
sns.distplot(y2) | notebooks/HELLO WORLD | matplotlib + seaborn + ipywidgets.ipynb | morningc/pyladies-interactive-planetary | mit |
ipywidgets
helpful tutorial here
with matplotlib | from ipywidgets import widgets
from IPython.html.widgets import *
t = arange(0.0, 1.0, 0.01)
def pltsin(f):
plt.plot(t, sin(2*pi*t*f))
interact(pltsin, f=(1,10,0.1)) | notebooks/HELLO WORLD | matplotlib + seaborn + ipywidgets.ipynb | morningc/pyladies-interactive-planetary | mit |
with seaborn! | def pltsin(f):
sns.distplot(sin(2*pi*t*f))
interact(pltsin, f=(1,10,0.1)) | notebooks/HELLO WORLD | matplotlib + seaborn + ipywidgets.ipynb | morningc/pyladies-interactive-planetary | mit |
execfile() | # Python 2 only:
execfile('myfile.py')
# Python 2 and 3: alternative 1
from past.builtins import execfile
execfile('myfile.py')
# Python 2 and 3: alternative 2
exec(compile(open('myfile.py').read()))
# This can sometimes cause this:
# SyntaxError: function ... uses import * and bare exec ...
# See https://githu... | imported/future/docs/notebooks/.ipynb_checkpoints/Writing Python 2-3 compatible code-checkpoint.ipynb | blockstack/packaging | gpl-3.0 |
Tkinter | # Python 2 only:
import Tkinter
import Dialog
import FileDialog
import ScrolledText
import SimpleDialog
import Tix
import Tkconstants
import Tkdnd
import tkColorChooser
import tkCommonDialog
import tkFileDialog
import tkFont
import tkMessageBox
import tkSimpleDialog
# Python 2 and 3 (after ``pip install future``)... | imported/future/docs/notebooks/.ipynb_checkpoints/Writing Python 2-3 compatible code-checkpoint.ipynb | blockstack/packaging | gpl-3.0 |
Configurando a biblioteca: | sn.node_size = 3
sn.node_color = (0, 0, 0)
sn.edge_width = 1
sn.edge_color = (192, 192, 192) | encontro09.ipynb | hashiprobr/redes-sociais | gpl-3.0 |
Esse será o grafo dos professores.
Atribuindo aleatoriamente tipos negativos e positivos às arestas: | from random import random
def randomize_types(g):
for n, m in g.edges():
if random() < 0.5:
g.edges[n, m]['type'] = -1
else:
g.edges[n, m]['type'] = 1
randomize_types(g) | encontro09.ipynb | hashiprobr/redes-sociais | gpl-3.0 |
Essa distribuição uniforme modela de forma aproximada os julgamentos dos professores após o "retreat". Não vamos usar uma atribuição fixa de tipos, pois sua solução não pode ser "viciada". Ela deve ser adequada para qualquer atribuição aleatória próxima.
Convertendo tipos em cores para visualização: | def convert_types_to_colors(g):
for n, m in g.edges():
if g.edges[n, m]['type'] == -1:
g.edges[n, m]['color'] = (255, 0, 0)
else:
g.edges[n, m]['color'] = (0, 0, 255)
convert_types_to_colors(g)
sn.show_graph(g) | encontro09.ipynb | hashiprobr/redes-sociais | gpl-3.0 |
Definindo uma atualização de tipo: | from random import choice
# Essa função calcula a pressão que cada aresta sofre para mudar seu tipo,
# ou seja, a quantidade de situações de influência nas quais está envolvida.
# Se nenhuma aresta está sofrendo pressão, a função devolve False. Senão,
# uma aresta com maior pressão inverte seu tipo e a função devolve... | encontro09.ipynb | hashiprobr/redes-sociais | gpl-3.0 |
Você não precisa modificar update_type, apenas decidir quais valores de a, b e c devem ser passados.
Definindo um contador de componentes: | from queue import Queue
# Não é obrigatório entender esse código, mas eu ficarei triste se
# você não perceber que é apenas uma sequência de buscas em largura!
def count_components(g):
for n in g.nodes():
g.node[n]['label'] = 0
label = 0
q = Queue()
for s in g.nodes():
if g.node[s][... | encontro09.ipynb | hashiprobr/redes-sociais | gpl-3.0 |
Simulando várias vezes o processo no qual as arestas do grafo mudam de tipo até as pressões acabarem.
No final das simulações, o número médio de componentes é impresso.
Esse é o código que você deve modificar. Em particular, deve modificar as variáveis a, b e c. | TIMES = 100
LIMIT = 100
a = 1 # Situação A
b = 1 # Situação B
c = 1 # Situação C
# Inicializa o número médio de componentes.
mean_components = 0
for _ in range(TIMES):
# Inicializa as arestas para uma nova simulação.
randomize_types(g)
# Inicializa o contador de iterações.
iterations = 0
# Con... | encontro09.ipynb | hashiprobr/redes-sociais | gpl-3.0 |
Para ter insights sobre o que está acontecendo, não esqueça de examinar a versão animada da simulação! | def snapshot(g, frames):
convert_types_to_colors(g)
frame = sn.generate_frame(g)
frames.append(frame)
frames = []
# Inicializa as arestas para uma nova simulação.
randomize_types(g)
# Inicializa aleatoriamente as posições dos nós.
sn.randomize_positions(g)
snapshot(g, frames)
iterations = 0
# Conti... | encontro09.ipynb | hashiprobr/redes-sociais | gpl-3.0 |
Exercise 1: The Pmf object provides __add__, so you can use the + operator to compute the Pmf of the sum of two dice.
Compute and plot the Pmf of the sum of two 6-sided dice. | # Solution
thinkplot.Hist(d6+d6) | workshop/workshop01soln.ipynb | AllenDowney/ThinkBayes2 | mit |
Exercise 2: Suppose I roll two dice and tell you the result is greater than 3.
Plot the Pmf of the remaining possible outcomes and compute its mean. | # Solution
pmf = d6 + d6
pmf[2] = 0
pmf[3] = 0
pmf.Normalize()
thinkplot.Hist(pmf)
pmf.Mean() | workshop/workshop01soln.ipynb | AllenDowney/ThinkBayes2 | mit |
Exercise 3: Suppose we put the first cookie back, stir, choose again from the same bowl, and get a chocolate cookie.
Hint: The posterior (after the first cookie) becomes the prior (before the second cookie). | # Solution
cookie['Bowl 1'] *= 0.25
cookie['Bowl 2'] *= 0.5
cookie.Normalize()
cookie.Print() | workshop/workshop01soln.ipynb | AllenDowney/ThinkBayes2 | mit |
Exercise 4: Instead of doing two updates, what if we collapse the two pieces of data into one update?
Re-initialize Pmf with two equally likely hypotheses and perform one update based on two pieces of data, a vanilla cookie and a chocolate cookie.
The result should be the same regardless of how many updates you do (or ... | # Solution
cookie = Pmf(['Bowl 1', 'Bowl 2'])
cookie['Bowl 1'] *= 0.75 * 0.25
cookie['Bowl 2'] *= 0.5 * 0.5
cookie.Normalize()
cookie.Print() | workshop/workshop01soln.ipynb | AllenDowney/ThinkBayes2 | mit |
Exercise 5: We'll solve this problem two ways. First we'll do it "by hand", as we did with the cookie problem; that is, we'll multiply each hypothesis by the likelihood of the data, and then renormalize.
In the space below, update suite based on the likelihood of the data (rolling a 6), then normalize and print the re... | # Solution
pmf[4] *= 0
pmf[6] *= 1/6
pmf[8] *= 1/8
pmf[12] *= 1/12
pmf.Normalize()
pmf.Print() | workshop/workshop01soln.ipynb | AllenDowney/ThinkBayes2 | mit |
Exercise 6: Now let's do the same calculation using Suite.Update.
Write a definition for a new class called Dice that extends Suite. Then define a method called Likelihood that takes data and hypo and returns the probability of the data (the outcome of rolling the die) for a given hypothesis (number of sides on the d... | class Dice(Suite):
# hypo is the number of sides on the die
# data is the outcome
def Likelihood(self, data, hypo):
return 1
# Solution
class Dice(Suite):
# hypo is the number of sides on the die
# data is the outcome
def Likelihood(self, data, hypo):
if dat... | workshop/workshop01soln.ipynb | AllenDowney/ThinkBayes2 | mit |
Exercise 7: Suppose we see another tank with serial number 17. What effect does this have on the posterior probabilities?
Update the suite again with the new data and plot the results. | # Solution
thinkplot.Pdf(tank, color='0.7')
tank.Update(17)
thinkplot.Pdf(tank)
tank.Mean() | workshop/workshop01soln.ipynb | AllenDowney/ThinkBayes2 | mit |
The Euro problem
Exercise 8: Write a class definition for Euro, which extends Suite and defines a likelihood function that computes the probability of the data (heads or tails) for a given value of x (the probability of heads).
Note that hypo is in the range 0 to 100. Here's an outline to get you started. | class Euro(Suite):
def Likelihood(self, data, hypo):
"""
hypo is the prob of heads (0-100)
data is a string, either 'H' or 'T'
"""
return 1
# Solution
class Euro(Suite):
def Likelihood(self, data, hypo):
"""
hypo is the prob of heads (0-100)
... | workshop/workshop01soln.ipynb | AllenDowney/ThinkBayes2 | mit |
Exercise 9: Update euro1 and euro2 with the same data we used before (140 heads and 110 tails) and plot the posteriors. How big is the difference in the means? | # Solution
evidence = 'H' * 140 + 'T' * 110
for outcome in evidence:
euro1.Update(outcome)
euro2.Update(outcome)
thinkplot.Pdfs([euro1, euro2])
thinkplot.Config(title='Posteriors')
euro1.Mean(), euro2.Mean() | workshop/workshop01soln.ipynb | AllenDowney/ThinkBayes2 | mit |
Traditional Value
In this notebook, we will develop a strategy based on the "traditional value" metrics described in the Lo/Patel whitepaper. The factors employed in this strategy designate stocks as either cheap or expensive using classic fundamental analysis. The factors that Lo/Patel used are:
Dividend Yield
Price ... | # Custom Factor 1 : Dividend Yield
class Div_Yield(CustomFactor):
inputs = [Fundamentals.div_yield5_year]
window_length = 1
def compute(self, today, assets, out, d_y):
out[:] = d_y[-1] | notebooks/lectures/Case_Study_Traditional_Value_Factor/notebook.ipynb | quantopian/research_public | apache-2.0 |
While this factor could be calculated using other fundamental metrics, Fundamentals removes the need for any calculation. It is good practice to check the list of fundamentals before creating a custom factor from scratch.
We will initialize a temporary Pipeline to get a sense of the values. | # create the pipeline
temp_pipe_1 = Pipeline()
# add the factor to the pipeline
temp_pipe_1.add(Div_Yield(), 'Dividend Yield')
# run the pipeline and get data for first 5 equities
run_pipeline(temp_pipe_1, start_date = '2015-11-11', end_date = '2015-11-11').dropna().head() | notebooks/lectures/Case_Study_Traditional_Value_Factor/notebook.ipynb | quantopian/research_public | apache-2.0 |
Price to Book Value
Price to Book Value (a.k.a Price to Book Ratio) is calculated as:
$$P/B\;Ratio = \frac{Price\;per\;share}{Net\;Asset\;Value\;per\;share}$$
Net Asset Value per share can be thought of (very roughly) as a company's total assets less its total liabilities, all divided by the number of shares outstandin... | # Custom Factor 2 : P/B Ratio
class Price_to_Book(CustomFactor):
inputs = [Fundamentals.pb_ratio]
window_length = 1
def compute(self, today, assets, out, pbr):
out[:] = pbr[-1]
# create the Pipeline
temp_pipe_2 = Pipeline()
# add the factor to the Pipeline
temp_pipe_2.add(Price_to_Book(),... | notebooks/lectures/Case_Study_Traditional_Value_Factor/notebook.ipynb | quantopian/research_public | apache-2.0 |
There are two points to make about this data series.
Firstly, AA_PR's P/B Ratio is given as NaN by Pipeline. NaN stands for "not a number" and occurs when a value can not be fetched by Pipeline. Eventually, we will remove these NaN values from the dataset as they often lead to confusing errors when manipulating the da... | # Custom Factor 3 : Price to Trailing 12 Month Sales
class Price_to_TTM_Sales(CustomFactor):
inputs = [Fundamentals.ps_ratio]
window_length = 1
def compute(self, today, assets, out, ps):
out[:] = -ps[-1]
# create the pipeline
temp_pipe_3 = Pipeline()
# add the factor to the pip... | notebooks/lectures/Case_Study_Traditional_Value_Factor/notebook.ipynb | quantopian/research_public | apache-2.0 |
Price to Trailing 12-Month Cashflows
This is calculated as a simple ratio between price per share and TTM free cashflow (here using the built-in Fundamental Morningstar ratio as an approximaton).
This ratio serves a similar function to the previous two. A future notebook will explore the subtle differences in these me... | # Custom Factor 4 : Price to Trailing 12 Month Cashflow
class Price_to_TTM_Cashflows(CustomFactor):
inputs = [Fundamentals.pcf_ratio]
window_length = 1
def compute(self, today, assets, out, pcf):
out[:] = -pcf[-1]
# create the pipeline
temp_pipe_4 = Pipeline()
# add the factor to the... | notebooks/lectures/Case_Study_Traditional_Value_Factor/notebook.ipynb | quantopian/research_public | apache-2.0 |
The Full Pipeline
Now that each individual factor has been added, it is now time to get all the necessary data at once. In the algorithm, this will take place once every day.
Later in the process, we will need a factor in order to create an approximate S&P500, so we will also include another factor called SPY_proxy (SP... | # This factor creates the synthetic S&P500
class SPY_proxy(CustomFactor):
inputs = [Fundamentals.market_cap]
window_length = 1
def compute(self, today, assets, out, mc):
out[:] = mc[-1]
# Custom Factor 2 : P/B Ratio
class Price_to_Book(CustomFactor):
inputs = [Fundamentals.pb_ratio... | notebooks/lectures/Case_Study_Traditional_Value_Factor/notebook.ipynb | quantopian/research_public | apache-2.0 |
DR8b Validation
Locate the data at NERSC: | Truth = Path('/project/projectdirs/desi/target/analysis/truth/')
assert Truth.exists
release = 'dr8b'
assert (Truth / release).exists | doc/nb/qso-dr8.ipynb | desihub/desitarget | bsd-3-clause |
Define the stripe 82 footprint: | def in_stripe82(ra, dec):
ra_hr = ra * 24 / 360
return (dec > -1.26) & (dec < 1.26) & ((ra_hr > 20) | (ra_hr < 4)) | doc/nb/qso-dr8.ipynb | desihub/desitarget | bsd-3-clause |
Load a truth-matched catalog, and flag objects in stripe 82: | def load_matched(name='sdss-specObj-dr14-unique-trimmed', survey='decam', release=release):
fullname = name + '-match.fits'
path = Truth / release / survey
assert path.exists
# Why does prefix contain decals even for 90prine-mosaic? (reported this to Rongpu)
prefix = f'decals-{release}'
external... | doc/nb/qso-dr8.ipynb | desihub/desitarget | bsd-3-clause |
Load the north and south DR8b catalogs matched to DR14 objects: | DR14N, _ = load_matched(survey='90prime-mosaic')
DR14S, unmatched = load_matched(survey='decam') | doc/nb/qso-dr8.ipynb | desihub/desitarget | bsd-3-clause |
Plot densities in stripe 82 for detected DR8b objects matched to DR14 quasars: | def plot82(ra, dec):
ra[ra > 180] -= 360
rabins = np.linspace(-60, 60, 60)
decbins = np.linspace(-1.26, +1.26, 10)
density, _, _ = np.histogram2d(dec, ra, bins=(decbins, rabins))
binarea = (decbins[1] - decbins[0]) * (rabins[1] - rabins[0])
density /= binarea
plt.figure(figsize=(12, 4))
... | doc/nb/qso-dr8.ipynb | desihub/desitarget | bsd-3-clause |
Do the same plot for DR14 stripe 82 quasars that were not detected in DR8b: | QSOin82 = (unmatched['STRIPE82'] == 1)
plot82(unmatched['PLUG_RA'][QSOin82], unmatched['PLUG_DEC'][QSOin82]) | doc/nb/qso-dr8.ipynb | desihub/desitarget | bsd-3-clause |
Compare the redshift distributions of DR14 stripe 82 quasars detected or undetected in DR8b: | def plot_undetected():
# Lookup detected objects in RA 0-45 deg of stripe 82.
area = 45 * 1.26 * 2
detected = np.where(
(DR14S['CLASS'] == 'QSO ') & (DR14S['STRIPE82'] == 1) &
(DR14S['PLUG_RA'] > 0) & (DR14S['PLUG_RA'] < 45))[0]
z_detected = DR14S[detected]['Z']
# Lookup undetected... | doc/nb/qso-dr8.ipynb | desihub/desitarget | bsd-3-clause |
Save (z,ra,dec) for undetected DR14 QSOs in stripe 82 for use with http://legacysurvey.org/viewer-dev and https://yymao.github.io/decals-image-list-tool/: | undetected.write('undetected.dat', format='ascii', overwrite=True)
undetected.write('undetected.fits', overwrite=True) | doc/nb/qso-dr8.ipynb | desihub/desitarget | bsd-3-clause |
Apply the random forest selection to all truth-matched objects and prepare the random forest inputs for tests below: | def prepare(cat, r_min=17.5, r_max=22.7, south=True):
ncat = len(cat)
print(f'Input catalog has {ncat} sources.')
# Lookup TRACTOR object type and brightblob flags.
objtype = cat['TYPE']
brightstarinblob = (cat['BRIGHTBLOB'] & 2**0) != 0
# Calculate extinction-corrected fluxes and check for zero... | doc/nb/qso-dr8.ipynb | desihub/desitarget | bsd-3-clause |
Show how the redshift distribution of DR14 quasars detected in DR8b is shaped by the preselection cuts and random forest selection: | def summarize(cat, out):
zbins = np.linspace(0, 5, 50)
fig = plt.figure(figsize=(10, 5))
isQSO = cat['CLASS'] == 'QSO '
plt.hist(cat[isQSO]['Z'], bins=zbins, label='DR14 QSO in DR8b')
isQSO = out['CLASS'] == 2
plt.hist(out[isQSO]['REDSHIFT'], bins=zbins, label='Preselection')
sel = isQSO &... | doc/nb/qso-dr8.ipynb | desihub/desitarget | bsd-3-clause |
Random Forest Performance and Interpretability
Load the DR3 training data (the more recent DR7 training data is not available at nersc issue#43): | Training = Path('/global/project/projectdirs/desi/target/qso_training/')
assert Training.exists
def loadDR3():
bands = 'G', 'R', 'Z', 'W1', 'W2'
qso_mags = desitarget.train.train_mva_decals.magsExtFromFlux(
fits.open(Training / 'qso_dr3_nora36-42.fits')[1].data)
star_mags = desitarget.train.train_mv... | doc/nb/qso-dr8.ipynb | desihub/desitarget | bsd-3-clause |
Train a random forest using the same hyperparameters as desitarget.train.train_mva_decals: | gen = np.random.RandomState(seed=123)
%time fit = ensemble.RandomForestClassifier(n_estimators=200, random_state=gen, n_jobs=8).fit(X_train, y_train) | doc/nb/qso-dr8.ipynb | desihub/desitarget | bsd-3-clause |
Test on DR8b objects in stripe 82 RA 36-42, which were excluded from the training sample: | DR8b_test = (outS['STRIPE82'] == 1) & (outS['RA'] > 36) & (outS['RA'] < 42)
X_test = outS[DR8b_test][outS.colnames[:11]].to_pandas()
y_test = 1 * (outS[DR8b_test]['CLASS'] == 2) | doc/nb/qso-dr8.ipynb | desihub/desitarget | bsd-3-clause |
Display the estimated importance of each feature to the trained random forest (from shuffling each feature, to preserve 1-pt stats, and measuring score change): | importance = pd.DataFrame(
{'Feature': X_test.columns, 'Importance': fit.feature_importances_}
).sort_values(by='Importance', ascending=False)
importance.plot('Feature', 'Importance', 'barh', figsize=(10, 10), legend=False)
plt.xlabel('Feature Importance'); | doc/nb/qso-dr8.ipynb | desihub/desitarget | bsd-3-clause |
Train a smaller model that only uses the 4 most important features: | nbest = 4
best_features = importance[:nbest]['Feature']
importance[:nbest] | doc/nb/qso-dr8.ipynb | desihub/desitarget | bsd-3-clause |
Optimize hyperparameters for training a small model, using a 20% validation sample: | def optimize(max_features=(2, 3, 4), n_estimators=(10, 20, 30, 40, 50, 60, 80, 100, 150, 200), seed=123):
gen = np.random.RandomState(seed)
# Hold out a 20% validation sample for hyperparam optimization.
X_t, X_v, y_t, y_v = model_selection.train_test_split(X_train[best_features], y_train, test_size=0.2, ra... | doc/nb/qso-dr8.ipynb | desihub/desitarget | bsd-3-clause |
Train a small model with optimized hyperparameters: | gen = np.random.RandomState(seed=123)
%time small_fit = ensemble.RandomForestClassifier(n_estimators=50, max_features=2, random_state=gen, n_jobs=8).fit(X_train[best_features], y_train) | doc/nb/qso-dr8.ipynb | desihub/desitarget | bsd-3-clause |
Recalculate feature importance for the small model: | small_importance = pd.DataFrame(
{'Feature': X_test[best_features].columns, 'Importance': small_fit.feature_importances_}
).sort_values(by='Importance', ascending=False)
small_importance.plot('Feature', 'Importance', 'barh', figsize=(10, 5), legend=False)
plt.xlabel('Feature Importance'); | doc/nb/qso-dr8.ipynb | desihub/desitarget | bsd-3-clause |
Calculate the QSO probability predicted by each tree, for each test object, using both models (FULL / SMALL): | full_prob = np.array([tree.predict_proba(X_test) for tree in fit.estimators_])[:,:,1]
small_prob = np.array([tree.predict_proba(X_test[best_features]) for tree in small_fit.estimators_])[:,:,1] | doc/nb/qso-dr8.ipynb | desihub/desitarget | bsd-3-clause |
All leaf nodes in all trees (of both models) are unanimous on the classification: | np.unique(full_prob), np.unique(small_prob) | doc/nb/qso-dr8.ipynb | desihub/desitarget | bsd-3-clause |
However, the ensemble average of trees gives a probability per source. Compare the full and small models for each DR14 class: | qso_prob = np.array([full_prob.mean(axis=0), small_prob.mean(axis=0)])
def plot_test():
bins = np.linspace(0, 1, 50)
fig, axes = plt.subplots(3, 1, figsize=(12, 10))
for C, clsname in enumerate(('GALAXY', 'QSO', 'STAR')):
sel = outS[DR8b_test]['CLASS'] == C+1
for i, (name, style) in enumera... | doc/nb/qso-dr8.ipynb | desihub/desitarget | bsd-3-clause |
Plot the distribution of the 4 most important features for each DR14 source type: | def plot_features():
df = X_test[best_features].copy()
C = outS[DR8b_test]['CLASS']
df['CLASS'] = [('GALAXY', 'QSO', 'STAR')[c-1] for c in C]
sns.pairplot(df, hue='CLASS', markers='.', diag_kind='kde', size=3.5)
plot_features() | doc/nb/qso-dr8.ipynb | desihub/desitarget | bsd-3-clause |
Using FVA
The first approach we can follow is to use FVA (Flux Variability Analysis) which among many other applications, is used to detect blocked reactions. The cobra.flux_analysis.find_blocked_reactions() function will return a list of all the blocked reactions obtained using FVA. | cobra.flux_analysis.find_blocked_reactions(test_model) | documentation_builder/consistency.ipynb | opencobra/cobrapy | gpl-2.0 |
As we see above, we are able to obtain the blocked reaction, which in this case is $v_2$.
Using FASTCC
The second approach to obtaining consistent network in cobrapy is to use FASTCC. Using this method, you can expect to efficiently obtain an accurate consistent network. For more details regarding the algorithm, please... | consistent_model = cobra.flux_analysis.fastcc(test_model)
consistent_model.reactions | documentation_builder/consistency.ipynb | opencobra/cobrapy | gpl-2.0 |
SPA output | tus = Location(32.2, -111, 'US/Arizona', 700, 'Tucson')
print(tus)
golden = Location(39.742476, -105.1786, 'America/Denver', 1830, 'Golden')
print(golden)
golden_mst = Location(39.742476, -105.1786, 'MST', 1830, 'Golden MST')
print(golden_mst)
berlin = Location(52.5167, 13.3833, 'Europe/Berlin', 34, 'Berlin')
print(ber... | docs/tutorials/solarposition.ipynb | cwhanse/pvlib-python | bsd-3-clause |
Speed tests | times = pd.date_range(start='20180601', freq='1min', periods=14400)
times_loc = times.tz_localize(loc.tz)
%%timeit
# NBVAL_SKIP
pyephemout = pvlib.solarposition.pyephem(times_loc, loc.latitude, loc.longitude)
#ephemout = pvlib.solarposition.ephemeris(times, loc)
%%timeit
# NBVAL_SKIP
#pyephemout = pvlib.solarpositi... | docs/tutorials/solarposition.ipynb | cwhanse/pvlib-python | bsd-3-clause |
This numba test will only work properly if you have installed numba. | %%timeit
# NBVAL_SKIP
#pyephemout = pvlib.solarposition.pyephem(times, loc)
ephemout = pvlib.solarposition.get_solarposition(times_loc, loc.latitude, loc.longitude,
method='nrel_numba') | docs/tutorials/solarposition.ipynb | cwhanse/pvlib-python | bsd-3-clause |
The numba calculation takes a long time the first time that it's run because it uses LLVM to compile the Python code to machine code. After that it's about 4-10 times faster depending on your machine. You can pass a numthreads argument to this function. The optimum numthreads depends on your machine and is equal to 4 b... | %%timeit
# NBVAL_SKIP
#pyephemout = pvlib.solarposition.pyephem(times, loc)
ephemout = pvlib.solarposition.get_solarposition(times_loc, loc.latitude, loc.longitude,
method='nrel_numba', numthreads=16)
%%timeit
# NBVAL_SKIP
ephemout = pvlib.solarposition.spa_python(tim... | docs/tutorials/solarposition.ipynb | cwhanse/pvlib-python | bsd-3-clause |
<span style="color:red">
The last value appears to be noise.</span>.
<span style="color:red">
I am not sure what is up with the first peak but I know it is not the peak of interest, which is around index 2000 to 2500.</span>.
<span style="color:red">
Right now I am not sure how to determinine that the range of the pe... | #x = findPeak(summed, (2000, 2500))
[x for x in range(len(csv)) if np.max(csv[x][2000:2500]) > 7.5]
samp = summed[2000:2500]
mu = np.mean(samp)
sig = np.std(samp)
print(mu, sig)
#plt.plot(samp)
def func(x, a, m, s, c):
return a * np.exp(-(x - m)**2 / (2 * s**2)) + c
xdata = range(0,len(samp)) ... | calibration/Untitled.ipynb | bearing/dosenet-analysis | mit |
Find the channel# of the peak | fit = func(xdata, *popt)
channel = np.argmax(fit)
print("The channel number is", channel,"and its values is", np.max(fit))
plt.plot(xdata,samp)
plt.plot(xdata,func(xdata, *popt))
plt.plot(channel, np.max(fit), 'ro')
plt.show()
print(int(popt[1] + 2000)) | calibration/Untitled.ipynb | bearing/dosenet-analysis | mit |
The End.
Everything below here is no longer relevant____
Okay but all of that was cheating and I need to use the summed plot to find the width of the peak.
Then the plan is to take the highest value within that range and find the channel it corresponds to.
I think i will start by disregarding the first peak and only l... | snipped = summed.copy()
snipped[-1] = 0
snipped[:1000] = np.mean(summed)/5
plt.plot(snipped)
plt.show()
plt.plot(summed)
plt.show()
print(np.std(snipped), np.std(summed))
| calibration/Untitled.ipynb | bearing/dosenet-analysis | mit |
Okay so the plan for finding the peak will be to look for points above the standard deviation and to see if 9/10(arbitrary value) of the values in between are greater than the STD. | def peakFinder(data):
std = np.std(data)
points = []
for x in range(len(data)):
if data[x] == int(std):
points = points + [x]
for p in range(len(points) - 1):
data[points[p]:
return peak
peakFinder(snipped) | calibration/Untitled.ipynb | bearing/dosenet-analysis | mit |
Below is random code I wrote that turned out to be useless | # This indexHelper helps me avoid array index out of bound errors
def indexHelper(i, top, up):
if i <= 0 or i >= top - 1:
return 0
elif up:
return i+1
else:
return i-1
... | calibration/Untitled.ipynb | bearing/dosenet-analysis | mit |
Types Matter
Python's built in functions and operators work differently depending on the type of the variable.: | a = 4
b = 5
a + b # this plus in this case means add so 9
a = "4"
b = "5"
a + b # the plus + in this case means concatenation, so '45' | content/lessons/02-Variables/LAB-Variables.ipynb | IST256/learn-python | mit |
Switching Types
there are built-in Python functions for switching types. For example: | x = "45" # x is a str
y = int(x) # y is now an int
z = float(x) # z is a float
print(x,y,z) | content/lessons/02-Variables/LAB-Variables.ipynb | IST256/learn-python | mit |
Inputs type str
When you use the input() function the result is of type str: | age = input("Enter your age: ")
type(age) | content/lessons/02-Variables/LAB-Variables.ipynb | IST256/learn-python | mit |
We can use a built in Python function to convert the type from str to our desired type: | age = input("Enter your age: ")
age = int(age)
type(age) | content/lessons/02-Variables/LAB-Variables.ipynb | IST256/learn-python | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.