markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
A cool feature of GanjaScene is the ability to use + to draw both scenes together: | draw(sc + sc_refl, sig=layout.sig, scale=0.5) | docs/tutorials/cga/visualization-tools.ipynb | arsenovic/clifford | bsd-3-clause |
mpl_toolkits.clifford
While ganja.js produces great diagrams, it's hard to combine them with other plotting tools.
mpl_toolkits.clifford works within matplotlib. | from matplotlib import pyplot as plt
plt.ioff() # we'll ask for plotting when we want it
# if you're editing this locally, you'll get an interactive UI if you uncomment the following
#
# %matplotlib notebook
from mpl_toolkits.clifford import plot
import mpl_toolkits.clifford; mpl_toolkits.clifford.__version__ | docs/tutorials/cga/visualization-tools.ipynb | arsenovic/clifford | bsd-3-clause |
Assembling the plot is a lot more work, but we also get much more control: | # standard matplotlib stuff - construct empty plots side-by-side, and set the scaling
fig, (ax_before, ax_both) = plt.subplots(1, 2, sharex=True, sharey=True)
ax_before.set(xlim=[-4, 4], ylim=[-4, 4], aspect='equal')
ax_both.set(xlim=[-4, 4], ylim=[-4, 4], aspect='equal')
# plot the objects before reflection on both p... | docs/tutorials/cga/visualization-tools.ipynb | arsenovic/clifford | bsd-3-clause |
G3C
Let's repeat the above, but with 3D Conformal Geometric Algebra.
Note that if you're viewing these docs in a jupyter notebook, the lines below will replace all your 2d variables with 3d ones | from clifford.g3c import *
point = up(2*e1+e2)
line = up(3*e1 + 2*e2) ^ up(3*e1 - 2*e2) ^ einf
circle = up(e1) ^ up(-e1 + 1.6*e2 + 1.2*e3) ^ up(-e1 - 1.6*e2 - 1.2*e3)
sphere = up(3*e1) ^ up(e1) ^ up(2*e1 + e2) ^ up(2*e1 + e3)
# note that due to floating point rounding, we need to truncate back to a single grade here,... | docs/tutorials/cga/visualization-tools.ipynb | arsenovic/clifford | bsd-3-clause |
pyganja
Once again, we can create a pair of scenes exactly as before | sc = GanjaScene()
sc.add_object(point, color=(255, 0, 0), label='point')
sc.add_object(line, color=(0, 255, 0), label='line')
sc.add_object(circle, color=(0, 0, 255), label='circle')
sc.add_object(sphere, color=(0, 255, 255), label='sphere')
sc_refl = GanjaScene()
sc_refl.add_object(point_refl, color=(128, 0, 0), labe... | docs/tutorials/cga/visualization-tools.ipynb | arsenovic/clifford | bsd-3-clause |
But this time, when we draw them we don't need to pass sig.
Better yet, we can rotate the 3D world around using left click, pan with right click, and zoom with the scroll wheel. | draw(sc + sc_refl, scale=0.5) | docs/tutorials/cga/visualization-tools.ipynb | arsenovic/clifford | bsd-3-clause |
Some more example of using pyganja to visualize 3D CGA can be found in the interpolation and clustering notebooks.
mpl_toolkits.clifford
The 3D approach for matplotlib is much the same.
Note that due to poor handling of rounding errors in clifford.tools.classify, a call to .normal() is needed.
Along with explicit grade... | # standard matplotlib stuff - construct empty plots side-by-side, and set the scaling
fig, (ax_before, ax_both) = plt.subplots(1, 2, subplot_kw=dict(projection='3d'), figsize=(8, 4))
ax_before.set(xlim=[-4, 4], ylim=[-4, 4], zlim=[-4, 4])
ax_both.set(xlim=[-4, 4], ylim=[-4, 4], zlim=[-4, 4])
# plot the objects before ... | docs/tutorials/cga/visualization-tools.ipynb | arsenovic/clifford | bsd-3-clause |
Export epochs to Pandas DataFrame
In this example the pandas exporter will be used to produce a DataFrame
object. After exploring some basic features a split-apply-combine
work flow will be conducted to examine the latencies of the response
maxima across epochs and conditions.
Note. Equivalent methods are available for... | # Author: Denis Engemann <denis.engemann@gmail.com>
#
# License: BSD (3-clause)
import mne
import matplotlib.pyplot as plt
import numpy as np
from mne.datasets import sample
print(__doc__)
data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
event_fname = data_path + '... | 0.15/_downloads/plot_epochs_to_data_frame.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Explore the Data
The dataset is broken into batches to prevent your machine from running out of memory. The CIFAR-10 dataset consists of 5 batches, named data_batch_1, data_batch_2, etc.. Each batch contains the labels and images that are one of the following:
* airplane
* automobile
* bird
* cat
* deer
* dog
* frog
*... | %matplotlib inline
%config InlineBackend.figure_format = 'retina'
import helper
import numpy as np
# Explore the dataset
batch_id = 2
sample_id = 18
helper.display_stats(cifar10_dataset_folder_path, batch_id, sample_id) | Deep_learning_ND/dlnd_image_classification.ipynb | sarathid/Learning | gpl-3.0 |
Implement Preprocess Functions
Normalize
In the cell below, implement the normalize function to take in image data, x, and return it as a normalized Numpy array. The values should be in the range of 0 to 1, inclusive. The return object should be the same shape as x. | def normalize(x):
"""
Normalize a list of sample image data in the range of 0 to 1
: x: List of image data. The image shape is (32, 32, 3)
: return: Numpy array of normalize data
"""
# TODO: Implement Function
# print(x[0][0][0])
z = x/255.0
# print(z[0][0][0])
return z
"""
DO... | Deep_learning_ND/dlnd_image_classification.ipynb | sarathid/Learning | gpl-3.0 |
One-hot encode
Just like the previous code cell, you'll be implementing a function for preprocessing. This time, you'll implement the one_hot_encode function. The input, x, are a list of labels. Implement the function to return the list of labels as One-Hot encoded Numpy array. The possible values for labels are 0 t... | def one_hot_encode(x):
"""
One hot encode a list of sample labels. Return a one-hot encoded vector for each label.
: x: List of sample Labels
: return: Numpy array of one-hot encoded labels
"""
# TODO: Implement Function
# print(x.shape)
# print(x[:10])
# print(np.eye(10)[x[:10]])
... | Deep_learning_ND/dlnd_image_classification.ipynb | sarathid/Learning | gpl-3.0 |
Build the network
For the neural network, you'll build each layer into a function. Most of the code you've seen has been outside of functions. To test your code more thoroughly, we require that you put each layer in a function. This allows us to give you better feedback and test for simple mistakes using our unittest... | import tensorflow as tf
def neural_net_image_input(image_shape):
"""
Return a Tensor for a batch of image input
: image_shape: Shape of the images
: return: Tensor for image input.
"""
# TODO: Implement Function
shape = (None, image_shape[0], image_shape[1], image_shape[2])
return tf.pl... | Deep_learning_ND/dlnd_image_classification.ipynb | sarathid/Learning | gpl-3.0 |
Convolution and Max Pooling Layer
Convolution layers have a lot of success with images. For this code cell, you should implement the function conv2d_maxpool to apply convolution then max pooling:
* Create the weight and bias using conv_ksize, conv_num_outputs and the shape of x_tensor.
* Apply a convolution to x_tensor... | def conv2d_maxpool(x_tensor, conv_num_outputs, conv_ksize, conv_strides, pool_ksize, pool_strides):
"""
Apply convolution then max pooling to x_tensor
:param x_tensor: TensorFlow Tensor
:param conv_num_outputs: Number of outputs for the convolutional layer
:param conv_ksize: kernal size 2-D Tuple fo... | Deep_learning_ND/dlnd_image_classification.ipynb | sarathid/Learning | gpl-3.0 |
Flatten Layer
Implement the flatten function to change the dimension of x_tensor from a 4-D tensor to a 2-D tensor. The output should be the shape (Batch Size, Flattened Image Size). Shortcut option: you can use classes from the TensorFlow Layers or TensorFlow Layers (contrib) packages for this layer. For more of a ch... | def flatten(x_tensor):
"""
Flatten x_tensor to (Batch Size, Flattened Image Size)
: x_tensor: A tensor of size (Batch Size, ...), where ... are the image dimensions.
: return: A tensor of size (Batch Size, Flattened Image Size).
"""
# TODO: Implement Function
# print(x_tensor.shape)
flat... | Deep_learning_ND/dlnd_image_classification.ipynb | sarathid/Learning | gpl-3.0 |
Output Layer
Implement the output function to apply a fully connected layer to x_tensor with the shape (Batch Size, num_outputs). Shortcut option: you can use classes from the TensorFlow Layers or TensorFlow Layers (contrib) packages for this layer. For more of a challenge, only use other TensorFlow packages.
Note: Act... | def output(x_tensor, num_outputs):
"""
Apply a output layer to x_tensor using weight and bias
: x_tensor: A 2-D tensor where the first dimension is batch size.
: num_outputs: The number of output that the new tensor should be.
: return: A 2-D tensor where the second dimension is num_outputs.
"""... | Deep_learning_ND/dlnd_image_classification.ipynb | sarathid/Learning | gpl-3.0 |
Create Convolutional Model
Implement the function conv_net to create a convolutional neural network model. The function takes in a batch of images, x, and outputs logits. Use the layers you created above to create this model:
Apply 1, 2, or 3 Convolution and Max Pool layers
Apply a Flatten Layer
Apply 1, 2, or 3 Full... | def conv_net(x, keep_prob):
"""
Create a convolutional neural network model
: x: Placeholder tensor that holds image data.
: keep_prob: Placeholder tensor that hold dropout keep probability.
: return: Tensor that represents logits
"""
# TODO: Apply 1, 2, or 3 Convolution and Max Pool layers
... | Deep_learning_ND/dlnd_image_classification.ipynb | sarathid/Learning | gpl-3.0 |
Show Stats
Implement the function print_stats to print loss and validation accuracy. Use the global variables valid_features and valid_labels to calculate validation accuracy. Use a keep probability of 1.0 to calculate the loss and validation accuracy. | def print_stats(session, feature_batch, label_batch, cost, accuracy):
"""
Print information about loss and validation accuracy
: session: Current TensorFlow session
: feature_batch: Batch of Numpy image data
: label_batch: Batch of Numpy label data
: cost: TensorFlow cost function
: accuracy... | Deep_learning_ND/dlnd_image_classification.ipynb | sarathid/Learning | gpl-3.0 |
Hyperparameters
Tune the following parameters:
* Set epochs to the number of iterations until the network stops learning or start overfitting
* Set batch_size to the highest number that your machine has memory for. Most people set them to common sizes of memory:
* 64
* 128
* 256
* ...
* Set keep_probability to the... | # TODO: Tune Parameters
epochs = 10
batch_size = 64
keep_probability = 0.5 | Deep_learning_ND/dlnd_image_classification.ipynb | sarathid/Learning | gpl-3.0 |
Es ist also sehr einfach in Python diese Funktion zu programmieren.Das hat aber nichts mit Machine Learning zu tun, sondern das ist das klassische Programmier Paradigma:<br>
- es gibt eine Regel
- es gibt einen Input
- der Algorithmus erzeugt einen Output<br>
Dieses Prinzip wird häufig auch EVA genannt - Eingabe/Verarb... | # Importieren Sie numpy as np
import numpy as np
# Importieren Sie tensorflow as tf
# Import des Modells Sequential
# from keras.models import Sequential
# Import des Dense Layers
# from keras.layers import Dense
# importieren Sie matplotlib.pyplot as plt
# Setzen Sie den magic Befehl: %matplotlib inline
# Üb... | 20-10-14-ml-workcamp/wc-arbeiten-tf-11-aufgabe.ipynb | mediagit2016/workcamp-maschinelles-lernen-grundlagen | gpl-3.0 |
<h2> Aufsetzen des Neuronalen Netzes als nn</h2> | # Initialisieren Sie ein Neuronales Netz nn mit Sequential()
# nn = Sequential()
# Fügen Sie einen Dense Layer mit einem Neuron hinzu, (units=1,input_dim=1)
#
# Wieviel Parameter hat dieser Layer ?
#
# nn.add(Dense(units=1, input_dim=1))
# Wir wollen den adam optimizer mit einer bestimmten Lernrate einsetzen
# mit... | 20-10-14-ml-workcamp/wc-arbeiten-tf-11-aufgabe.ipynb | mediagit2016/workcamp-maschinelles-lernen-grundlagen | gpl-3.0 |
<h2>Vorhersage von Werten</h2> | # Vorhersage für den Wert 100.0
ergebnis = nn.predict([#Wert#])
print(ergebnis)
# Vorhersage für den Wert 85.5
ergebnis = nn.predict([#Wert#])
print(ergebnis) | 20-10-14-ml-workcamp/wc-arbeiten-tf-11-aufgabe.ipynb | mediagit2016/workcamp-maschinelles-lernen-grundlagen | gpl-3.0 |
<h3 style="color:orange; font-weight:bold;">Dies ist doch ein erstaunliches Ergebnis, oder ?</h3>
Wir wollen deshalb einmal überprüfen welche Werte in diesem einen<br>
Layer gelernt wurden.
<h2>Auslesen der gelernten Parameter</h2> | # Ausgabe der Layer Parameter die gelernt wurden
print("Dies sind die Layer Variablen: {}".format(nn.get_weights()))
# erwartetes Ergebnis [1.8, 32] | 20-10-14-ml-workcamp/wc-arbeiten-tf-11-aufgabe.ipynb | mediagit2016/workcamp-maschinelles-lernen-grundlagen | gpl-3.0 |
In diesem Single Layer Neuronalen Netz lässt sich die Formel<br>
für die Umrechnung also exakt nachbilden und die Parameter werden gelernt.<br>
<br>
Wie sieht das aber aus, wenn wir eine andere Struktur des Neuronalen Netzes wählen ?<br>
<h2>Erweiterung des Neuronalen Netzes nn2</h2> | # Initialisieren des Neuronalen Netzes nn2
# nn2=Sequential()
#
# Hinufügen der Layer (Vergabe von Namen)
#
# nn2.add(Dense(units=4, input_dim=1, name='a'))
# nn2.add(Dense(units=4, name='b'))
# nn2.add(Dense(units=1, name='c'))
# Überlegung:
# Wieviel Parameter hat Layer a ?
# Wieviel Parameter hat Layer b ?
# Wievi... | 20-10-14-ml-workcamp/wc-arbeiten-tf-11-aufgabe.ipynb | mediagit2016/workcamp-maschinelles-lernen-grundlagen | gpl-3.0 |
<h2> Vorhersage von Werten</h2> | # Vorhersage für den Wert 100.0
ergebnis = nn2.predict([#Wert#])
print(ergebnis)
# Vorhersage für den Wert 85.5
ergebnis = nn2.predict([#Wert#])
print(ergebnis) | 20-10-14-ml-workcamp/wc-arbeiten-tf-11-aufgabe.ipynb | mediagit2016/workcamp-maschinelles-lernen-grundlagen | gpl-3.0 |
<h3 style="color:orange;">Dieses Modell liefert also nahezu identische Vorhersagewerte</h3> | print("Model nn2 ermittelt, dass 100 Grad Celsius: {} Grad Fahrenheit sind.".format(nn2.predict([100.0])))
| 20-10-14-ml-workcamp/wc-arbeiten-tf-11-aufgabe.ipynb | mediagit2016/workcamp-maschinelles-lernen-grundlagen | gpl-3.0 |
Wie sehen aber die Parameter in den Layern aus ? | # Ausgabe der Layer
# nn2.layers
nn2.layers | 20-10-14-ml-workcamp/wc-arbeiten-tf-11-aufgabe.ipynb | mediagit2016/workcamp-maschinelles-lernen-grundlagen | gpl-3.0 |
Alle Parameter eines Layers können über Ihre Methoden<br>
get_weights()<br>
set_weights()<br>
angesprochen werden.
Für einen Dense Layer gehören dazu sowohl die <br>
Gewichte wie auch die Bias Werte.<br>
<br>
Wir lesen die Werte der Layer in die Variablen input1, input2 und input3<br>
aus. Die Layer haben dabei die Ind... | # Auslesen der Layer 1-3 in Variablen - Index 0-2
input1 = nn2.layers[0]
input2 = nn2.layers[1]
input3 = nn2.layers[2]
# Einlesen der Gewichte und Bias Werte aus Layer a h hat den Index 0
weights, biases = input1.get_weights()
# Ausgabe der Gewichte in Layer a
weights
# Aus gabe der Bias Werte in Layer a
biases | 20-10-14-ml-workcamp/wc-arbeiten-tf-11-aufgabe.ipynb | mediagit2016/workcamp-maschinelles-lernen-grundlagen | gpl-3.0 |
<h2>Auslesen der Werte für Layer b</h2> | # Einlesen der Gewichte und Bias Werte aus Layer b - hat den Index 1
# und wurde in die Variable input2 ausgelesen
weights1, biases1 = input2.get_weights()
# Ausgabe der Gewichte in Layer b
weights1
# Aus gabe der Bias Werte in Layer b
biases1 | 20-10-14-ml-workcamp/wc-arbeiten-tf-11-aufgabe.ipynb | mediagit2016/workcamp-maschinelles-lernen-grundlagen | gpl-3.0 |
<h2>Auslesen der Werte für Layer c</h2> | # Einlesen der Gewichte und Bias Werte aus Layer c - hat den Index 2 und
# wurde in die Variable input3 ausgelesen
weights2, biases2 = input3.get_weights()
# Ausgabe der Gewichte in Layer c
weights2
# Aus gabe der Bias Werte in Layer b
biases2
print("Das sind die Parameter in Layer a: {}".format(input1.get_weights()... | 20-10-14-ml-workcamp/wc-arbeiten-tf-11-aufgabe.ipynb | mediagit2016/workcamp-maschinelles-lernen-grundlagen | gpl-3.0 |
<h2>Aufsetzen eines Neuronalen Netzes nn3 und Überprüfen
der Parameter vor und nach dem Training</h2> | # Initialisierung des Modells nn3 als Sequential
# nn3 = Sequential()
# Hinzufügen der Layer
#nn3.add(Dense(units=16, input_dim=1))
#nn3.add(Dense(units=8))
#nn3.add(Dense(units=1))
#
# Überprüfen Sie gedanklich einmal die Parameter
#
# Überprüfen der Konfiguration
# nn3.summary()
# Definieren des optimizers mi... | 20-10-14-ml-workcamp/wc-arbeiten-tf-11-aufgabe.ipynb | mediagit2016/workcamp-maschinelles-lernen-grundlagen | gpl-3.0 |
Warum stehen da Werte ? Warum sind die Bias Werte 0 ? | print("Das sind die Parameter in Layer 1: {}".format(inp2.get_weights()))
print("Das sind die Parameter in Layer 2: {}".format(inp3.get_weights()))
# Trainieren Sie das Modell nn2 mit 800 epochs
epoch_num = #Wert#
history = nn3.fit(celsius_i,fahrenheit_o,epochs=epoch_num, verbose=1 )
print("Das Training ist beendet")... | 20-10-14-ml-workcamp/wc-arbeiten-tf-11-aufgabe.ipynb | mediagit2016/workcamp-maschinelles-lernen-grundlagen | gpl-3.0 |
Time to build the network
Below you'll build your network. We've built out the structure and the backwards pass. You'll implement the forward pass through the network. You'll also set the hyperparameters: the learning rate, the number of hidden units, and the number of training passes.
<img src="assets/neural_network.p... | #############
# In the my_answers.py file, fill out the TODO sections as specified
#############
from my_answers import NeuralNetwork
def MSE(y, Y):
return np.mean((y-Y)**2) | first-neural-network/Your_first_neural_network.ipynb | fnakashima/deep-learning | mit |
Unfortunately, making the queries directly in django is complicated and it takes a long time to run. Instead, we query directly the database using postico and export the results to csv for further processing.
PostgreSQL command
You can use the following sql command to retrieve the data corresponding to one day.
SELECT
... | def strip_id(s):
try:
index = s.index(':')
except ValueError:
index = len(s)
return s[:index]
columns = [
'agency_id',
'service_date_id', 'service_date_date',
'route_id', 'route_short_name', 'route_long_name',
'trip_id', 'trip_headsign', 'trip_short_name',
'stop_time_id... | preprocessing/process_csv.ipynb | tOverney/ADA-Project | apache-2.0 |
We process the CSV to stem the stop_id as they are currently not in the official form. The geops dataset add a suffix to each stop_id if they correspond to differente route. | dates = ['2017-01-30','2017-01-31','2017-02-01','2017-02-02','2017-02-03','2017-02-04','2017-02-05']
for date in dates:
file = in_dir + date + '.csv'
df = pd.read_csv(file)
df.columns = columns
df['stop_stop_id'] = df['stop_stop_id'].apply(lambda x: strip_id(x))
df.to_csv(out_dir + date ... | preprocessing/process_csv.ipynb | tOverney/ADA-Project | apache-2.0 |
Load data
To download data go to https://map.ox.ac.uk/explorer/#/ and select the layer Plasmodium falciparum parasite rate in 2-10 year olds in Africa and click download. Select the zip file option. You should then have a zip file called 2015_Nature_Africa_PR.2000.zip.
Unzip the folder and enter the folder location bel... | import os
import pandas as pd
data_folder_location = '~/Downloads/2015_Nature_Africa_PR.2000/'
name_lf = '2015_Nature_Africa_PR.2005.tif'
name_hf = '2015_Nature_Africa_PR.2015.tif'
if not os.path.exists(name_lf[:-3] + 'csv'):
import georaster
def get_map_as_df(path):
my_image = georaster.SingleBandRas... | emukit/examples/multi_fidelity_dgp/malaria_data_example.ipynb | EmuKit/emukit | apache-2.0 |
Change paths to where your data is stored | import scipy.special
# Discard points where we have no data
lf_valid = lf_data.value > 0
hf_valid = hf_data.value > 0
y_lf = lf_data.value.values[lf_valid, None]
y_hf = hf_data.value.values[hf_valid, None]
# Transform data so it lies on real line
y_lf_transformed = scipy.special.logit(y_lf)
y_hf_transformed = scipy.... | emukit/examples/multi_fidelity_dgp/malaria_data_example.ipynb | EmuKit/emukit | apache-2.0 |
Initialze inducing points to a subset of the data | i_z = np.random.choice(x_lf.shape[0], 1000, replace=False)
z_low = x_lf[i_z, :]
i_z_low = np.random.choice(x_lf.shape[0], 1000, replace=False)
z_high = np.concatenate([x_lf[i_z_low, :], y_lf_transformed[i_z_low, :]], axis=1)
dgp = make_dgpMF_model([x_lf, x_hf_train], [y_lf_transformed, y_hf_train], [z_low, z_high]) | emukit/examples/multi_fidelity_dgp/malaria_data_example.ipynb | EmuKit/emukit | apache-2.0 |
Training loop + some printing | class PrintAction(Action):
def __init__(self, model, text):
self.model = model
self.text = text
def run(self, ctx):
if ctx.iteration % 500 == 0:
likelihood = ctx.session.run(self.model.likelihood_tensor)
objective = ctx.session.run(self.model.objective)
... | emukit/examples/multi_fidelity_dgp/malaria_data_example.ipynb | EmuKit/emukit | apache-2.0 |
Test against a subset of high fidelity data | n_test = 10000
idxs = np.arange(0, y_hf.shape[0])
idxs_minus_train = np.array(list(set(idxs) - set(i_train)))
np.random.seed(123)
i_test = np.random.choice(idxs_minus_train, n_test, replace=False)
x_test = x_hf[i_test, :]
y_test = y_hf[i_test, :]
import scipy
# batch predict
batch_size = 1000
n_batches = int(np.ceil(... | emukit/examples/multi_fidelity_dgp/malaria_data_example.ipynb | EmuKit/emukit | apache-2.0 |
Importing from HDF5
The openmc.data module can read OpenMC's HDF5-formatted data into Python objects. The easiest way to do this is with the openmc.data.IncidentNeutron.from_hdf5(...) factory method. Replace the filename variable below with a valid path to an HDF5 data file on your computer. | # Get filename for Gd-157
filename ='/home/romano/openmc/scripts/nndc_hdf5/Gd157.h5'
# Load HDF5 data into object
gd157 = openmc.data.IncidentNeutron.from_hdf5(filename)
gd157 | docs/source/pythonapi/examples/nuclear-data.ipynb | samuelshaner/openmc | mit |
There is also summed_reactions attribute for cross sections (like total) which are built from summing up other cross sections. | pprint(list(gd157.summed_reactions.values())) | docs/source/pythonapi/examples/nuclear-data.ipynb | samuelshaner/openmc | mit |
Note that the cross sections for these reactions are represented by the Sum class rather than Tabulated1D. They do not support the x and y attributes. | gd157[27].xs | docs/source/pythonapi/examples/nuclear-data.ipynb | samuelshaner/openmc | mit |
Converting ACE to HDF5
The openmc.data package can also read ACE files and output HDF5 files. ACE files can be read with the openmc.data.IncidentNeutron.from_ace(...) factory method. | filename = '/opt/data/ace/nndc/293.6K/Gd_157_293.6K.ace'
gd157_ace = openmc.data.IncidentNeutron.from_ace(filename)
gd157_ace | docs/source/pythonapi/examples/nuclear-data.ipynb | samuelshaner/openmc | mit |
We can store this formerly ACE data as HDF5 with the export_to_hdf5() method. | gd157_ace.export_to_hdf5('gd157.h5', 'w') | docs/source/pythonapi/examples/nuclear-data.ipynb | samuelshaner/openmc | mit |
With few exceptions, the HDF5 file encodes the same data as the ACE file. | gd157_reconstructed = openmc.data.IncidentNeutron.from_hdf5('gd157.h5')
gd157_ace[16].xs['294K'].y - gd157_reconstructed[16].xs['294K'].y | docs/source/pythonapi/examples/nuclear-data.ipynb | samuelshaner/openmc | mit |
0. Motivation
The typical economics graduate student places great faith in the analytical mathematical tools that he or she was taught as an undergraduate. In particular this student is likely under the impression that virtually all economic models have closed-form solutions. At best the typical student believes that i... | import pypwt
pwt = pypwt.load_pwt_data()
fig, ax = plt.subplots(1, 1, figsize=(8,6))
for ctry in pwt.major_axis:
tmp_data = pwt.major_xs(ctry)
tmp_data.labsh.plot(color='gray', alpha=0.5)
# plot some specific countries
pwt.major_xs('USA').labsh.plot(color='blue', ax=ax, label='USA')
pwt.major_xs('IND').l... | examples/0 Motivation.ipynb | solowPy/solowPy | mit |
From the above figure it is clear that the prediction of constant factor shares is strongly at odds with the empirical data for most countries. Labor's share of real GDP has been declining, on average, for much of the post-war period. For many countries, such as India, China, and South Korea, the fall in labor's share ... | solowpy.Model? | examples/0 Motivation.ipynb | solowPy/solowPy | mit |
More details on on how to create instances of the solow.Model class can be found in the Getting started notebook in the solowPy repository.
2. Finding the steady state
Traditionally, most analysis of the Solow model focuses almost excusively on the long run steady state of the model. Recall that the steady state of the... | solowpy.Model.find_steady_state?
k_star, result = ces_model.find_steady_state(1e-6, 1e6, method='bisect', full_output=True)
print("The steady-state value is {}".format(k_star))
print("Did the bisection algorithm coverge? {}".format(result.converged)) | examples/0 Motivation.ipynb | solowPy/solowPy | mit |
More details on on how to the various methods of the solow.Model class for finding the model's steady state can be found in the accompanying Finding the steady state notebook in the solowPy repository.
3. Graphical analysis using Matplotlib and IPython widgets
Graphical analysis is an important pedagogic and research t... | fig, ax = plt.subplots(1, 1, figsize=(8,6))
ces_model.plot_solow_diagram(ax)
fig.show() | examples/0 Motivation.ipynb | solowPy/solowPy | mit |
There are number of additional plotting methods available (all of which can be turned into interactive plots using IPython widgets). See the Graphical analysis notebook in the solowPy repository.
4. Solving the Solow model
Solving the Solow model requires efficiently and accurately approximating the solution to a non-l... | ces_model.ivp? | examples/0 Motivation.ipynb | solowPy/solowPy | mit |
Finite-difference methods only return a discrete approximation to the continuous function $k(t)$. To get a continouous approximation of the solution we can combined finite-difference methods with B-spline interpolation using the interpolate method of the ivp attribute. | ces_model.ivp.interpolate?
# interpolate!
ti = np.linspace(0, 100, 1000)
interpolated_soln = ces_model.ivp.interpolate(numeric_soln, ti, k=3) | examples/0 Motivation.ipynb | solowPy/solowPy | mit |
Accuracy of our numerical methods
When doing numerical work it is important to understand the accuracy of the methods that you are using to approximate the solution to your model. Typically one assesses the accuracy of a solution method by computing and evaluatin some residual function:
$$ R(k; \theta) = sf(\hat{k}(\th... | # compute the residual...
ti = np.linspace(0, 100, 1000)
residual = ces_model.ivp.compute_residual(numeric_soln, ti, k=3) | examples/0 Motivation.ipynb | solowPy/solowPy | mit |
For more details behind the numerical methods used in this section see the the Solving the Solow model notebook in the solowPy repository.
5. Impulse response functions
Impulse response functions (IRFs) are a standard tool for analyzing the short run dynamics of dynamic macroeconomic models, such as the Solow growth mo... | # 50% increase in the current savings rate...
ces_model.irf.impulse = {'s': 1.5 * ces_model.params['s']}
# in efficiency units...
ces_model.irf.kind = 'efficiency_units'
fig, ax = plt.subplots(1, 1, figsize=(8,6))
ces_model.irf.plot_impulse_response(ax, variable='output')
plt.show() | examples/0 Motivation.ipynb | solowPy/solowPy | mit |
For more details and examples see the accompanying Impulse response function notebook in the solowPy repository.
6. The Solow model, declining labor's share, and secular stagnation
Recently there has been much discussion about the reasons for the Elsby (2013) has a nice paper that looks at the decline of labor share in... | def awesome_interactive_plot(model, iso3_code, **params):
"""Interactive widget for the my awesome plot."""
# extract the relevant data
tmp_data = pwt.major_xs(iso3_code)
actual_labor_share = tmp_data.labsh.values
actual_capital_share = 1 - tmp_data.labsh
output = tmp_data.rgdpna
c... | examples/0 Motivation.ipynb | solowPy/solowPy | mit |
We run the simulation up to a fixed number of iterations, controlled by the variable niter, storing the value of the EM field $E_z$ at every timestep so we can analyze them later: | import numpy as np
niter = 4000
Ex_t = np.zeros((niter,sim.nx))
Ez_t = np.zeros((niter,sim.nx))
tmax = niter * sim.dt
print("\nRunning simulation up to t = {:g} ...".format(tmax))
while sim.t <= tmax:
print('n = {:d}, t = {:g}'.format(sim.n,sim.t), end = '\r')
Ex_t[sim.n,:] = sim.emf.Ex
Ez_t[sim.n,:] = ... | python/Electron Plasma Waves.ipynb | zambzamb/zpic | agpl-3.0 |
Electrostatic / Electromagnetic Waves
As discussed above, the simulation was initialized with a broad spectrum of waves through the thermal noise of the plasma. We can see the noisy fields in the plot below: | import matplotlib.pyplot as plt
iter = sim.n//2
plt.plot(np.linspace(0, sim.box, num = sim.nx),Ex_t[iter,:], label = "$E_x$")
plt.plot(np.linspace(0, sim.box, num = sim.nx),Ez_t[iter,:], label = "$E_z$")
plt.grid(True)
plt.xlabel("$x_1$ [$c/\omega_n$]")
plt.ylabel("$E$ field []")
plt.title("$E_x$, $E_z$, t = {:g}".fo... | python/Electron Plasma Waves.ipynb | zambzamb/zpic | agpl-3.0 |
Electrostatic Plasma Waves
To analyze the dispersion relation of the electrostatic plasma waves we use a 2D (Fast) Fourier transform of $E_x(x,t)$ field values that we stored during the simulation. The plot below shows the obtained power spectrum alongside the theoretical prediction.
Since the dataset is not periodic a... | import matplotlib.pyplot as plt
import matplotlib.colors as colors
# (omega,k) power spectrum
win = np.hanning(niter)
for i in range(sim.nx):
Ex_t[:,i] *= win
sp = np.abs(np.fft.fft2(Ex_t))**2
sp = np.fft.fftshift( sp )
k_max = np.pi / sim.dx
omega_max = np.pi / sim.dt
plt.imshow( sp, origin = 'lower', norm=co... | python/Electron Plasma Waves.ipynb | zambzamb/zpic | agpl-3.0 |
Electromagnetic Plasma Waves
To analyze the dispersion relation of the electrostatic plasma waves we use a 2D (Fast) Fourier transform of $E_z(x,t)$ field values that we stored during the simulation. The plot below shows the obtained power spectrum alongside the theoretical prediction.
Since the dataset is not periodic... | import matplotlib.pyplot as plt
import matplotlib.colors as colors
# (omega,k) power spectrum
win = np.hanning(niter)
for i in range(sim.nx):
Ez_t[:,i] *= win
sp = np.abs(np.fft.fft2(Ez_t))**2
sp = np.fft.fftshift( sp )
k_max = np.pi / sim.dx
omega_max = np.pi / sim.dt
plt.imshow( sp, origin = 'lower', norm=co... | python/Electron Plasma Waves.ipynb | zambzamb/zpic | agpl-3.0 |
Theoretical background
In addition to the GHZ states, the generalized W states, as proposed by Dür, Vidal and Cirac, in 2000, is a class of interesting examples of multiple qubit entanglement.
A generalized $n$ qubit W state can be written as :
$$ |W_{n}\rangle \; = \; \sqrt{\frac{1}{n}} \: (\:|10...0\rangle \: + |01.... | "Choice of the backend"
# using local qasm simulator
backend = Aer.get_backend('qasm_simulator')
# using IBMQ qasm simulator
# backend = IBMQ.get_backend('ibmq_qasm_simulator')
# using real device
# backend = least_busy(IBMQ.backends(simulator=False))
flag_qx2 = True
if backend.name() == 'ibmqx4':
flag_qx2... | community/teach_me_qiskit_2018/w_state/W State 1 - Multi-Qubit Systems.ipynb | antoniomezzacapo/qiskit-tutorial | apache-2.0 |
Three-qubit W state, step 1
In this section, the production of a three qubit W state will be examined step by step.
In this circuit, the starting state is now: $ |\varphi_{0} \rangle \, = \, |100\rangle$.
The entire circuit corresponds to:
$$ |W_{3}\rangle \,=\, cNOT_{3,2}\, \, cNOT_{... | # 3-qubit W state Step 1
n = 3
q = QuantumRegister(n)
c = ClassicalRegister(n)
W_states = QuantumCircuit(q,c)
W_states.x(q[2]) #start is |100>
F_gate(W_states,q,2,1,3,1) # Applying F12
for i in range(3) :
W_states.measure(q[i] , c[i])
# circuits = ['W_states']
shots = 1024
time_exp = time.strftime('%d/%m/... | community/teach_me_qiskit_2018/w_state/W State 1 - Multi-Qubit Systems.ipynb | antoniomezzacapo/qiskit-tutorial | apache-2.0 |
Three-qubit W state: adding step 2
In the previous step you obtained an histogram compatible with the following state:
$$ |\varphi_{1} \rangle= F_{1,2}\, |\varphi_{0} \rangle\,=F_{1,2}\, \,|1 0 0 \rangle=\frac{1}{\sqrt{3}} \: |1 0 0 \rangle \: + \sqrt{\frac{2}{3}} \: |1 1 0 \rangle $$
NB: Depending on the backend, it... | # 3-qubit W state, first and second steps
n = 3
q = QuantumRegister(n)
c = ClassicalRegister(n)
W_states = QuantumCircuit(q,c)
W_states.x(q[2]) #start is |100>
F_gate(W_states,q,2,1,3,1) # Applying F12
F_gate(W_states,q,1,0,3,2) # Applying F23
for i in range(3) :
W_states.measure(q[i] , c[i])
s... | community/teach_me_qiskit_2018/w_state/W State 1 - Multi-Qubit Systems.ipynb | antoniomezzacapo/qiskit-tutorial | apache-2.0 |
Three-qubit W state, full circuit
In the previous step, we got an histogram compatible with the state:
$$ |\varphi_{2} \rangle =F_{2,3}\, \, |\varphi_{1} \rangle=F_{2,3}\, \, (\frac{1}{\sqrt{3}} \: |1 0 0 \rangle \: + \sqrt{\frac{2}{3}} \: |1 1 0 )= \frac{1}{\sqrt{3}} \: (|1 0 0 \rangle \: + |1 1 0 \:\rangle + |1 1... | # 3-qubit W state
n = 3
q = QuantumRegister(n)
c = ClassicalRegister(n)
W_states = QuantumCircuit(q,c)
W_states.x(q[2]) #start is |100>
F_gate(W_states,q,2,1,3,1) # Applying F12
F_gate(W_states,q,1,0,3,2) # Applying F23
if flag_qx2 : # option ibmqx2
W_states.cx(q[1],q[2]) # cNOT 21
W_states.cx(q[0],q[1]) ... | community/teach_me_qiskit_2018/w_state/W State 1 - Multi-Qubit Systems.ipynb | antoniomezzacapo/qiskit-tutorial | apache-2.0 |
Now you get an histogram compatible with the final state $|W_{3}\rangle$ through the following steps:
$$ |\varphi_{3} \rangle = cNOT_{2,1}\, \, |\varphi_{2} \rangle =cNOT_{2,1}\,\frac{1}{\sqrt{3}} \: (|1 0 0 \rangle \: + |1 1 0 \rangle\: + |1 1 1\rangle) = \frac{1}{\sqrt{3}} \: (|1 0 0 \rangle \: + |0 1 0 \: + ... | # 4-qubit W state
n = 4
q = QuantumRegister(n)
c = ClassicalRegister(n)
W_states = QuantumCircuit(q,c)
W_states.x(q[3]) #start is |1000>
F_gate(W_states,q,3,2,4,1) # Applying F12
F_gate(W_states,q,2,1,4,2) # Applying F23
F_gate(W_states,q,1,0,4,3) # Applying F34
cxrv(W_states,q,2,3) # cNOT 21
if flag_qx2 : #... | community/teach_me_qiskit_2018/w_state/W State 1 - Multi-Qubit Systems.ipynb | antoniomezzacapo/qiskit-tutorial | apache-2.0 |
Now, if you used a simulator, you get an histogram clearly compatible with the state:
$$ |W_{4}\rangle \;=\; \frac{1}{2} \: (\:|1000\rangle + |0100\rangle + |0010\rangle + |0001\rangle \:) $$
If you used a real quantum computer, the columns of the histogram compatible with a $|W_{4}\rangle$ state are not all among t... | # 5-qubit W state
n = 5
q = QuantumRegister(n)
c = ClassicalRegister(n)
W_states = QuantumCircuit(q,c)
W_states.x(q[4]) #start is |10000>
F_gate(W_states,q,4,3,5,1) # Applying F12
F_gate(W_states,q,3,2,5,2) # Applying F23
F_gate(W_states,q,2,1,5,3) # Applying F34
F_gate(W_states,q,1,0,5,4) # Applying F45
W_states.cx... | community/teach_me_qiskit_2018/w_state/W State 1 - Multi-Qubit Systems.ipynb | antoniomezzacapo/qiskit-tutorial | apache-2.0 |
Load open source data published bei the Global Energy Observation, GEO. As you might know, this is not the original format of the database but the standardized format of powerplantmatching. | geo = pm.data.GEO()
geo.head() | doc/example.ipynb | FRESNA/powerplantmatching | gpl-3.0 |
Load the data published by the ENTSOE which has the same format as the geo data. | entsoe = pm.data.ENTSOE()
entsoe.head() | doc/example.ipynb | FRESNA/powerplantmatching | gpl-3.0 |
Data Inspection
Whereas various options of inspection of provided by the pandas package, some more powerplant specific methods are applicable via an accessor 'powerplant'. It gives you a convenient way to inspect, manipulate the data: | geo.powerplant.plot_map();
geo.powerplant.lookup().head(20).to_frame()
geo.powerplant.fill_missing_commyears().head() | doc/example.ipynb | FRESNA/powerplantmatching | gpl-3.0 |
Of course the pandas function are also very convenient: | print('Total capacity of GEO is: \n {} MW \n'.format(geo.Capacity.sum()));
print('The technology types are: \n {} '.format(geo.Technology.unique())) | doc/example.ipynb | FRESNA/powerplantmatching | gpl-3.0 |
Incomplete data
All open databases are so far not complete and cover only an part of overall European powerplants. We perceive the capacity gaps looking at the ENTSOE SO&AF Statistics. | stats = pm.data.Capacity_stats()
pm.plot.fueltype_totals_bar([geo, entsoe, stats], keys=["ENTSOE", "GEO", 'Statistics']); | doc/example.ipynb | FRESNA/powerplantmatching | gpl-3.0 |
The gaps for both datasets are unmistakable. Adding both datasets on top of each other would not be a solution, since the intersection of both sources are two high, and the resulting dataset would include many duplicates. A better approach is to merge the incomplete datasets together, respecting intersections and diffe... | dfs = [geo.powerplant.aggregate_units(), entsoe.powerplant.aggregate_units()]
intersection = pm.matching.combine_multiple_datasets(dfs)
intersection.head() | doc/example.ipynb | FRESNA/powerplantmatching | gpl-3.0 |
The result of the matching process is a multiindexed dataframe. To bring the matched dataframe into a convenient format, we combine the information of the two source sources. | intersection = intersection.powerplant.reduce_matched_dataframe()
intersection.head() | doc/example.ipynb | FRESNA/powerplantmatching | gpl-3.0 |
As you can see in the very last column, we can track which original data entries flew into the resulting one.
We can have a look into the Capacity statisitcs | pm.plot.fueltype_totals_bar([intersection, stats], keys=["Intersection", 'Statistics']);
combined = intersection.powerplant.extend_by_non_matched(entsoe).powerplant.extend_by_non_matched(geo)
pm.plot.fueltype_totals_bar([combined, stats], keys=["Combined", 'Statistics']); | doc/example.ipynb | FRESNA/powerplantmatching | gpl-3.0 |
The aggregated capacities roughly match the SO&AF for all conventional powerplants
Processed Data
powerplantmatching comes along with already matched data, this includes data from GEO, ENTSOE, OPSD, CARMA, GPD and ESE (ESE, only if you have followed the instructions) | m = pm.collection.matched_data()
m.powerplant.plot_map(figsize=(13,13));
pm.plot.fueltype_totals_bar([m, stats], keys=["Processed", 'Statistics']);
pm.plot.factor_comparison([m, stats], keys=['Processed', 'Statistics'])
m.head()
pd.concat([m[m.DateIn.notnull()].groupby('Fueltype').DateIn.count(),
m[m.Dat... | doc/example.ipynb | FRESNA/powerplantmatching | gpl-3.0 |
In order to be able to use the Data Observatory via CARTOframes, you need to set your CARTO account credentials first.
Please, visit the Authentication guide for further detail. | from cartoframes.auth import set_default_credentials
set_default_credentials('creds.json') | docs/examples/advanced_use_cases/building_a_dashboard.ipynb | CartoDB/cartoframes | bsd-3-clause |
Note about credentials
For security reasons, we recommend storing your credentials in an external file to prevent publishing them by accident when sharing your notebooks. You can get more information in the section Setting your credentials of the Authentication guide.
<a id='section1'></a>
1. Download all pharmacies in... | dem_bbox = box(-75.229353,39.885501,-75.061124,39.997898) | docs/examples/advanced_use_cases/building_a_dashboard.ipynb | CartoDB/cartoframes | bsd-3-clause |
We can get the pharmacies from Pitney Bowes' Consumer Points of Interest dataset. This is a premium dataset, so we first need to check that we are subscribed to it.
Take a look at <a href='#example-access-premium-data-from-the-data-observatory' target='_blank'>this template</a> for more details on how to access and dow... | Catalog().subscriptions().datasets.to_dataframe() | docs/examples/advanced_use_cases/building_a_dashboard.ipynb | CartoDB/cartoframes | bsd-3-clause |
Download and explore sample
Pitney Bowes POI's are hierarchically classified (levels: trade division, group, class, sub class).
Since we might not know which level can help us identify all pharmacies, we can start by downloading a sample for a smaller area to explore the dataset. For calculating the bounding box we us... | dataset = Dataset.get('pb_consumer_po_62cddc04')
dataset.head() | docs/examples/advanced_use_cases/building_a_dashboard.ipynb | CartoDB/cartoframes | bsd-3-clause |
Let's now download a small sample to help us identify which of the four hierarchy variables gives us the pharmacies. | sql_query = "SELECT * except(do_label) FROM $dataset$ WHERE ST_IntersectsBox(geom, -75.161723,39.962019,-75.149535,39.968071)"
sample = dataset.to_dataframe(sql_query=sql_query)
sample.head()
sample['TRADE_DIVISION'].unique()
sample.loc[sample['TRADE_DIVISION'] == 'DIVISION G. - RETAIL TRADE', 'GROUP'].unique()
sam... | docs/examples/advanced_use_cases/building_a_dashboard.ipynb | CartoDB/cartoframes | bsd-3-clause |
The class DRUG STORES AND PROPRIETARY STORES is the one we're looking for. | sample.loc[sample['CLASS'] == 'DRUG STORES AND PROPRIETARY STORES', 'SUB_CLASS'].unique() | docs/examples/advanced_use_cases/building_a_dashboard.ipynb | CartoDB/cartoframes | bsd-3-clause |
Download all pharmacies in the area of study | sql_query = """SELECT * except(do_label)
FROM $dataset$
WHERE CLASS = 'DRUG STORES AND PROPRIETARY STORES'
AND ST_IntersectsBox(geom, -75.229353,39.885501,-75.061124,39.997898)"""
ph_pharmacies = dataset.to_dataframe(sql_query=sql_query)
ph_pharmacies.head() | docs/examples/advanced_use_cases/building_a_dashboard.ipynb | CartoDB/cartoframes | bsd-3-clause |
The dataset contains different versions of the POI's tagged by the do_date column. We are only inetrested in the latest version of each POI. | ph_pharmacies = ph_pharmacies.sort_values(by='do_date', ascending=False).groupby('PB_ID').first().reset_index()
ph_pharmacies.shape | docs/examples/advanced_use_cases/building_a_dashboard.ipynb | CartoDB/cartoframes | bsd-3-clause |
Visualize the dataset | Layer(ph_pharmacies,
geom_col='geom',
style=basic_style(opacity=0.75),
popup_hover=popup_element('NAME')) | docs/examples/advanced_use_cases/building_a_dashboard.ipynb | CartoDB/cartoframes | bsd-3-clause |
<a id='section2'></a>
2. Calculate catchment areas
In order to know the characteristics of the potential customers of every pharmacy, we assume the majority of their clients live closeby. Therefore we will calculate 5-minute-by-car isochrones and take them as their cathment areas.
Note catchment areas usually depend on... | iso_service = Isolines()
isochrones_gdf, _ = iso_service.isochrones(ph_pharmacies, [300], mode='car', geom_col='geom')
ph_pharmacies['iso_5car'] = isochrones_gdf.sort_values(by='source_id')['the_geom'].values | docs/examples/advanced_use_cases/building_a_dashboard.ipynb | CartoDB/cartoframes | bsd-3-clause |
Visualize isochrones
We'll only visualize the ten first isochrones to get a clean visualization. | Map([Layer(ph_pharmacies.iloc[:10],
geom_col='iso_5car',
style=basic_style(opacity=0.1),
legends=basic_legend('Catchment Areas')),
Layer(ph_pharmacies.iloc[:10],
geom_col='geom',
popup_hover=popup_element('NAME'),
legends=basic_legend('Pharmacies'... | docs/examples/advanced_use_cases/building_a_dashboard.ipynb | CartoDB/cartoframes | bsd-3-clause |
<a id='section3'></a>
3. Enrichment: Chacacterize catchment areas
We'll now enrich the pharmacies catchment areas with demographics, POI's, and consumer spending data.
For the enrichment, we will use the CARTOframes Enrichment class. This class contains the functionality to enrich polygons and points.
Visit CARTOframe... | enrichment = Enrichment() | docs/examples/advanced_use_cases/building_a_dashboard.ipynb | CartoDB/cartoframes | bsd-3-clause |
Demographics
We will use AGS premium data. In particular, we will work with the dataset ags_sociodemogr_f510a947 which contains yearly demographics data from 2019.
Variable selection
Here we will enrich the pharmacies isochrones with:
- Population aged 60+
- Household income
- Household income for population ages 65... | Catalog().country('usa').category('demographics').provider('ags').datasets.to_dataframe().head()
dataset = Dataset.get('ags_sociodemogr_f510a947')
dataset.head() | docs/examples/advanced_use_cases/building_a_dashboard.ipynb | CartoDB/cartoframes | bsd-3-clause |
We explore the variables to identify the ones we're interested in.
Variables in a dataset are uniquely identified by their slug. | dataset.variables.to_dataframe().head() | docs/examples/advanced_use_cases/building_a_dashboard.ipynb | CartoDB/cartoframes | bsd-3-clause |
We'll select:
- Population and population by age variables to identify number of people aged 60+ as a percentage of total population
- Average household income
- Average household income for porpulation aged 65+ | vars_enrichment = ['POPCY_5e23b8f4', 'AGECY6064_d54c2315', 'AGECY6569_ad369d43', 'AGECY7074_74eb7531',
'AGECY7579_c91cb67', 'AGECY8084_ab1079a8', 'AGECYGT85_a0959a08', 'INCCYMEDHH_b80a7a7b',
'HINCYMED65_37a430a4', 'HINCYMED75_2ebf01e5'] | docs/examples/advanced_use_cases/building_a_dashboard.ipynb | CartoDB/cartoframes | bsd-3-clause |
Isochrone enrichment | ph_pharmacies_enriched = enrichment.enrich_polygons(
ph_pharmacies,
variables=vars_enrichment,
geom_col='iso_5car'
)
ph_pharmacies_enriched.head()
ph_pharmacies = ph_pharmacies_enriched.copy()
ph_pharmacies['pop_60plus'] = ph_pharmacies[['AGECY8084', 'AGECYGT85', 'AGECY6569', 'AGECY7579', 'AGECY7074', 'A... | docs/examples/advanced_use_cases/building_a_dashboard.ipynb | CartoDB/cartoframes | bsd-3-clause |
Points of Interest
We will use Pitney Bowes' Consumer Points of Interest premium dataset.
Variable selection
We are interested in knowing how many of the following POIs can be found in each isochrone:
- Beauty shops and beauty salons
- Gyms and other sports centers
These POI's will be considered as an indicator of pe... | sample.loc[sample['TRADE_DIVISION'] == 'DIVISION I. - SERVICES', 'SUB_CLASS'].unique() | docs/examples/advanced_use_cases/building_a_dashboard.ipynb | CartoDB/cartoframes | bsd-3-clause |
Isochrone enrichment
In order to count only Beauty Shops/Salons and Gyms, we will apply a filter to the enrichment. All filters are applied with an AND-like relationship. This means we need to run two independent enrichment calls, one for the beauty shops/salons and another one for the gyms. | ph_pharmacies_enriched = enrichment.enrich_polygons(
ph_pharmacies,
variables=['SUB_CLASS_10243439'],
aggregation='COUNT',
geom_col='iso_5car',
filters={Variable.get('SUB_CLASS_10243439').id : "= 'BEAUTY SHOPS/BEAUTY SALON'"}
)
ph_pharmacies = ph_pharmacies_enriched.rename(columns={'SUB_CLASS_y':'n... | docs/examples/advanced_use_cases/building_a_dashboard.ipynb | CartoDB/cartoframes | bsd-3-clause |
Consumer spending
For consumer spending, we will use AGS premium data. In particular, we will work with the dataset ags_consumer_sp_dbabddfb which contains the latest version of yearly consumer data.
Variable selection
We are interested in spending in:
- Personal care services
- Personal care products
- Health care ... | dataset = Dataset.get('ags_consumer_sp_dbabddfb')
dataset.variables.to_dataframe().head() | docs/examples/advanced_use_cases/building_a_dashboard.ipynb | CartoDB/cartoframes | bsd-3-clause |
The variables we're interested in are:
- XCYHC2 Health care services expenditure
- XCYPC3 Personal care services expenditure
- XCYPC4 Personal care products expenditure | Variable.get('XCYHC2_18141567').to_dict()
ph_pharmacies_enriched = enrichment.enrich_polygons(
ph_pharmacies,
variables=['XCYPC3_7d26d739', 'XCYPC4_e342429a', 'XCYHC2_18141567'],
geom_col='iso_5car'
) | docs/examples/advanced_use_cases/building_a_dashboard.ipynb | CartoDB/cartoframes | bsd-3-clause |
We rename the new columns to give them a more descriptive name. | ph_pharmacies = ph_pharmacies_enriched.rename(columns={'XCYHC2':'health_care_services_exp',
'XCYPC3':'personal_care_services_exp',
'XCYPC4':'personal_care_products_exp'})
ph_pharmacies.head(2) | docs/examples/advanced_use_cases/building_a_dashboard.ipynb | CartoDB/cartoframes | bsd-3-clause |
<a id='section4'></a>
4. Dashboard
Finally, with all the data gathered, we will build the dashboard and publish it so we can share it with our client/manager/colleague for them to explore it.
This dashboard allows you to select a range of desired expenditure in care products, people aged 60+, household income, and so f... | cmap = Map(Layer(ph_pharmacies,
geom_col='geom',
style=color_category_style('SIC8_DESCRIPTION', size=4, opacity=0.85, palette='safe', stroke_width=0.15),
widgets=[formula_widget(
'PB_ID',
operation='COUNT',
... | docs/examples/advanced_use_cases/building_a_dashboard.ipynb | CartoDB/cartoframes | bsd-3-clause |
Publish dashboard | cmap.publish('ph_pharmacies_dashboard', password='MY_PASS', if_exists='replace') | docs/examples/advanced_use_cases/building_a_dashboard.ipynb | CartoDB/cartoframes | bsd-3-clause |
Train Test Split | from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(df_in, np.ravel(df_target), test_size=0.30, random_state=101) | 04-more-supervised.ipynb | msadegh97/machine-learning-course | gpl-3.0 |
Train the Support Vector Classifier | from sklearn.svm import SVC
model = SVC(kernel='rbf')
model.fit(X_train,y_train) | 04-more-supervised.ipynb | msadegh97/machine-learning-course | gpl-3.0 |
Woah! Notice that we are classifying everything into a single class! This means our model needs to have it parameters adjusted (it may also help to normalize the data).
We can search for parameters using a GridSearch!
Gridsearch
Finding the right parameters (like what C or gamma values to use) is a tricky task! But luc... | param_grid = {'C': [0.1,1, 10, 100, 1000], 'gamma': [1,0.1,0.01,0.001,0.0001], 'kernel': ['rbf']}
from sklearn.model_selection import GridSearchCV
grid = GridSearchCV(SVC(),param_grid,refit=True,verbose=3)
grid.fit(X_train,y_train)
grid.best_params_
grid.best_estimator_
grid_predictions = grid.predict(X_test)
p... | 04-more-supervised.ipynb | msadegh97/machine-learning-course | gpl-3.0 |
Decision Tree | from sklearn.tree import DecisionTreeClassifier
dtree = DecisionTreeClassifier()
dtree.fit(X_train,y_train)
treepredictop = dtree.predict(X_test)
print(classification_report(y_test,treepredictop))
features = X_train.columns
features
from IPython.display import Image as image
from sklearn.externals.six import Str... | 04-more-supervised.ipynb | msadegh97/machine-learning-course | gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.