markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
We need to start with our VGG 16 model, since we're using its predictions & features | from vgg16 import Vgg16
vgg = Vgg16()
model = vgg.model | _____no_output_____ | MIT | FAI_old/lesson2/lesson2_codealong.ipynb | WNoxchi/Kawkasos |
Our overall approach here will be:1. Get the true labels for every image2. Get the 1,000 ImageNet category predictions for every image3. Feed these predictions as input to a simple linear model.Let's start by grabbing training and validation batches.(so that's a thousand floats for every image)use an output of 2 as inp... | # Use batch size of 1 since we're just doing preprocessing on the CPU
val_batches = get_batches(path + 'valid', shuffle=False, batch_size=1)
batches = get_batches(path + 'train', shuffle=False, batch_size=1) | Found 50 images belonging to 2 classes.
Found 352 images belonging to 2 classes.
| MIT | FAI_old/lesson2/lesson2_codealong.ipynb | WNoxchi/Kawkasos |
Getting the 1,000 categories for each image will take a long time & there's no reason to do it again & again. So after we do it the first time, let's save the resulting arrays. | import bcolz
def save_array(fname, arr): c=bcolz.carray(arr, rootdir=fname, mode='w'); c.flush()
def load_array(fname): return bcolz.open(fname)[:] | _____no_output_____ | MIT | FAI_old/lesson2/lesson2_codealong.ipynb | WNoxchi/Kawkasos |
It's also time consuming to convert all the images in the 224x224 format VGG 16 expects. So ```get_data``` will also store a Numpy array of the results of that conversion. | # ?? shows you the source code
??get_data
val_data = get_data(path + 'valid')
trn_data = get_data(path + 'train')
# so what the above does is createa a Numpy array with our full set of
# training images -- 352 imgs, ea. of which is 3 colors, and 224x224
trn_data.shape
save_array(model_path + 'train_data.bc', trn_data)
... | _____no_output_____ | MIT | FAI_old/lesson2/lesson2_codealong.ipynb | WNoxchi/Kawkasos |
& Now we can load our training & validation data layer without recalculating them | trn_data = load_array(model_path + 'train_data.bc')
val_data = load_array(model_path + 'valid_data.bc')
val_data.shape # our 50 validatn imgs | _____no_output_____ | MIT | FAI_old/lesson2/lesson2_codealong.ipynb | WNoxchi/Kawkasos |
Most Deep Learning is done w/ One-Hot Encoding: prediction = 1, all other classes = 0; & Keras expects labels in a very specific format. Example of One Hot Encoding:```Class: 1Ht Enc: 0 100 1 010 2 001 1 010 0 100```1Ht Encoding is used because you can perform a MatMul since the num. weights ==... | def onehot(x): return np.array(OneHotEncoder().fit_transform(x.reshape(-1, 1)).todense())
# So, next thing we want to do is grab our labels and One-Hot Encode them
val_classes = val_batches.classes
trn_classes = batches.classes
val_labels = onehot(val_classes)
trn_labels = onehot(trn_classes)
trn_classes.shape # Keras ... | _____no_output_____ | MIT | FAI_old/lesson2/lesson2_codealong.ipynb | WNoxchi/Kawkasos |
Now we can finally do Step No.2: get the 1,000 ImageNet categ. preds for every image. Keras makes this easy for us. We can simple call ```model.predict(..)``` and pass in our data | trn_features = model.predict(trn_data, batch_size=batch_size)
val_features = model.predict(val_data, batch_size=batch_size)
trn_features.shape # we can see it is indeed No. imgs x 1000 categories
# let's take a look at one of the images (displaying all its categs)
trn_features[0] | _____no_output_____ | MIT | FAI_old/lesson2/lesson2_codealong.ipynb | WNoxchi/Kawkasos |
Not surprisingly, nearly all of these numbers are near zero.Now we can define our linear model, just like we did earlier; now that we have our 1000 features for each image | # 1000 inputs, since those're the saved features, and 2 outputs: dog & cat
lm = Sequential([Dense(2, activation='softmax', input_shape=(1000,))])
lm.compile(optimizer=RMSprop(lr=0.1), loss='categorical_crossentropy', metrics=['accuracy']) | _____no_output_____ | MIT | FAI_old/lesson2/lesson2_codealong.ipynb | WNoxchi/Kawkasos |
& Now we're ready to fit the model! RMSprop is somewhat better than SGD. It's a minor tweak on SGD that tends to be much faster. | batch_size=4
lm.fit(trn_features, trn_labels, batch_size=batch_size, nb_epoch=3,
validation_data = (val_features, val_labels))
# let's have a look at our model
lm.summary() | ____________________________________________________________________________________________________
Layer (type) Output Shape Param # Connected to
====================================================================================================
dense_6 (Dense) ... | MIT | FAI_old/lesson2/lesson2_codealong.ipynb | WNoxchi/Kawkasos |
So it ran almost instantly because running 3 epochs on a single layer with 2000 is really quick for my little i5 MacBook :3We got an accuracy of ```.92```. Let's run another 3 epochs and see if this changes: | lm.fit(trn_features, trn_labels, batch_size=batch_size, nb_epoch=3,
validation_data = (val_features, val_labels)) | Train on 352 samples, validate on 50 samples
Epoch 1/3
352/352 [==============================] - 0s - loss: 0.0267 - acc: 0.9915 - val_loss: 0.2057 - val_acc: 0.9000
Epoch 2/3
352/352 [==============================] - 0s - loss: 0.0266 - acc: 0.9886 - val_loss: 0.2279 - val_acc: 0.9000
Epoch 3/3
352/352 [============... | MIT | FAI_old/lesson2/lesson2_codealong.ipynb | WNoxchi/Kawkasos |
(I actually ran 9, bc on a tiny set of 350 images it took a bit more to improve: no change on the 1st, dropped to ```.90``` on the 2nd, and finally up to ```.94``` on the final)Here we haven't done any finetuning. All we did was take the ImageNet model of predictions, and built a model that maps from those predictions ... | vgg.model.summary() | ____________________________________________________________________________________________________
Layer (type) Output Shape Param # Connected to
====================================================================================================
lambda_1 (Lambda)... | MIT | FAI_old/lesson2/lesson2_codealong.ipynb | WNoxchi/Kawkasos |
The last layer is a Dense (FC/Linear) layer. It doesn't make sense to add another dense layer atop of a dense layer that's already tuned to classify the 1,000 ImageNet categories. We'll remove it, and use the previous Dense layer with it's 4096 activations to find Cats & Dogs.We do this by calling ```model.pop()``` to ... | model.pop()
for layer in model.layers: layer.trainable=False | _____no_output_____ | MIT | FAI_old/lesson2/lesson2_codealong.ipynb | WNoxchi/Kawkasos |
Now we add our final Cat vs Dog layer | model.add(Dense(2, activation='softmax')) | _____no_output_____ | MIT | FAI_old/lesson2/lesson2_codealong.ipynb | WNoxchi/Kawkasos |
To see what happened when we called ```vgg.finetune()``` earlier:Basically what it does is a ```model.pop()``` and a ```model.add(Dense(..))``` | ??vgg.finetune() | _____no_output_____ | MIT | FAI_old/lesson2/lesson2_codealong.ipynb | WNoxchi/Kawkasos |
After we add our new final layer, we'll setup our batches to use preprocessed images (and we'll also *shuffle* the traiing batches to add more randomness when using multiple epochs): | gen = image.ImageDataGenerator()
batches = gen.flow(trn_data, trn_labels, batch_size=batch_size, shuffle=True)
val_batches = gen.flow(val_data, val_labels, batch_size=batch_size, shuffle=False) | _____no_output_____ | MIT | FAI_old/lesson2/lesson2_codealong.ipynb | WNoxchi/Kawkasos |
Now we have a model designed to classify Cats vs Dogs instead of the 1,000 ImageNet categories & THEN Cats vs Dogs. After this, everything is done the same as before. Compile the model & choose optimizer, fit the model (btw, whenever we work with batches in Keras, we'll be using ```model.function_generator(..)``` inste... | # NOTE: now use batches.n instead of batches.N
def fit_model(model, batches, val_batches, nb_epoch=1):
model.fit_generator(batches, samples_per_epoch=batches.n, nb_epoch=nb_epoch,
validation_data=val_batches, nb_val_samples=val_batches.n) | _____no_output_____ | MIT | FAI_old/lesson2/lesson2_codealong.ipynb | WNoxchi/Kawkasos |
It'll run a bit slowly since it has to calculate all previous layers in order to know what input to pass to the new final layer. We can save time by precalculating the output of the penultimate layer, like we did for the final layer earlier. Note for later work. | # compile the new model
opt = RMSprop(lr=0.1)
model.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy'])
# then fit it
fit_model(model, batches, val_batches, nb_epoch=2) | Epoch 1/2
352/352 [==============================] - 170s - loss: 1.4733 - acc: 0.8949 - val_loss: 1.6794 - val_acc: 0.8600
Epoch 2/2
352/352 [==============================] - 164s - loss: 1.5168 - acc: 0.9006 - val_loss: 0.3224 - val_acc: 0.9800
| MIT | FAI_old/lesson2/lesson2_codealong.ipynb | WNoxchi/Kawkasos |
Note how little actual code was needed to finetune the model. Because this is such an important and common operation, Keras is set up to make it as easy as possible. Not external helper functions were needed.It's a good idea to save weights of all your models, so you can re-use them later. Be sure to note the git log n... | model.save_weights(model_path + 'finetune1.h5')
# We can now use this as a good starting point for future Dogs v Cats models
model.load_weights(model_path + 'finetune1.h5')
model.evaluate(val_data, val_labels) | 50/50 [==============================] - 18s
| MIT | FAI_old/lesson2/lesson2_codealong.ipynb | WNoxchi/Kawkasos |
Week 2 Assignments:**Take it further** -- now that you know what's going on with finetuning and linear layers -- think about everything you know: the evaluation function, the categorical cross entropy loss function, finetuning: and see if you can find ways to make your model better and see how high up the rankings in K... | preds = model.predict_classes(val_data, batch_size=batch_size)
probs = model.predict_proba(val_data, batch_size=batch_size)[:,0] | _____no_output_____ | MIT | FAI_old/lesson2/lesson2_codealong.ipynb | WNoxchi/Kawkasos |
Get EchoVPR from GitHub | !git clone https://github.com/anilozdemir/EchoVPR.git | Cloning into 'EchoVPR'...
remote: Enumerating objects: 82, done.[K
remote: Counting objects: 100% (82/82), done.[K
remote: Compressing objects: 100% (60/60), done.[K
remote: Total 82 (delta 33), reused 53 (delta 18), pack-reused 0[K
Unpacking objects: 100% (82/82), done.
| MIT | notebooks/example_train_single_ESN.ipynb | anilozdemir/EchoVPR |
Install `echovpr` module | %cd EchoVPR/src
!python setup.py develop | running develop
running egg_info
creating echovpr.egg-info
writing echovpr.egg-info/PKG-INFO
writing dependency_links to echovpr.egg-info/dependency_links.txt
writing top-level names to echovpr.egg-info/top_level.txt
writing manifest file 'echovpr.egg-info/SOURCES.txt'
writing manifest file 'echovpr.egg-info/SOURCES.tx... | MIT | notebooks/example_train_single_ESN.ipynb | anilozdemir/EchoVPR |
Train ESN and ESN+SpaRCe | import torch
from echovpr.datasets import getHiddenRepr, DataSets, Tolerance
from echovpr.networks import singleESN, getSparsity
from echovpr.experiments import ESN_Exp, getValidationIndices | _____no_output_____ | MIT | notebooks/example_train_single_ESN.ipynb | anilozdemir/EchoVPR |
Get NetVLAD Hidden Representation and Validation Indices | ds = 'GardensPoint'
tol = Tolerance[ds]
# Get NetVLAD Hidden Representation
hiddenReprTrain, hiddenReprTest = getHiddenRepr('GardensPoint')
# Get Input and Output Size; First element of shape: (number of images == number of classes == nOutput); Second element: size of hidden representations
nOutput, nInput = hiddenR... | _____no_output_____ | MIT | notebooks/example_train_single_ESN.ipynb | anilozdemir/EchoVPR |
ESN Training | nRes = 1000
nCon = 10
nTrial = 10
nEpoch = 50
nBatch = 5
lR = 0.01
gamma = 0.0003
alpha = 0.68
_ESN_model_ = lambda randSeed: singleESN(nInput, nOutput, nReservoir=nRes, randomSeed = randSeed, device='cpu', useReadout = False,
sparsity = getSparsity(nCon, nRes), alpha... | _____no_output_____ | MIT | notebooks/example_train_single_ESN.ipynb | anilozdemir/EchoVPR |
ESN+SpaRCe Training | nRes = 1000
nCon = 10
nTrial = 10
nEpoch = 50
nBatch = 5
lR = 0.01
gamma = 0.0003
alpha = 0.74
quantile = 0.4
lrDiv = 10
_SPARCE_model_ = lambda randSeed: singleESN(nInput, nOutput, nReservoir = nRes, randomSeed = randSeed, device='cpu', useReadout = False,
... | _____no_output_____ | MIT | notebooks/example_train_single_ESN.ipynb | anilozdemir/EchoVPR |
Hyperparameter tuning Dask + scikit-learn | from dask.distributed import Client
from dask_saturn import SaturnCluster
cluster = SaturnCluster(
scheduler_size='2xlarge',
worker_size='2xlarge',
nthreads=8,
n_workers=3,
)
client = Client(cluster)
cluster | [2020-12-04 17:54:56] INFO - dask-saturn | Cluster is ready
| BSD-3-Clause | machine_learning/hyperparameter_tuning/hyperparam-dask.ipynb | mmccarty/saturn-cloud-examples |
Load data and feature engineering | import numpy as np
import datetime
import dask.dataframe as dd
taxi = dd.read_csv(
's3://nyc-tlc/trip data/yellow_tripdata_2019-01.csv',
parse_dates=['tpep_pickup_datetime', 'tpep_dropoff_datetime'],
storage_options={'anon': True},
).sample(frac=0.1, replace=False)
taxi['pickup_weekday'] = taxi.tpep_pickup... | _____no_output_____ | BSD-3-Clause | machine_learning/hyperparameter_tuning/hyperparam-dask.ipynb | mmccarty/saturn-cloud-examples |
Run grid search | from sklearn.pipeline import Pipeline
from sklearn.linear_model import ElasticNet
from dask_ml.compose import ColumnTransformer
from dask_ml.preprocessing import StandardScaler, DummyEncoder, Categorizer
from dask_ml.model_selection import GridSearchCV
numeric_feat = ['pickup_weekday', 'pickup_weekofyear', 'pickup_ho... | _____no_output_____ | BSD-3-Clause | machine_learning/hyperparameter_tuning/hyperparam-dask.ipynb | mmccarty/saturn-cloud-examples |
3 nodes | cluster.scale(3)
client.wait_for_workers(3)
%%time
_ = grid_search.fit(taxi[features], taxi[y_col]) | CPU times: user 5.4 s, sys: 578 ms, total: 5.98 s
Wall time: 1h 3min 54s
| BSD-3-Clause | machine_learning/hyperparameter_tuning/hyperparam-dask.ipynb | mmccarty/saturn-cloud-examples |
Scale up to 10 nodes | cluster.scale(10)
client.wait_for_workers(10)
%%time
_ = grid_search.fit(taxi[features], taxi[y_col]) | CPU times: user 3.14 s, sys: 275 ms, total: 3.41 s
Wall time: 19min 49s
| BSD-3-Clause | machine_learning/hyperparameter_tuning/hyperparam-dask.ipynb | mmccarty/saturn-cloud-examples |
Scale up to 20 nodes | cluster.scale(20)
client.wait_for_workers(20)
%%time
_ = grid_search.fit(taxi[features], taxi[y_col]) | CPU times: user 2.57 s, sys: 257 ms, total: 2.83 s
Wall time: 10min 48s
| BSD-3-Clause | machine_learning/hyperparameter_tuning/hyperparam-dask.ipynb | mmccarty/saturn-cloud-examples |
Resnet example with Flax and JAXopt.[](https://colab.research.google.com/github/google/jaxopt/blob/main/docs/notebooks/resnet_flax.ipynb)[*Mathieu Blondel*](https://mblondel.org/), [*Fabian Pedregosa*](https://fa.bianp.net)In this notebook, we'l... | %%capture
%pip install jaxopt flax
from datetime import datetime
import collections
from functools import partial
from typing import Any, Callable, Sequence, Tuple
from flax import linen as nn
import jax
import jax.numpy as jnp
from jaxopt import loss
from jaxopt import OptaxSolver
from jaxopt import tree_util
imp... | _____no_output_____ | Apache-2.0 | docs/notebooks/deep_learning/resnet_flax.ipynb | froystig/jaxopt |
We'll now load our train and test dataset and plot a few of the training images. | # Hide any GPUs from TensorFlow. Otherwise TF might reserve memory and make
# it unavailable to JAX.
tf.config.experimental.set_visible_devices([], 'GPU')
train_ds, ds_info = load_dataset("train", is_training=True,
batch_size=FLAGS.train_batch_size)
test_ds, _ = load_dataset("test", i... | _____no_output_____ | Apache-2.0 | docs/notebooks/deep_learning/resnet_flax.ipynb | froystig/jaxopt |
# DATA FILES DIRECTORY
dirIn = 'path to Data folder for exercise 1'
# IMPORTS
import helpFunctions as hf
import matplotlib.pyplot as plt
import numpy as np
import imageio
# DAY ONE MULTISPECTRAL IMAGE AND ANNOTATIONS
multiIm, annotationIm = hf.loadMulti('multispectral_day01.mat','annotation_day01.png',\
dirIn)
# ASSUME... | _____no_output_____ | Apache-2.0 | EX1_model2+3.ipynb | sonomarina/Mathmodelling_DTU | |
Jupyter notebook transcription of http://www.physics.utah.edu/~bolton/python_lens_demo/ | %matplotlib inline | _____no_output_____ | CC-BY-4.0 | notebooks/StrongLensDemo.ipynb | bombrun/GaiaLQSO |
original python files | ls *.py | lensdemo_funcs.py lensdemo_script.py
| CC-BY-4.0 | notebooks/StrongLensDemo.ipynb | bombrun/GaiaLQSO |
Import the necessary packages | import numpy as np
import matplotlib as mp
from matplotlib import pyplot as plt
import lensdemo_funcs as ldf
mp.rcParams['figure.figsize'] = (12, 8) | _____no_output_____ | CC-BY-4.0 | notebooks/StrongLensDemo.ipynb | bombrun/GaiaLQSO |
Package some image display preferences in a dictionary object, for use below: | myargs = {'interpolation': 'nearest', 'origin': 'lower', 'cmap': mp.cm.gnuplot} | _____no_output_____ | CC-BY-4.0 | notebooks/StrongLensDemo.ipynb | bombrun/GaiaLQSO |
Test Make some x and y coordinate images: | nx = 501
ny = 501
xhilo = [-2.5, 2.5]
yhilo = [-2.5, 2.5]
x = (xhilo[1] - xhilo[0]) * np.outer(np.ones(ny), np.arange(nx)) / float(nx-1) + xhilo[0]
y = (yhilo[1] - yhilo[0]) * np.outer(np.arange(ny), np.ones(nx)) / float(ny-1) + yhilo[0]
# The following lines can be used to verify that the SIE potential gradient
# func... | _____no_output_____ | CC-BY-4.0 | notebooks/StrongLensDemo.ipynb | bombrun/GaiaLQSO |
First lens Set some Gaussian blob image parameters and pack them into an array | g_amp = 1.0 # peak brightness value
g_sig = 0.05 # Gaussian "sigma" (i.e., size)
g_xcen = 0.0 # x position of center
g_ycen = 0.0 # y position of center
g_axrat = 1.0 # minor-to-major axis ratio
g_pa = 0.0 # major-axis position angle (degrees) c.c.w. from x axis
gpar = np.array([g_amp, g_sig, g_xcen, g_ycen, g_... | _____no_output_____ | CC-BY-4.0 | notebooks/StrongLensDemo.ipynb | bombrun/GaiaLQSO |
The un-lensed Gaussian image: Set some SIE lens-model parameters and pack them into an array: | l_amp = 1. # Einstein radius
l_xcen = 0.0 # x position of center
l_ycen = 0.0 # y position of center
l_axrat = 1.0 # minor-to-major axis ratio
l_pa = 0.0 # major-axis position angle (degrees) c.c.w. from x axis
lpar = np.asarray([l_amp, l_xcen, l_ycen, l_axrat, l_pa]) | _____no_output_____ | CC-BY-4.0 | notebooks/StrongLensDemo.ipynb | bombrun/GaiaLQSO |
The following lines will plot the un-lensed and lensed images side by side: | g_image = ldf.gauss_2d(x, y, gpar)
(xg, yg) = ldf.sie_grad(x, y, lpar)
g_lensimage = ldf.gauss_2d(x-xg, y-yg, gpar)
f = plt.imshow(np.hstack((g_image, g_lensimage)), **myargs) | _____no_output_____ | CC-BY-4.0 | notebooks/StrongLensDemo.ipynb | bombrun/GaiaLQSO |
Playing around Ilustration of proper motion magnification | gpar = np.asarray([100.0, 0.01, -0.2, 0.1, 1.0, 0.0])
lpar = np.asarray([1.0, 0.0, 0.0, 1.0, 0.0])
g_image = ldf.gauss_2d(x, y, gpar)
(xg, yg) = ldf.sie_grad(x, y, lpar)
g_lensimage = ldf.gauss_2d(x-xg, y-yg, gpar)
f = plt.imshow(np.hstack((g_image, g_lensimage)), **myargs)
gpar = np.asarray([1.0, 0.05, -0.1, 0.1, 1.0,... | _____no_output_____ | CC-BY-4.0 | notebooks/StrongLensDemo.ipynb | bombrun/GaiaLQSO |
Ilustration of proper motion magnification | gpar = np.asarray([1.0, 0.05, -0.4, 0.1, 1.0, 0.0])
lpar = np.asarray([1.0, 0.0, 0.0, 2.0, 0.0])
g_image = ldf.gauss_2d(x, y, gpar)
(xg, yg) = ldf.sie_grad(x, y, lpar)
g_lensimage = ldf.gauss_2d(x-xg, y-yg, gpar)
f = plt.imshow(np.hstack((g_image, g_lensimage)), **myargs)
gpar = np.asarray([1.0, 0.05, -0.3, 0.1, 1.0, 0... | _____no_output_____ | CC-BY-4.0 | notebooks/StrongLensDemo.ipynb | bombrun/GaiaLQSO |
Ilustration of missing counter part detection | gpar = np.asarray([1.0, 0.05, -0.8 , 0, 1.0, 0.0])
lpar = np.asarray([1.0, 0.0, 0.0, 1.0, 0.0])
g_image = ldf.gauss_2d(x, y, gpar)
(xg, yg) = ldf.sie_grad(x, y, lpar)
g_lensimage = ldf.gauss_2d(x-xg, y-yg, gpar)
f = plt.imshow(np.hstack((g_image, g_lensimage)), **myargs) | _____no_output_____ | CC-BY-4.0 | notebooks/StrongLensDemo.ipynb | bombrun/GaiaLQSO |
Illustration of lens elliptisity | gpar = np.asarray([1.0, 0.05, -1 , 0, 1.0, 0.0])
lpar = np.asarray([1.0, 0.0, 0.0, 0.1, 0.0])
g_image = ldf.gauss_2d(x, y, gpar)
(xg, yg) = ldf.sie_grad(x, y, lpar)
g_lensimage = ldf.gauss_2d(x-xg, y-yg, gpar)
f = plt.imshow(np.hstack((g_image, g_lensimage)), **myargs)
gpar = np.asarray([1.0, 0.05, -0.5 , 0, 1.0, 0.0])... | _____no_output_____ | CC-BY-4.0 | notebooks/StrongLensDemo.ipynb | bombrun/GaiaLQSO |
Tutorial 2: Optimal Control for Continuous State**Week 3, Day 3: Optimal Control****By Neuromatch Academy**__Content creators:__ Zhengwei Wu, Shreya Saxena, Xaq Pitkow__Content reviewers:__ Karolina Stosio, Roozbeh Farhoodi, Saeed Salehi, Ella Batty, Spiros Chavlis, Matt Krause and Michael Waskom **Our 2021 Sponsors,... | # @title Tutorial slides
# @markdown These are the slides for all videos in this tutorial.
from IPython.display import IFrame
IFrame(src=f"https://mfr.ca-1.osf.io/render?url=https://osf.io/8j5rs/?direct%26mode=render%26action=download%26mode=render", width=854, height=480) | _____no_output_____ | MIT | tutorials/W3D3_OptimalControl/student/W3D3_Tutorial2.ipynb | luisarai/NMA2021 |
--- Setup | # Imports
import numpy as np
import scipy
import matplotlib.pyplot as plt
from matplotlib import gridspec
from math import isclose
#@title Figure Settings
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import ipywidgets as widgets
from ipywidgets import interact, fixed, HBox, Layout, VBox, interacti... | _____no_output_____ | MIT | tutorials/W3D3_OptimalControl/student/W3D3_Tutorial2.ipynb | luisarai/NMA2021 |
--- Section 1: Exploring a Linear Dynamical System (LDS) with Open-Loop and Closed-Loop Control | # @title Video 1: Flying Through Space
from ipywidgets import widgets
out2 = widgets.Output()
with out2:
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = 'https://player.bilibili.com/player.html?b... | _____no_output_____ | MIT | tutorials/W3D3_OptimalControl/student/W3D3_Tutorial2.ipynb | luisarai/NMA2021 |
In this example, a cat is trying to catch a mouse in space. The location of the mouse is the goal state $g$, here a static goal. Later on, we will make the goal time varying, i.e. $g(t)$. The cat's location is the state of the system $s_t$. The state has its internal dynamics: think of the cat drifting slowly in space.... | class LDS:
def __init__(self, T: int, ini_state: float, noise_var: float):
self.T = T # time horizon
self.ini_state = ini_state
self.noise_var = noise_var
def dynamics(self, D: float):
s = np.zeros(self.T) # states initialization
s[0] = self.ini_state
noise = np.random.normal(0, self.nois... | Well Done!
| MIT | tutorials/W3D3_OptimalControl/student/W3D3_Tutorial2.ipynb | luisarai/NMA2021 |
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W3D3_OptimalControl/solutions/W3D3_Tutorial2_Solution_799ec42e.py) Interactive Demo 1.1: Explore no control vs. open-loop control vs. closed-loop controlOnce your code above passes the tests, use the interactive demo belo... | #@markdown Make sure you execute this cell to enable the widget!
#@markdown Play around (attentively) with **`a`** and **`L`** to see the effect on the open-loop controlled and closed-loop controlled state.
def simulate_lds(D=0.95, L=-0.3, a=-1., B=2., noise_var=0.1,
T=50, ini_state=2.):
# linea... | _____no_output_____ | MIT | tutorials/W3D3_OptimalControl/student/W3D3_Tutorial2.ipynb | luisarai/NMA2021 |
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W3D3_OptimalControl/solutions/W3D3_Tutorial2_Solution_4ae677cb.py) Interactive Demo 1.2: Exploring the closed-loop setting further Execute the cell below to visualize the MSE between the state and goal, as a function of c... | #@markdown Execute this cell to visualize MSE between state and goal, as a function of control gain
def calculate_plot_mse():
D, B, noise_var, T, ini_state = 0.95, 2., 0.1, 50, 2.
control_gain_array = np.linspace(0.1, 0.9, T)
mse_array = np.zeros(control_gain_array.shape)
for i in range(len(control_gain_array))... | _____no_output_____ | MIT | tutorials/W3D3_OptimalControl/student/W3D3_Tutorial2.ipynb | luisarai/NMA2021 |
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W3D3_OptimalControl/solutions/W3D3_Tutorial2_Solution_a2d58988.py) --- Section 2: Designing an optimal control input using a linear quadratic regulator (LQR) | # @title Video 2: Linear quadratic regulator (LQR)
from ipywidgets import widgets
out2 = widgets.Output()
with out2:
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = 'https://player.bilibili.com/p... | _____no_output_____ | MIT | tutorials/W3D3_OptimalControl/student/W3D3_Tutorial2.ipynb | luisarai/NMA2021 |
Section 2.1 Constraints on the systemNow we will start imposing additional constraints on our system. For example. if you explored different values for $s_{init}$ above, you would have seen very large values for $a_t$ in order to get to the mouse in a short amount of time. However, perhaps the design of our jetpack ma... | class LQR(LDS):
def __init__(self, T, ini_state, noise_var):
super().__init__(T, ini_state, noise_var)
self.goal = np.zeros(T) # The class LQR only supports g=0
def control_gain_LQR(self, D, B, rho):
P = np.zeros(self.T) # Dynamic programming variable
L = np.zeros(self.T - 1) # control gain
... | Well Done!
| MIT | tutorials/W3D3_OptimalControl/student/W3D3_Tutorial2.ipynb | luisarai/NMA2021 |
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W3D3_OptimalControl/solutions/W3D3_Tutorial2_Solution_06c558e2.py) Interactive Demo 2.2: LQR to the origin In this exercise, we will use your new LQR controller to track a static goal at $g=0$. Here, we will explore how v... | #@markdown Make sure you execute this cell to enable the widget!
def simulate_rho(rho=1.):
D, B, T, ini_state, noise_var = 0.9, 2., 50, 2., .1 # state parameter
lqr = LQR(T, ini_state, noise_var)
L = lqr.control_gain_LQR(D, B, rho)
s_lqr, a_lqr = lqr.dynamics_closedloop(D, B, L)
plt.figure(figsiz... | _____no_output_____ | MIT | tutorials/W3D3_OptimalControl/student/W3D3_Tutorial2.ipynb | luisarai/NMA2021 |
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W3D3_OptimalControl/solutions/W3D3_Tutorial2_Solution_f5b9225d.py) Section 2.3: The tradeoff between state cost and control costIn Exercise 2.1, you implemented code to calculate for $J_{state}$ and $J_{control}$ in the c... | #@markdown Execute this cell to visualize the tradeoff between state and control cost
def calculate_plot_costs():
D, B, noise_var, T, ini_state = 0.9, 2., 0.1, 50, 2.
rho_array = np.linspace(0.2, 40, 100)
J_state = np.zeros(rho_array.shape)
J_control = np.zeros(rho_array.shape)
for i in np.arange(len(rho_arra... | _____no_output_____ | MIT | tutorials/W3D3_OptimalControl/student/W3D3_Tutorial2.ipynb | luisarai/NMA2021 |
You should notice the bottom half of a 'C' shaped curve, forming the tradeoff between the state cost and the control cost under optimal linear control.For a desired value of the state cost, we cannot reach a lower control cost than the curve in the above plot. Similarly, for a desired value of the control cost, we must... | # @title Video 3: Tracking a moving goal
from ipywidgets import widgets
out2 = widgets.Output()
with out2:
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = 'https://player.bilibili.com/player.html... | _____no_output_____ | MIT | tutorials/W3D3_OptimalControl/student/W3D3_Tutorial2.ipynb | luisarai/NMA2021 |
In a more realistic situation, the mouse would move around constantly. Suppose you were able to predict the movement of the mouse as it bounces from one place to another. This becomes your goal trajectory $g_t$.When the target state, denoted as $g_t$, is not $0$, the cost function becomes$$ J({\bf a}) = \sum_{t = 0}^{T... | #@markdown Execute this cell to include class
#@markdown for LQR control to desired time-varying goal
class LQR_tracking(LQR):
def __init__(self, T, ini_state, noise_var, goal):
super().__init__(T, ini_state, noise_var)
self.goal = goal
def dynamics_tracking(self, D, B, L):
s = np.zeros(self.T) # sta... | _____no_output_____ | MIT | tutorials/W3D3_OptimalControl/student/W3D3_Tutorial2.ipynb | luisarai/NMA2021 |
Interactive Demo 3: LQR control to desired time-varying goalUse the demo below to explore how LQR tracks a time-varying goal. Starting with the sinusoidal goal function `sin`, investigate how the system reacts with different values of $\rho$ and process noise variance. Next, explore other time-varying goal, such as a ... | #@markdown Make sure you execute this cell to enable the widget!
def simulate_tracking(rho=20., noise_var=0.1, goal_func='sin'):
D, B, T, ini_state = 0.9, 2., 100, 0.
if goal_func == 'sin':
goal = np.sin(np.arange(T) * 2 * np.pi * 5 / T)
elif goal_func == 'step':
goal = np.zeros(T)
goal[int(T /... | _____no_output_____ | MIT | tutorials/W3D3_OptimalControl/student/W3D3_Tutorial2.ipynb | luisarai/NMA2021 |
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W3D3_OptimalControl/solutions/W3D3_Tutorial2_Solution_eb1414c8.py) --- Section 4: Control of an partially observed state using a Linear Quadratic Gaussian (LQG) controller Section 4.1 Introducing the LQG Controller | # @title Video 4: Linear Quadratic Gaussian (LQG) Control
from ipywidgets import widgets
out2 = widgets.Output()
with out2:
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = 'https://player.bilibil... | _____no_output_____ | MIT | tutorials/W3D3_OptimalControl/student/W3D3_Tutorial2.ipynb | luisarai/NMA2021 |
In practice, the controller does not have full access to the state. For example, your jet pack in space may be controlled by Mission Control back on earth! In this case, noisy measurements $m_t$ of the state $s_t$ are taken via radar, and the controller needs to (1) estimate the true state, and (2) design an action ba... | #@markdown Execute this cell to include MyKalmanFilter class
class MyKalmanFilter():
def __init__(self, n_dim_state, n_dim_obs, transition_matrices, transition_covariance, observation_matrices,
observation_covariance, initial_state_mean, initial_state_covariance, control_matrices):
"""
@param n... | _____no_output_____ | MIT | tutorials/W3D3_OptimalControl/student/W3D3_Tutorial2.ipynb | luisarai/NMA2021 |
Take a look at the helper code for the `MyKalmanFilter` class above. In the following exercises, we will use the same notation that we have been using in this tutorial; adapter code has been provided to convert it into the representation `MyKalmanFilter expects`.Use interactive demo below to refresh your memory of how ... | #@markdown Make sure you execute this cell to enable the widget!
def simulate_kf_no_control(D=0.9, B=2., C=1., L=0., T=50, ini_state=5,
proc_noise = 0.1, meas_noise = 0.2):
control_gain = np.ones(T) * L
# Format the above variables into a format acccepted by the Kalman Filter
n_dim_s... | _____no_output_____ | MIT | tutorials/W3D3_OptimalControl/student/W3D3_Tutorial2.ipynb | luisarai/NMA2021 |
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W3D3_OptimalControl/solutions/W3D3_Tutorial2_Solution_5ecbeb0c.py) Interactive Demo 4.2: LQG controller output with varying control gainsNow let's implement the Kalman filter with closed-loop feedback with the controller.... | #@markdown Make sure you execute this cell to enable the widget!
def simulate_kf_with_control(D=0.9, B=2., C=1., L=-0.1, T=50, ini_state=5,
proc_noise = 0.1, meas_noise = 0.2):
control_gain = np.ones(T)*L
# Format the above variables into a format acccepted by the Kalman Filter
n_dim... | _____no_output_____ | MIT | tutorials/W3D3_OptimalControl/student/W3D3_Tutorial2.ipynb | luisarai/NMA2021 |
Interactive Demo 4.3: LQG with varying control effort costsNow let's see the performance of the LQG controller. We will use an LQG controller gain, where the control gain is from a system with an infinite-horizon. In this case, the optimal control gain turns out to be a constant. Vary the value of $\rho$ from $0$ to l... | #@markdown Execute this cell to include helper function for LQG
class LQG(MyKalmanFilter, LQR):
def __init__(self, T, n_dim_state, n_dim_obs,
transition_matrices, transition_covariance, observation_matrices,
observation_covariance, initial_state_mean, initial_state_covariance, control... | _____no_output_____ | MIT | tutorials/W3D3_OptimalControl/student/W3D3_Tutorial2.ipynb | luisarai/NMA2021 |
Interactive Demo 4.4: How does the process noise and the measurement noise influence the controlled state and desired action?Process noise $w_t$ (proc_noise) and measurement noise $v_t$ (meas_noise) have very different effects on the controlled state. (a) To visualize this, play with the sliders to get an intuition fo... | #@markdown Make sure you execute this cell to enable the widget!
def lqg_slider(D=0.9, B=2., C=1., T=50, ini_state=5,
proc_noise=2.9, meas_noise=0., rho=1.):
# Format the above variables into a format acccepted by the Kalman Filter
# Format the above variables into a format acccepte... | _____no_output_____ | MIT | tutorials/W3D3_OptimalControl/student/W3D3_Tutorial2.ipynb | luisarai/NMA2021 |
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W3D3_OptimalControl/solutions/W3D3_Tutorial2_Solution_baaf321d.py) Section 4.2 Noise effects on the LQGWe can now quantify how the state cost and control costs changes when we change the process and measurement noise leve... | #@markdown Execute this cell to to quantify the dependence of state and control
#@markdown cost on process and measurement noise (takes ~20 seconds)
D = 0.9 # state parameter
B = 2 # control parameter
C = 1 # measurement parameter
noise_var = 0.1
T = 200 # time horizon
ini_state = 5 # initial state
process_n... | _____no_output_____ | MIT | tutorials/W3D3_OptimalControl/student/W3D3_Tutorial2.ipynb | luisarai/NMA2021 |
spotiPylot The collaborative playlist generator. By: David AndexlerProof-of-ConceptDescription: A Python application that allows users to generate collaborative playlists based on music each participant is likely to enjoy. In the current iteration, best results will be obtained with fewer than five participants.Overvi... | import matplotlib.pyplot as plt
import numpy as np
import os
import pandas as pd
import seaborn as sns
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
import util | _____no_output_____ | MIT | code/concept.ipynb | dandexler/spotify-exercise |
Loading Environment Variables | SPOTIFY_CLIENT_ID = os.environ['SPOTIFY_CLIENT_ID']
SPOTIFY_CLIENT_SECRET = os.environ['SPOTIFY_CLIENT_SECRET']
SPOTIFY_REDIRECT_URI = 'http://localhost:8888/callback/'
username = os.environ['SPOTIFY_USER_ID'] | _____no_output_____ | MIT | code/concept.ipynb | dandexler/spotify-exercise |
Authorization Client Authorization | scope = 'playlist-modify-public'
user_token = spotipy.util.prompt_for_user_token(username, scope, SPOTIFY_CLIENT_ID, SPOTIFY_CLIENT_SECRET, SPOTIFY_REDIRECT_URI)
spotify = spotipy.Spotify(auth=user_token) | _____no_output_____ | MIT | code/concept.ipynb | dandexler/spotify-exercise |
Data Acquisition Get Playlist TracksFor demonstration purposes, three pre-populated playlists are utilized, representing three independent users using the application to collaborate on a shared playlist. The example playlists have a general "theme" and the tracks were selected based only on the "theme" and my genera... | users = util.get_users()
playlist_information = util.get_playlists(spotify=spotify, users=users)
playlist_information | Enter Spotify username or user ID: dandexler
Enter another user? [y/n] n
Users selected: ['dandexler']
User: dandexler
Playlist Information:
name git init Playlist
description spotiPylot example playlist
id ... | MIT | code/concept.ipynb | dandexler/spotify-exercise |
Table 01: Demo playlists and identifying information. Format Final DataFrameSalient audio features needed for the preliminary analysis are extracted and formatted. Information about each audio feature can be found at Spotify for Developers . | final_df = util.get_track_features(spotify=spotify, playlist_information=playlist_information)
final_df = final_df.drop(columns=['track_id', 'type', 'id', 'uri', 'track_href', 'analysis_url', 'time_signature'])
final_df | _____no_output_____ | MIT | code/concept.ipynb | dandexler/spotify-exercise |
Table 02: Combined Tracks and Audio Features. Analysis Exploratory Data AnalysisPlaylist name, artist name, track name, and time signature were dropped from the EDA table. Kernel density estimates were generated for each numeric variable. | util.plot_distributions(final_df, drop=['playlist_name', 'artist_name', 'track_name']) | _____no_output_____ | MIT | code/concept.ipynb | dandexler/spotify-exercise |
Figure 01 - Figure 12: Distributions of Audio Features. Clustering Using Fuzzy SetsThe aim of this project is to identify the joint similarities between all users (represented by each playlist). Some clustering techniques force all observations to be in one of the identified clusters. In this concept presentation... | from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
import skfuzzy as fuzz | _____no_output_____ | MIT | code/concept.ipynb | dandexler/spotify-exercise |
Principal Component Analysis Projecting the playlist features into fewer dimensions. Standardizing the FeaturesFeatures were standardized using scikit-learn's StandardScaler. | final_df_drop = final_df.drop(columns=['playlist_name', 'artist_name', 'track_name'])
stdz_values = StandardScaler().fit_transform(final_df_drop) | _____no_output_____ | MIT | code/concept.ipynb | dandexler/spotify-exercise |
PCAThe number of principal components was selected by roughly optimizing variance explained against complexity. Six principal components were selected to explain ~73% of the variance in the playlists. If I selected two dimensions, variance explained would be ~ 35%. Though I am giving up visualization capabilities, I b... | components = [x+1 for x in range(12)]
pca_obj = PCA(n_components=12)
pca_obj.fit_transform(stdz_values)
# Scree plot and selected number of principal components
p1 = sns.pointplot(x=components, y=pca_obj.explained_variance_ratio_)
p1.set(xlabel='Number Components', ylabel='Variance Explained Ratio')
plt.axvline(5, 0,... | _____no_output_____ | MIT | code/concept.ipynb | dandexler/spotify-exercise |
Figure 13: Scree plot of variance explained against number of principal components. | # Cumulative sum of variance explained graph with selected components
p2 = sns.pointplot(x=components, y=np.cumsum(pca_obj.explained_variance_ratio_))
p2.set(xlabel='Number Components', ylabel='Cumulative Variance Explained')
plt.axvline(5, 0, 1, color='r') | _____no_output_____ | MIT | code/concept.ipynb | dandexler/spotify-exercise |
Figure 14: Variance explained against number of prinicpal components. PCA, continued.Six principal components were selected and fitted to the standardized data. | pca_obj = PCA(n_components=2)
pca_data = pca_obj.fit_transform(stdz_values)
pcaDF = pd.DataFrame(pca_data, columns = ['pc1', 'pc2', 'pc3', 'pc4', 'pc5', 'pc6'])
pcaDF | _____no_output_____ | MIT | code/concept.ipynb | dandexler/spotify-exercise |
Table 04: Three original playlist audio features projected along six principal components. Fuzzy C-Means ClusteringThree fuzzy clusters are set. Max iterations will be 1000 unless error stopping criterion=0.005. Seed set to 1234 for reproducibility. Visualization of clusters are not possible for 6-dimensional PCA com... | cntr, u, u0, d, jm, p, fpc = fuzz.cluster.cmeans(data=pcaDF, c=3, m=2, error=0.005, maxiter=1000, init=None, seed=1234)
# Returns array rows x clusters, which are the centers of each feature for each cluster.
u0 | _____no_output_____ | MIT | code/concept.ipynb | dandexler/spotify-exercise |
Creating the Playlist Using the Fuzzy C-Means clusters To populate the playlist, I am looking for 100 songs that have the highest membership in all three fuzzy c-means clusters. This data was obtained from a Kaggle dataset and contains 130,000 tracks and their corresponding audio features. This data set was updated... | new_tracks = pd.read_csv("C:/Users/dande/Documents/Projects/spotiPylot/data/SpotifyAudioFeaturesApril2019.csv")
new_tracks | _____no_output_____ | MIT | code/concept.ipynb | dandexler/spotify-exercise |
Table 05: Audio features of 130,000 tracks on Spotify as of April 2019. PCA on the New DataBefore clustering, the new data are projected to six principal components to mirror the playlist data. | new_features = new_tracks.loc[:,final_df_drop.columns]
new_stdz_values = StandardScaler().fit_transform(new_features)
new_pca_obj = PCA(n_components=6)
new_pca_data = new_pca_obj.fit_transform(new_stdz_values)
new_pcaDF = pd.DataFrame(new_pca_data, columns = ['pc1', 'pc2', 'pc3', 'pc4', 'pc5', 'pc6'])
new_pcaDF | _____no_output_____ | MIT | code/concept.ipynb | dandexler/spotify-exercise |
Table 06: Six principal components of the new data. Determining fuzzy c-means cluster membershipRandomly sample 150 songs from the PCA dataframe, use the fuzzy c-means to predict fuzzy partition coefficient. After n random draws, the sample with the highest FPC is loaded into the playlist. Had to remove seed to get d... | fpc = 0
for i in range(1000):
new_pca_sample = new_pcaDF.sample(100)
new_model = fuzz.cluster.cmeans_predict(new_pca_sample, cntr, 2, error=0.005, maxiter=1000)
if new_model[-1] > fpc:
new_df = new_pca_sample.copy() # If the FPC is greater than previous, saves FPC and the indices of the dataframe
... | _____no_output_____ | MIT | code/concept.ipynb | dandexler/spotify-exercise |
Retrieving Selected TracksRetrieves by index. | final_full_tracks = new_tracks.iloc[new_df.index,:]
final_full_tracks | _____no_output_____ | MIT | code/concept.ipynb | dandexler/spotify-exercise |
Table 07: Tracks selected by the clustering algorithm. Creating the Playlist and Populating with Clustered TracksWARNING: THIS WILL CREATE A PLAYLIST ON YOUR PROFILE FOR EACH TIME YOU RUN IT. RUN ONCE. | util.create_playlist(tracks=final_full_tracks, spotify=spotify, username=username)
| _____no_output_____ | MIT | code/concept.ipynb | dandexler/spotify-exercise |
Summary of Trending Topics for the DayIn this script we will pull data on what's trending for the day in Singapore. We will use [Google Trends](https://trends.google.com/trends/?geo=SG) as the primary platform to get the latest news/information on what is trending for the day. | import tagui as t
#Visiting the URL to get the daily trends for today
t.init(visual_automation = True, chrome_browser = True)
t.url('https://trends.google.com/trends/trendingsearches/daily?geo=SG')
header1 = t.read('/html/body/div[2]/div[2]/div/div[2]/div/div[1]/ng-include/div/div/div/div/md-list[1]/feed-item/ng-includ... | _____no_output_____ | MIT | .ipynb_checkpoints/Summary of Trending Topics for the Day-checkpoint.ipynb | Coolbreeze151/RPA-with-TagUI |
Record Scratching SimulatorThis notebook allows you to read an audio file and modify the signal by adding a scratching effect. The scratching effect is simulated by taking a short audio signal, speeding it up in the forward followed by the reverse direction, and inserting the modified signal into the original audio. T... | %%bash
!(stat -t /usr/local/lib/*/dist-packages/google/colab > /dev/null 2>&1) && exit
rm -rf record-scratching/
git clone https://github.com/gened1080/record-scratching.git
pip install pydub
sudo apt-get install libasound-dev portaudio19-dev libportaudio2 libportaudiocpp0 ffmpeg
# Import relevant packages
import sys
... | _____no_output_____ | MIT | Simulate_Scratching.ipynb | gened1080/record-scratching |
Read audio file and plot signalWe start by creating an object of the `AudioS` class, which also calls the method for reading an audio file. The files for reading need to be placed in the samples directory. After the file is read, the audio signal is extracted and plotted below. | # create object of AudioS class and read file
scr = asc.AudioS()
# plot the audio signal in the file
scr.plot_signal(scr.original_sound, 'original') | ----------------------
Enter the audio filename you want to read including the extension: ahh.wav
----------------------
| MIT | Simulate_Scratching.ipynb | gened1080/record-scratching |
Play AudioThe original audio track can be played below | # play audiotrack
ipd.Audio(scr.original_signal, rate=scr.framerate) | _____no_output_____ | MIT | Simulate_Scratching.ipynb | gened1080/record-scratching |
Scratching EffectThe `scratch_audio` method implements the scratching effect simulator. The user is asked to specify the amount of speedup during a scratch. We assume that the scratch is done over a quarter rotation of the record. Then using the user-entered speedup, we determine the duration of the scratch. The user ... | # Runs the scratching effect simulator
scr.scratch_audio(scr.original_sound) | ----------------------
Do you want to manually enter scratching parameters (y/n): n
----------------------
| MIT | Simulate_Scratching.ipynb | gened1080/record-scratching |
Play Audio with Scratch EffectThe modified audio with the scratch effect can be played below. | # Play audio
ipd.Audio(scr.scratched_signal, rate=scr.framerate)
| _____no_output_____ | MIT | Simulate_Scratching.ipynb | gened1080/record-scratching |
> This is one of the 100 recipes of the [IPython Cookbook](http://ipython-books.github.io/), the definitive guide to high-performance scientific computing and data science in Python. 3.6. Creating a custom Javascript widget in the notebook: a spreadsheet editor for Pandas You need IPython 2.0+ for this recipe. Besides... | from IPython.html import widgets
from IPython.display import display
from IPython.utils.traitlets import Unicode | _____no_output_____ | BSD-2-Clause | notebooks/chapter03_notebook/06_widgets.ipynb | khanparwaz/PythonProjects |
2. We create a new widget. The `value` trait will contain the JSON representation of the entire table. This trait will be synchronized between Python and Javascript thanks to IPython 2.0's widget machinery. | class HandsonTableWidget(widgets.DOMWidget):
_view_name = Unicode('HandsonTableView', sync=True)
value = Unicode(sync=True) | _____no_output_____ | BSD-2-Clause | notebooks/chapter03_notebook/06_widgets.ipynb | khanparwaz/PythonProjects |
3. Now we write the Javascript code for the widget. The three important functions that are responsible for the synchronization are: * `render` for the widget initialization * `update` for Python to Javascript update * `handle_table_change` for Javascript to Python update | %%javascript
var table_id = 0;
require(["widgets/js/widget"], function(WidgetManager){
// Define the HandsonTableView
var HandsonTableView = IPython.DOMWidgetView.extend({
render: function(){
// Initialization: creation of the HTML elements
// for our widget.
... | _____no_output_____ | BSD-2-Clause | notebooks/chapter03_notebook/06_widgets.ipynb | khanparwaz/PythonProjects |
4. Now, we have a synchronized table widget that we can already use. But we'd like to integrate it with Pandas. To do this, we create a light wrapper around a `DataFrame` instance. We create two callback functions for synchronizing the Pandas object with the IPython widget. Changes in the GUI will automatically trigger... | from io import StringIO # Python 2: from StringIO import StringIO
import numpy as np
import pandas as pd
class HandsonDataFrame(object):
def __init__(self, df):
self._df = df
self._widget = HandsonTableWidget()
self._widget.on_trait_change(self._on_data_changed,
... | _____no_output_____ | BSD-2-Clause | notebooks/chapter03_notebook/06_widgets.ipynb | khanparwaz/PythonProjects |
5. Now, let's test all that! We first create a random `DataFrame`. | data = np.random.randint(size=(3, 5), low=100, high=900)
df = pd.DataFrame(data)
df | _____no_output_____ | BSD-2-Clause | notebooks/chapter03_notebook/06_widgets.ipynb | khanparwaz/PythonProjects |
6. We wrap it in a `HandsonDataFrame` and show it. | ht = HandsonDataFrame(df)
ht.show() | _____no_output_____ | BSD-2-Clause | notebooks/chapter03_notebook/06_widgets.ipynb | khanparwaz/PythonProjects |
7. We can now *change* the values interactively, and they will be changed in Python accordingly. | ht.to_dataframe() | _____no_output_____ | BSD-2-Clause | notebooks/chapter03_notebook/06_widgets.ipynb | khanparwaz/PythonProjects |
Query Registry Users Before executing this notebook, complete [step 2](./2_WorkflowRegistrySetup.ipynb). | lifemonitor_root = "/home/simleo/git/life_monitor"
%cd -q {lifemonitor_root}
import requests
lm_base_url = "https://localhost:8443"
lm_token_url = f"{lm_base_url}/oauth2/token"
# Get info on the "seek" registry
!docker-compose exec lm /bin/bash -c "flask registry show seek"
# Copy registry credentials from the above du... | /usr/lib/python3/dist-packages/urllib3/connectionpool.py:860: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
InsecureRequestWarning)
| MIT | examples/3_WorkflowRegistryUsers.ipynb | kikkomep/life_monitor |
Módulo 2: Scraping con Selenium LATAM AirlinesVamos a scrapear el sitio de Latam para averiguar datos de vuelos en funcion el origen y destino, fecha y cabina. La información que esperamos obtener de cada vuelo es:- Precio(s) disponibles- Horas de salida y llegada (duración)- Información de las escalas¡Empecemos! | url = 'https://www.latam.com/es_ar/apps/personas/booking?fecha1_dia=20&fecha1_anomes=2019-12&auAvailability=1&ida_vuelta=ida&vuelos_origen=Buenos%20Aires&from_city1=BUE&vuelos_destino=Madrid&to_city1=MAD&flex=1&vuelos_fecha_salida_ddmmaaaa=20/12/2019&cabina=Y&nadults=1&nchildren=0&ninfants=0&cod_promo='
from selenium i... | _____no_output_____ | MIT | NoteBooks/Curso de WebScraping/Unificado/web-scraping-master/Clases/Módulo 3_ Scraping con Selenium/M3C4. Scrapeando escalas y tarifas - Script.ipynb | Alejandro-sin/Learning_Notebooks |
Obtenemos la información de la hora de salida, llegada y duración del vuelo | # Hora de salida
vuelo.find_element_by_xpath('.//div[@class="departure"]/time').get_attribute('datetime')
# Hora de llegada
vuelo.find_element_by_xpath('.//div[@class="arrival"]/time').get_attribute('datetime')
# Duración del vuelo
vuelo.find_element_by_xpath('.//span[@class="duration"]/time').get_attribute('datetime')... | _____no_output_____ | MIT | NoteBooks/Curso de WebScraping/Unificado/web-scraping-master/Clases/Módulo 3_ Scraping con Selenium/M3C4. Scrapeando escalas y tarifas - Script.ipynb | Alejandro-sin/Learning_Notebooks |
Clase 13En esta clase obtendremos la información de las escalas que se encuentran en el modal que aparece al clickear sobre el botón de escalas | segmento = segmentos[0]
# Origen
segmento.find_element_by_xpath('.//div[@class="departure"]/span[@class="ground-point-name"]').text
# Hora de salida
segmento.find_element_by_xpath('.//div[@class="departure"]/time').get_attribute('datetime') | _____no_output_____ | MIT | NoteBooks/Curso de WebScraping/Unificado/web-scraping-master/Clases/Módulo 3_ Scraping con Selenium/M3C4. Scrapeando escalas y tarifas - Script.ipynb | Alejandro-sin/Learning_Notebooks |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.