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 input to LMoutput of 1 as target to our LM, create LM & build predictionsAs usual, we start by creating our batches & validation vatches
# 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) save_array(model_path + 'valid_data.bc', val_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 == encoding length. In the above example W would be a vector of: ```w1, w2, w3```This lets you do Deep Learning very easily with categorical variablesKeras returns *classes* as a single column, so we convert to 1Ht.
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 single col of all imgs trn_labels.shape # One-Hot Encoded: 2 bit-width col <--> 2 classes trn_classes[:4] # taking a look at 1st 4 classes trn_labels[:4] # seeing the 1st 4 labels are 1Ht encoded
_____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) (None, 2) 2002 dense_input_3[0][0] ==================================================================================================== Total params: 2,002 Trainable params: 2,002 Non-trainable params: 0 ____________________________________________________________________________________________________
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 [==============================] - 0s - loss: 0.0221 - acc: 0.9915 - val_loss: 0.2109 - val_acc: 0.9400
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 to either 'Cat' or 'Dog'This is actually what most amatuer Machine Learning researchers do. They take a pretrained model, they grab the outputs, stick it into a linear model -- and it actually often works pretty well!To get this 94% accuracy, we haven't done used any magical libraries at all. We just grabbed our batches up, we turned the images into a Numpy array, we took the Numpy array and ran ```model.predict(..)``` on them, we grabbed our labels and One-Hot Encoded them, and finally we took the 1Ht Enc labels and the 1,000 probabilities and fed them to a Linear Model with a thousand inputs and 2 outputs - and trained it and ended up with a validationa ccuracy of ```0.9400``` 1.3.3 About Activation FunctionsThe last thing we're going to do is take this and turn it into a finetuning model. For that we need to understand activation functions. We've been looking at our Linear Model as a series of matrix multiplies. But a series of matrix multiplies is itself a matrix multiply --> a series of linear models is itself a linear model. Deep Learning must be doing something more than just this. At each stage (layer) it is putting the activations, the results of the previous layer, through a non-Linearity of some sort. ```tanh```, ```sigmoid```, ```max(0,x)``` (ReLU), etc.Using the activation functions at each layer, we now have a genuine, modern (ca.2017), Deep Learning Neural Network. This kind of NN is capable of approximating any given function of arbitrary complexity.A series of matrix-multiplies & activation (sa. ReLU) is actually what's going on in a DLNN.Remember how we defined our model:```lm = Sequential([Dense(2, activation='softmax', input_shape(1000,))])```And the definition of a fully connected layer in the original VGG:```model.add(Dense(4096, activation='relu'))```What that ```activation``` parameter says is "after you do the Matrix Π, do a activation of (in this case): ```max(0, x)```" 2 Modifying the Model 2.1 Retrain last layer's Linear ModelSo what we need to do is take our final layer, which has a Matrix Multip and & activation function, and we're going to remove it. To understand why, take a look at our DLNN layers:
vgg.model.summary()
____________________________________________________________________________________________________ Layer (type) Output Shape Param # Connected to ==================================================================================================== lambda_1 (Lambda) (None, 3, 224, 224) 0 lambda_input_1[0][0] ____________________________________________________________________________________________________ zeropadding2d_1 (ZeroPadding2D) (None, 3, 226, 226) 0 lambda_1[0][0] ____________________________________________________________________________________________________ convolution2d_1 (Convolution2D) (None, 64, 224, 224) 1792 zeropadding2d_1[0][0] ____________________________________________________________________________________________________ zeropadding2d_2 (ZeroPadding2D) (None, 64, 226, 226) 0 convolution2d_1[0][0] ____________________________________________________________________________________________________ convolution2d_2 (Convolution2D) (None, 64, 224, 224) 36928 zeropadding2d_2[0][0] ____________________________________________________________________________________________________ maxpooling2d_1 (MaxPooling2D) (None, 64, 112, 112) 0 convolution2d_2[0][0] ____________________________________________________________________________________________________ zeropadding2d_3 (ZeroPadding2D) (None, 64, 114, 114) 0 maxpooling2d_1[0][0] ____________________________________________________________________________________________________ convolution2d_3 (Convolution2D) (None, 128, 112, 112) 73856 zeropadding2d_3[0][0] ____________________________________________________________________________________________________ zeropadding2d_4 (ZeroPadding2D) (None, 128, 114, 114) 0 convolution2d_3[0][0] ____________________________________________________________________________________________________ convolution2d_4 (Convolution2D) (None, 128, 112, 112) 147584 zeropadding2d_4[0][0] ____________________________________________________________________________________________________ maxpooling2d_2 (MaxPooling2D) (None, 128, 56, 56) 0 convolution2d_4[0][0] ____________________________________________________________________________________________________ zeropadding2d_5 (ZeroPadding2D) (None, 128, 58, 58) 0 maxpooling2d_2[0][0] ____________________________________________________________________________________________________ convolution2d_5 (Convolution2D) (None, 256, 56, 56) 295168 zeropadding2d_5[0][0] ____________________________________________________________________________________________________ zeropadding2d_6 (ZeroPadding2D) (None, 256, 58, 58) 0 convolution2d_5[0][0] ____________________________________________________________________________________________________ convolution2d_6 (Convolution2D) (None, 256, 56, 56) 590080 zeropadding2d_6[0][0] ____________________________________________________________________________________________________ zeropadding2d_7 (ZeroPadding2D) (None, 256, 58, 58) 0 convolution2d_6[0][0] ____________________________________________________________________________________________________ convolution2d_7 (Convolution2D) (None, 256, 56, 56) 590080 zeropadding2d_7[0][0] ____________________________________________________________________________________________________ maxpooling2d_3 (MaxPooling2D) (None, 256, 28, 28) 0 convolution2d_7[0][0] ____________________________________________________________________________________________________ zeropadding2d_8 (ZeroPadding2D) (None, 256, 30, 30) 0 maxpooling2d_3[0][0] ____________________________________________________________________________________________________ convolution2d_8 (Convolution2D) (None, 512, 28, 28) 1180160 zeropadding2d_8[0][0] ____________________________________________________________________________________________________ zeropadding2d_9 (ZeroPadding2D) (None, 512, 30, 30) 0 convolution2d_8[0][0] ____________________________________________________________________________________________________ convolution2d_9 (Convolution2D) (None, 512, 28, 28) 2359808 zeropadding2d_9[0][0] ____________________________________________________________________________________________________ zeropadding2d_10 (ZeroPadding2D) (None, 512, 30, 30) 0 convolution2d_9[0][0] ____________________________________________________________________________________________________ convolution2d_10 (Convolution2D) (None, 512, 28, 28) 2359808 zeropadding2d_10[0][0] ____________________________________________________________________________________________________ maxpooling2d_4 (MaxPooling2D) (None, 512, 14, 14) 0 convolution2d_10[0][0] ____________________________________________________________________________________________________ zeropadding2d_11 (ZeroPadding2D) (None, 512, 16, 16) 0 maxpooling2d_4[0][0] ____________________________________________________________________________________________________ convolution2d_11 (Convolution2D) (None, 512, 14, 14) 2359808 zeropadding2d_11[0][0] ____________________________________________________________________________________________________ zeropadding2d_12 (ZeroPadding2D) (None, 512, 16, 16) 0 convolution2d_11[0][0] ____________________________________________________________________________________________________ convolution2d_12 (Convolution2D) (None, 512, 14, 14) 2359808 zeropadding2d_12[0][0] ____________________________________________________________________________________________________ zeropadding2d_13 (ZeroPadding2D) (None, 512, 16, 16) 0 convolution2d_12[0][0] ____________________________________________________________________________________________________ convolution2d_13 (Convolution2D) (None, 512, 14, 14) 2359808 zeropadding2d_13[0][0] ____________________________________________________________________________________________________ maxpooling2d_5 (MaxPooling2D) (None, 512, 7, 7) 0 convolution2d_13[0][0] ____________________________________________________________________________________________________ flatten_1 (Flatten) (None, 25088) 0 maxpooling2d_5[0][0] ____________________________________________________________________________________________________ dense_3 (Dense) (None, 4096) 102764544 flatten_1[0][0] ____________________________________________________________________________________________________ dropout_1 (Dropout) (None, 4096) 0 dense_3[0][0] ____________________________________________________________________________________________________ dense_4 (Dense) (None, 4096) 16781312 dropout_1[0][0] ____________________________________________________________________________________________________ dropout_2 (Dropout) (None, 4096) 0 dense_4[0][0] ____________________________________________________________________________________________________ dense_5 (Dense) (None, 1000) 4097000 dropout_2[0][0] ==================================================================================================== Total params: 138,357,544 Trainable params: 138,357,544 Non-trainable params: 0 ____________________________________________________________________________________________________
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 pop off the last layer, and set all remaining layers to be fixed, so they aren't altered.
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(..)``` instead of ```model.function(..)```So let's do that and see what we get after 2 epochs of training:We'll also define a function for fitting models to save time typing.
# 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 number of your model when keeping a research journal of your results.
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 Kaggle you can get.**If you want to push yourself** -- see if you can do the same thing by writing all the code yourself. Don't use the class notebooks at all -- build it all from scratch.**If you want to go *Even* further** -- see if you can enter another Kaggle competition (Galaxy Zoo, Plankton, Statefarm Distracted Driver, etc)-- end of lecture 2 --10 May 2017 WNx We can look at the earlier prediction examples visualizations by redefiing *probs* and *preds* and re-using our earlier code.
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. remote: Counting objects: 100% (82/82), done. remote: Compressing objects: 100% (60/60), done. remote: Total 82 (delta 33), reused 53 (delta 18), pack-reused 0 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.txt' running build_ext Creating /usr/local/lib/python3.7/dist-packages/echovpr.egg-link (link to .) Adding echovpr 1.0 to easy-install.pth file Installed /content/EchoVPR/src Processing dependencies for echovpr==1.0 Finished processing dependencies for echovpr==1.0
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 = hiddenReprTrain.shape # Get Validation Indices TestInd, ValidationInd = getValidationIndices(1, nOutput)
_____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 = alpha, gamma = gamma, rho = 0.99) model = _ESN_model_(0) exp = ESN_Exp(model, hiddenReprTrain, hiddenReprTest, TestInd, ValidationInd, tol) results = exp.train_esn(nEpoch=nEpoch, lR=lR, nBatch=nBatch, returnData=True, returnDataAll=False) results['AccTest'][-1].mean()
_____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, sparsity = getSparsity(nCon, nRes), alpha = alpha, gamma = gamma, rho = 0.99) model = _SPARCE_model_(0) exp = ESN_Exp(model, hiddenReprTrain, hiddenReprTest, TestInd, ValidationInd, tol) results = exp.train_sparce(nEpoch=nEpoch, lR=lR, nBatch=nBatch, quantile=quantile, lr_divide_factor=lrDiv, returnData=True, returnDataAll=False) results['AccTest'][-1].mean()
_____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_datetime.dt.weekday taxi['pickup_weekofyear'] = taxi.tpep_pickup_datetime.dt.weekofyear taxi['pickup_hour'] = taxi.tpep_pickup_datetime.dt.hour taxi['pickup_minute'] = taxi.tpep_pickup_datetime.dt.minute taxi['pickup_year_seconds'] = (taxi.tpep_pickup_datetime - datetime.datetime(2019, 1, 1, 0, 0, 0)).dt.seconds taxi['pickup_week_hour'] = (taxi.pickup_weekday * 24) + taxi.pickup_hour taxi['passenger_count'] = taxi.passenger_count.astype(float).fillna(-1) taxi = taxi.fillna(value={'VendorID': 'missing', 'RatecodeID': 'missing', 'store_and_fwd_flag': 'missing' }) taxi = taxi.persist()
_____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_hour', 'pickup_minute', 'pickup_year_seconds', 'pickup_week_hour', 'passenger_count'] categorical_feat = ['VendorID', 'RatecodeID', 'store_and_fwd_flag', 'PULocationID', 'DOLocationID'] features = numeric_feat + categorical_feat y_col = 'total_amount' pipeline = Pipeline(steps=[ ('categorize', Categorizer(columns=categorical_feat)), ('onehot', DummyEncoder(columns=categorical_feat)), ('scale', ColumnTransformer( transformers=[('num', StandardScaler(), numeric_feat)], remainder='passthrough', )), ('clf', ElasticNet(normalize=False, max_iter=100)), ]) params = { 'clf__l1_ratio': np.arange(0, 1.01, 0.01), 'clf__alpha': [0, 0.5, 1, 2], } grid_search = GridSearchCV(pipeline, params, cv=3)
_____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.[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](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'll go through training a deep residual network with jaxopt.
%%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 import optax import tensorflow_datasets as tfds import tensorflow as tf from matplotlib import pyplot as plt Flags = collections.namedtuple( "Flags", [ "l2reg", # amount of L2 regularization in the objective "learning_rate", # learning rate for the Adam optimizer "epochs", # number of passes over the dataset "dataset", # one of "mnist", "kmnist", "emnist", "fashion_mnist", "cifar10", "cifar100" "model", # model architecture, one of "resnet1", "resnet18", "resnet34" "train_batch_size", # Batch size at train time "test_batch_size" # Batch size at test time ]) FLAGS = Flags( l2reg=0.0001, learning_rate=0.001, epochs=50, dataset="cifar10", model="resnet18", train_batch_size=128, test_batch_size=128) def load_dataset(split, *, is_training, batch_size): version = 3 ds, ds_info = tfds.load( f"{FLAGS.dataset}:{version}.*.*", as_supervised=True, # remove useless keys split=split, with_info=True) ds = ds.cache().repeat() if is_training: ds = ds.shuffle(10 * batch_size, seed=0) ds = ds.batch(batch_size) return iter(tfds.as_numpy(ds)), ds_info class ResNetBlock(nn.Module): """ResNet block.""" filters: int conv: Any norm: Any act: Callable strides: Tuple[int, int] = (1, 1) @nn.compact def __call__(self, x,): residual = x y = self.conv(self.filters, (3, 3), self.strides)(x) y = self.norm()(y) y = self.act(y) y = self.conv(self.filters, (3, 3))(y) y = self.norm(scale_init=nn.initializers.zeros)(y) if residual.shape != y.shape: residual = self.conv(self.filters, (1, 1), self.strides, name='conv_proj')(residual) residual = self.norm(name='norm_proj')(residual) return self.act(residual + y) class ResNet(nn.Module): """ResNetV1.""" stage_sizes: Sequence[int] block_cls: Any num_classes: int num_filters: int = 64 dtype: Any = jnp.float32 act: Callable = nn.relu @nn.compact def __call__(self, x, train: bool = True): conv = partial(nn.Conv, use_bias=False, dtype=self.dtype) norm = partial(nn.BatchNorm, # use_running_average=True, use_running_average=not train, momentum=0.99, epsilon=0.001, dtype=self.dtype) x = conv(self.num_filters, (7, 7), (2, 2), padding=[(3, 3), (3, 3)], name='conv_init')(x) x = norm(name='bn_init')(x) x = nn.relu(x) x = nn.max_pool(x, (3, 3), strides=(2, 2), padding='SAME') for i, block_size in enumerate(self.stage_sizes): for j in range(block_size): strides = (2, 2) if i > 0 and j == 0 else (1, 1) x = self.block_cls(self.num_filters * 2 ** i, strides=strides, conv=conv, norm=norm, act=self.act)(x) x = jnp.mean(x, axis=(1, 2)) x = nn.Dense(self.num_classes, dtype=self.dtype)(x) x = jnp.asarray(x, self.dtype) return x ResNet1 = partial(ResNet, stage_sizes=[1], block_cls=ResNetBlock) ResNet18 = partial(ResNet, stage_sizes=[2, 2, 2, 2], block_cls=ResNetBlock) ResNet34 = partial(ResNet, stage_sizes=[3, 4, 6, 3], block_cls=ResNetBlock)
_____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", is_training=False, batch_size=FLAGS.test_batch_size) input_shape = (1,) + ds_info.features["image"].shape num_classes = ds_info.features["label"].num_classes iter_per_epoch_train = ds_info.splits['train'].num_examples // FLAGS.train_batch_size iter_per_epoch_test = ds_info.splits['test'].num_examples // FLAGS.test_batch_size class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck'] mb_images, mb_labels = next(train_ds) _, axes = plt.subplots(nrows=4, ncols=4, figsize=(6, 6)) for i in range(4): for j in range(4): k = i * 4 + j axes[i, j].imshow(mb_images[k], cmap=plt.cm.gray_r, interpolation="nearest") axes[i, j].set_axis_off() axes[i, j].set_title(class_names[mb_labels[k]]) # Set up model. if FLAGS.model == "resnet1": net = ResNet1(num_classes=num_classes) elif FLAGS.model == "resnet18": net = ResNet18(num_classes=num_classes) elif FLAGS.model == "resnet34": net = ResNet34(num_classes=num_classes) else: raise ValueError("Unknown model.") def predict(params, inputs, batch_stats, train=False): x = inputs.astype(jnp.float32) / 255. all_params = {"params": params, "batch_stats": batch_stats} if train: # Returns logits and net_state (which contains the key "batch_stats"). return net.apply(all_params, x, train=train, mutable=["batch_stats"]) else: # Returns logits only. return net.apply(all_params, x, train=train, mutable=False) logistic_loss = jax.vmap(loss.multiclass_logistic_loss) def loss_from_logits(params, l2reg, logits, labels): mean_loss = jnp.mean(logistic_loss(labels, logits)) sqnorm = tree_util.tree_l2_norm(params, squared=True) return mean_loss + 0.5 * l2reg * sqnorm @jax.jit def accuracy_and_loss(params, l2reg, data, aux): inputs, labels = data logits = predict(params, inputs, aux, train=False) accuracy = jnp.mean(jnp.argmax(logits, axis=-1) == labels) loss = loss_from_logits(params, l2reg, logits, labels) return accuracy, loss def loss_fun(params, l2reg, data, aux): inputs, labels = data logits, net_state = predict(params, inputs, aux, train=True) loss = loss_from_logits(params, l2reg, logits, labels) # batch_stats will be stored in state.aux return loss, net_state["batch_stats"] # Initialize solver. opt = optax.adam(learning_rate=FLAGS.learning_rate) # We need has_aux=True because loss_fun returns batch_stats. solver = OptaxSolver(opt=opt, fun=loss_fun, maxiter=FLAGS.epochs * iter_per_epoch_train, has_aux=True) # Initialize parameters. rng = jax.random.PRNGKey(0) init_vars = net.init({"params": rng}, jnp.ones(input_shape, net.dtype)) params = init_vars["params"] batch_stats = init_vars["batch_stats"] start = datetime.now().replace(microsecond=0) # Run training loop. state = solver.init_state(params) jitted_update = jax.jit(solver.update) all_test_error = [] all_train_loss = [] for it in range(solver.maxiter): train_minibatch = next(train_ds) if state.iter_num % iter_per_epoch_train == iter_per_epoch_train - 1: # Once per epoch evaluate the model on the train and test sets. test_acc, test_loss = 0., 0. # make a pass over test set to compute test accuracy for _ in range(iter_per_epoch_test): tmp = accuracy_and_loss(params, FLAGS.l2reg, next(test_ds), batch_stats) test_acc += tmp[0] / iter_per_epoch_test test_loss += tmp[1] / iter_per_epoch_test train_acc, train_loss = 0., 0. # make a pass over train set to compute train accuracy for _ in range(iter_per_epoch_train): tmp = accuracy_and_loss(params, FLAGS.l2reg, next(train_ds), batch_stats) train_acc += tmp[0] / iter_per_epoch_train train_loss += tmp[1] / iter_per_epoch_train train_acc = jax.device_get(train_acc) train_loss = jax.device_get(train_loss) test_acc = jax.device_get(test_acc) test_loss = jax.device_get(test_loss) all_test_error.append(1 - test_acc) all_train_loss.append(train_loss) # time elapsed without microseconds time_elapsed = (datetime.now().replace(microsecond=0) - start) print(f"[Epoch {state.iter_num // (iter_per_epoch_train+1) + 1}/{FLAGS.epochs}] " f"Train acc: {train_acc:.3f}, train loss: {train_loss:.3f}. " f"Test acc: {test_acc:.3f}, test loss: {test_loss:.3f}. " f"Time elapsed: {time_elapsed}") params, state = jitted_update(params=params, state=state, l2reg=FLAGS.l2reg, data=train_minibatch, aux=batch_stats) batch_stats = state.aux fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 6)) ax1.plot(all_test_error, lw=3) ax1.set_ylabel('Error on test set', fontsize=20) ax1.grid() ax1.set_xlabel('Epochs', fontsize=20) ax2.plot(all_train_loss, lw=3) ax2.set_ylabel('Loss on train set', fontsize=20) ax2.grid() ax2.set_xlabel('Epochs', fontsize=20) plt.show()
_____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 EQUAL PROBABILITY. CHANGE THIS TO ACCOMMODATE METHOD 3 PRIOR PROBABILITIES p = 0.5 # EXTRACT PIXELS FOR FAT AND MEAT [fatPix, fatR, fatC] = hf.getPix(multiIm, annotationIm[:,:,1]); [meatPix, meatR, meatC] = hf.getPix(multiIm, annotationIm[:,:,2]); # MEANS FOR THE BANDS meatM = np.mean(meatPix,0) fatM = np.mean(fatPix, 0) covM = np.zeros((19,19)) covF = np.zeros((19,19)) # ARRAY OF PIXELS FOR EACH BAND m = 264196 reshIm = np.zeros((m, 19)) for i in range(0, 19): reshIm[:,i] = multiIm[:,:,i].flatten() # COMPUTE COVARIANCE for i in range(0, 19): for j in range(0, 19): covM[i, j] = 1/(m - 1)*np.sum((reshIm[:,i] - meatM[i])*(reshIm[:,j] - meatM[j])) covF[i, j] = 1/(m - 1)*np.sum((reshIm[:,i] - fatM[i])*(reshIm[:,j] - fatM[j])) cov = 1/(2*m - 2)*((m-1)*covM + (m-1)*covF) # LDA FUNCTION def discFunc(x): s_meat = np.dot(x,np.dot(np.linalg.inv(cov),meatM)) - \ 1/2*np.dot(meatM, np.dot(np.linalg.inv(cov),meatM)) + np.log(p) s_fat = np.dot(x,np.dot(np.linalg.inv(cov),fatM)) - \ 1/2*np.dot(fatM, np.dot(np.linalg.inv(cov),fatM)) + np.log(p) return s_meat, s_fat # CLASSIFY THE PIXELS s = np.zeros(264196) for i in range(0, 264196): s_meat, s_fat = discFunc(reshIm[i,:]) if (s_fat >= s_meat): s[i] = 1 else: s[i] = 0 s = np.reshape(s, (514, 514)).astype(np.int64) # IDENTIFIED CLASSIFICATIONS VS KNOWN CLASSIFICATIONS c = s[fatR, fatC] == annotationIm[fatR, fatC, 1] rate = len(c[c == True])/len(c) # IDENTIFY BACKGROUND bPix = np.where(np.logical_and(annotationIm[:,:,0] == 0, annotationIm[:,:,1] == 0, \ annotationIm[:,:,2] == 0)) # REMOVE BACKGROUND s[bPix] = 0 # CLASSIFIED IMAGE PLOT [fatPix, fatR, fatC] = hf.getPix(multiIm, s) pixId = np.stack((fatR, fatC), axis=1) imRGB = imageio.imread(dirIn + 'color_day01.png') rgbOut = hf.setImagePix(imRGB, pixId) plt.imshow(rgbOut) plt.title('Classified image of the salami on day 1') plt.xlim(0,514) plt.ylim(514,0) plt.savefig('salami_day1_model_2', dpi = 300) plt.show()
_____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 # function actually computes what is is supposed to compute! # Feel free to disregard... # Pick some arbitrary lens parameters: lpar = np.asarray([1.11, -0.23, 0.59, 0.72, 33.3]) # Compute the gradients: (xg, yg) = ldf.sie_grad(x, y, lpar) # Compute convergence as half the Laplacian of the potential from the gradients: kappa_g = 0.5 * ( (xg[1:-1,2:] - xg[1:-1,0:-2]) / (x[1:-1,2:] - x[1:-1,0:-2]) + (yg[2:,1:-1] - yg[0:-2,1:-1]) / (y[2:,1:-1] - y[0:-2,1:-1])) # Compute the expected analytic convergence for these lens parameters: (xn, yn) = ldf.xy_rotate(x, y, lpar[1], lpar[2], lpar[4]) kappa_a = 0.5 * lpar[0] / np.sqrt(lpar[3]*xn[1:-1,1:-1]**2 + yn[1:-1,1:-1]**2 / lpar[3]) f = plt.imshow(np.hstack((np.log(kappa_g), np.log(kappa_a), np.log(kappa_g) - np.log(kappa_a))), vmax=np.log(kappa_g).max(), vmin=np.log(kappa_g).min(), **myargs) # OK, looks good! Some disagreement in the center, which is to be expected.
_____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_axrat, g_pa])
_____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, 0.0]) lpar = np.asarray([1., 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.0, 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)
_____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.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.2, 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.1, 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.1, 0.0, 1.0, 0.0]) lpar = np.asarray([1.0, 0.0, 0.0, 2, 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
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]) lpar = np.asarray([1.0, 0.0, 0.0, 0.1, 45]) 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
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, including Presenting Sponsor Facebook Reality Labs** --- Tutorial ObjectivesIn this tutorial, we will implement a continuous control task: you will design control inputs for a linear dynamical system to reach a target state. The state here is continuous-valued, i.e. takes on any real number from $-\infty$ to $\infty$.You have already learned about control for binary states in Tutorial 1, and you have learned about stochastic dynamics, latent states, and measurements yesterday. Now we introduce you to the new concepts of designing a controller with full observation of the state (linear qudratic regulator - LQR), and under partial observability of the state (linear quadratic gaussian - LQG).The running example we consider throughout the tutorial is a cat trying to catch a mouse in space, using its handy little jet pack to navigate.
# @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, interactive, Label plt.style.use("https://raw.githubusercontent.com/NeuromatchAcademy/course-content/master/nma.mplstyle") # @title Plotting Functions def plot_vs_time(s, slabel, color, goal=None, ylabel=None): plt.plot(s, color, label=slabel) if goal is not None: plt.plot(goal, 'm', label='goal $g$') plt.xlabel("Time", fontsize=14) plt.legend(loc="upper right") if ylabel: plt.ylabel(ylabel, fontsize=14) # @title Helper Functions class ExerciseError(AssertionError): pass def test_lds_class(lds_class): from math import isclose ldsys = lds_class(T=2, ini_state=2., noise_var=0.) if not isclose(ldsys.dynamics(.9)[1], 1.8): raise ExerciseError("'dynamics' method is not correctly implemented!") if not isclose(ldsys.dynamics_openloop(.9, 2., np.zeros(ldsys.T)-1.)[1], -0.2): raise ExerciseError("'dynamics_openloop' method is not correctly implemented!") if not isclose(ldsys.dynamics_closedloop(.9, 2., np.zeros(ldsys.T)+.3)[0][1], 3.): raise ExerciseError("s[t] in 'dynamics_closedloop' method is not correctly implemented!") if not isclose(ldsys.dynamics_closedloop(.9, 2., np.zeros(ldsys.T)+.3)[1][0], .6): raise ExerciseError("a[t] in 'dynamics_closedloop' method is not correctly implemented!") ldsys.noise_var = 1. if isclose(ldsys.dynamics(.9)[1], 1.8): raise ExerciseError("Did you forget to add noise to your s[t+1] in 'dynamics'?") if isclose(ldsys.dynamics_openloop(.9, 2., np.zeros(ldsys.T)-1.)[1], -0.2): raise ExerciseError("Did you forget to add noise to your s[t+1] in 'dynamics_openloop'?") if isclose(ldsys.dynamics_closedloop(.9, 2., np.zeros(ldsys.T)+.3)[0][1], 3.): raise ExerciseError("Did you forget to add noise to your s[t+1] in 'dynamics_closedloop'?") if not isclose(ldsys.dynamics_closedloop(.9, 2., np.zeros(ldsys.T)+.3)[1][0], .6): raise ExerciseError("Your input a[t] should not be noisy in 'dynamics_closedloop'.") print('Well Done!') def test_lqr_class(lqr_class): from math import isclose lqreg = lqr_class(T=2, ini_state=2., noise_var=0.) lqreg.goal = np.array([-2, -2]) s = np.array([1, 2]) a = np.array([3, 4]) if not isclose(lqreg.calculate_J_state(s), 25): raise ExerciseError("'calculate_J_state' method is not correctly implemented!") if not isclose(lqreg.calculate_J_control(a), 25): raise ExerciseError("'calculate_J_control' method is not correctly implemented!") print('Well Done!')
_____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?bvid={0}&page={1}'.format(id, page) super(BiliVideo, self).__init__(src, width, height, **kwargs) video = BiliVideo(id="BV1Zv411B7WV", width=854, height=480, fs=1) print('Video available at https://www.bilibili.com/video/{0}'.format(video.id)) display(video) out1 = widgets.Output() with out1: from IPython.display import YouTubeVideo video = YouTubeVideo(id="MLUTR8z16jI", width=854, height=480, fs=1, rel=0) print('Video available at https://youtube.com/watch?v=' + video.id) display(video) out = widgets.Tab([out1, out2]) out.set_title(0, 'Youtube') out.set_title(1, 'Bilibili') display(out)
_____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. These dynamics are such that the state at the next time step $s_{t+1}$ are a linear function of the current state $s_t$. There is some environmental noise (think: meteorites) affecting the state, here modeled as gaussian noise $w_t$.The control input or action $a_t$ is the action of the jet pack, which has an effect $Ba_t$ on the state at the next time step $s_{t+1}$. In this tutorial, we will be designing the action $a_t$ to reach the goal $g$, with known state dynamics.Thus, our linear discrete-time system evolves according to the following equation:\begin{eqnarray*}s_{t+1} &=& Ds_t + Ba_t + w_t \tag{1}\\s_{0} &=& s_{init}\end{eqnarray*}with $t$: time step, ranging from $1$ to $T$, where $T$ is the time horizon.$s_t$: state at time $t$ $a_t$: action at time $t$ (also known as control input)$w_t$: gaussian noise at time $t$$D$ and $B$: parameters of the linear dynamical system. For simplicity, we will consider the 1D case, where the matrices reduce to scalars, and the states, control and noise are one-dimensional as well. Specifically, $D$ and $B$ are scalars.We will consider the goal $g$ to be the origin, i.e. $g=0$, for Exercises 1 and 2.2. Note that if the state dynamics are stable, the state reaches $0$ in any case. This is a slightly unrealistic situation for the purposes of simplicity, but we will see more realistic cases later on with $g \neq 0$**Stability** \\The system is stable, i.e. the output remains finite for any finite initial condition $s_{init}$, if $|D|<1$.**Control** \\In *open-loop control*, $a_t$ is not a function of $s_t$. In *closed-loop linear control*, $a_t$ is a linear function of the state $s_t$. Specifically, $a_t$ is the control gain $L_t$ multiplied by $s_t$, i.e. $a_t=L_t s_t$. For now, you will explore these equations, and later on, you will *design* $L_t$ to reach the goal $g$. Coding Exercise 1: Implement state evolution equationsImplement the state evolution equations in the class methods as provided below, for the following cases: \\(a) no control: `def dynamics` \\(b) open-loop control: `def dynamics_openloop` \\(c) closed-loop control: `def dynamics_closedloop` \\*Tip: refer to Equation (1) above. The provided code uses the same notation*
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.noise_var, self.T) for t in range(self.T - 1): #################################################################### ## Insert your code here to fill with the state dynamics equation ## without any control input ## complete the function and remove #raise NotImplementedError("Exercise: Please complete 'dynamics'") #################################################################### # calculate the state of t+1 s[t + 1] = D*s[t] + noise[t] return s def dynamics_openloop(self, D: float, B: float, a: np.ndarray): s = np.zeros(self.T) # states initialization s[0] = self.ini_state noise = np.random.normal(0, self.noise_var, self.T) for t in range(self.T - 1): #################################################################### ## Insert your code here to fill with the state dynamics equation ## with open-loop control input a[t] ## complete the function and remove #raise NotImplementedError("Please complete 'dynamics_openloop'") #################################################################### # calculate the state of t+1 s[t + 1] = D*s[t] + B*a[t] +noise[t] return s def dynamics_closedloop(self, D: float, B: float, L: np.ndarray): s = np.zeros(self.T) # states initialization s[0] = self.ini_state noise = np.random.normal(0, self.noise_var, self.T) a = np.zeros(self.T - 1) for t in range(self.T - 1): #################################################################### ## Insert your code here to fill with the state dynamics equation ## with closed-loop control input as a function of control gain L. ## complete the function and remove #raise NotImplementedError("Please complete 'dynamics_closedloop'") #################################################################### # calculate the current action a[t] = L[t] * s[t] # calculate the next state s[t + 1] = D*s[t] + B*a[t] +noise[t] return s, a # Test your function test_lds_class(LDS)
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 below to visualize the effects of different kinds of control inputs. (a) For the no-control case, can you identify two distinct outcomes, depending on the value of D? Why? (b) The open-loop controller works well--or does it? Run the simulation multiple times and see if there are any problems, especially in challenging (high noise) conditions. (c) Does the closed-loop controller fare better with the noise? Vary the values of $L$ and find a range where it quickly reaches the goal.
#@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.): # linear dynamical system lds = LDS(T, ini_state, noise_var) # No control s_no_control=lds.dynamics(D) # Open loop control at = np.append(a, np.zeros(T - 1)) s_open_loop = lds.dynamics_openloop(D, B, at) # Closed loop control Lt = np.zeros(T) + L s_closed_loop, a_closed_loop = lds.dynamics_closedloop(D, B, Lt) plt.figure(figsize=(10, 6)) plt.plot(s_no_control, 'b', label='No control') plt.plot(s_open_loop, 'g', label='Open Loop with a = {}'.format(a)) plt.plot(s_closed_loop, 'r', label='Closed Loop with L = {}'.format(L)) plt.plot(np.zeros(T), 'm', label='goal') plt.title('LDS State Evolution') plt.ylabel('State', fontsize=14) plt.xlabel('Time', fontsize=14) plt.legend(loc="upper right") plt.show() widget=interactive(simulate_lds, {'manual': True}, D=(.85, 1.05, .1), L=(-0.6, 0., .15), a=(-2., 1., 1.), B=(1., 3., 1.), noise_var=(0., 0.2, .1), T=fixed(50), ini_state=(2., 10., 4.)) widget.children[-2].description='Run Simulation' widget.children[-2].style.button_color='lightgreen' controls = HBox(widget.children[:-1], layout=Layout(flex_flow='row wrap')) output = widget.children[-1] display(VBox([controls, output]))
_____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 control gain $L$. You should see a U-shaped curve, with a clear minimum MSE. The control gain at which the minimum MSE is reached, is the 'optimal' constant control gain for minimizing MSE, here called the numerical optimum. A green dashed line is shown $L = -\frac{D}{B}$ with $D=0.95$ and $B=2$. Consider how Why is this the theoretical optimal control gain for minimizing MSE of the state $s$ to the goal $g=0$? Examine how the states evolve with a constant gain $L$$$\begin{eqnarray*}s_{t+1} &=& Ds_t + Ba_t + w_t \\&=& Ds_t + B(Ls_t) + w_t \\&=& (D+BL)s_t + w_t \tag{2}\end{eqnarray*}$$Now, let's visualize the evolution of the system as we change the control gain. We will start with the optimal gain (the control gain that gets us the minimum MSE), and then explore over- and under- ambitious values.
#@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)): lds = LDS(T, ini_state, noise_var) L = - np.ones(T) * control_gain_array[i] s, a = lds.dynamics_closedloop(D, B, L) mse_array[i] = np.sum(s**2) plt.figure() plt.plot(-control_gain_array, mse_array, 'b') plt.axvline(x=-D/B, color='g', linestyle='--') plt.xlabel("control gain (L)", fontsize=14) plt.ylabel("MSE between state and goal" , fontsize=14) plt.title("MSE vs control gain", fontsize=20) plt.show() calculate_plot_mse() #@markdown Make sure you execute this cell to enable the widget! #@markdown Explore different values of control gain **`L`** (close to optimal, over- and under- ambitious) \\ def simulate_L(L:float=-0.45): D, B, noise_var, T, ini_state = 0.95, 2., 0.1, 50, 2. lds = LDS(T, ini_state, noise_var) # Closed loop control with the numerical optimal control gain Lt = np.ones(T) * L s_closed_loop_choice, _ = lds.dynamics_closedloop(D, B, Lt) # Closed loop control with the theoretical optimal control gain L_theory = - D / B * np.ones(T) s_closed_loop_theoretical, _ = lds.dynamics_closedloop(D, B, L_theory) # Plotting closed loop state evolution with both theoretical and numerical optimal control gains plt.figure(figsize=(10, 6)) plot_vs_time(s_closed_loop_theoretical, 'Closed Loop (Theoretical optimal control gain)','b') plot_vs_time(s_closed_loop_choice, 'Closed Loop (your choice of L = {})'.format(L), 'g', goal=np.zeros(T), ylabel="State") plt.title('Closed Loop State Evolution') plt.show() widget=interactive(simulate_L, {'manual': True}, L=(-1.05, 0.051, .1)) widget.children[-2].description='Run Simulation' widget.children[-2].style.button_color='lightgreen' controls = HBox(widget.children[:-1], layout=Layout(flex_flow='row wrap')) output = widget.children[-1] display(VBox([controls, output]))
_____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/player.html?bvid={0}&page={1}'.format(id, page) super(BiliVideo, self).__init__(src, width, height, **kwargs) video = BiliVideo(id="BV1sz411v7za", width=854, height=480, fs=1) print('Video available at https://www.bilibili.com/video/{0}'.format(video.id)) display(video) out1 = widgets.Output() with out1: from IPython.display import YouTubeVideo video = YouTubeVideo(id="NZSwDy7wtIs", width=854, height=480, fs=1, rel=0) print('Video available at https://youtube.com/watch?v=' + video.id) display(video) out = widgets.Tab([out1, out2]) out.set_title(0, 'Youtube') out.set_title(1, 'Bilibili') display(out)
_____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 makes it dangerous to use large amounts of fuel in a single timestep. We certainly do not want to explode, so we would like to keep the actions $a_t$ as small as possible while still mantaining good control.Moreover, in Exercise 1, we had restricted ourselves to a static control gain $L_t \equiv L$. How would we vary it if we could?This leads us to a more principled way of designing the optimal control input. Setting up a cost function In a finite-horizon LQR problem, the cost function is defined as: \begin{eqnarray}J({\bf s},{\bf a}) &=& J_{state}({\bf s}) + \rho J_{control}({\bf a}) \\ &=& \sum_{t = 0}^{T} (s_{t}-g)^2 + \rho \sum_{t=0}^{T-1}a_{t}^2 \tag{3}\end{eqnarray}where $\rho$ is the weight on the control effort cost, as compared to the cost of not being at the goal. Here, ${\bf a} = \{a_t\}_{t=0}^{T-1}$, ${\bf s} = \{s_t\}_{t=0}^{T}$. This is a quadratic cost function. In Exercise $2$, we will only explore $g=0$, in which case $J_{state}({\bf s})$ can also be expressed as $\sum_{t = 0}^{T} s_{t}^2$. In Exercise $3$, we will explore a non-zero time-varying goal.The goal of the LQR problem is to find control ${\bf a}$ such that $J({\bf s},{\bf a})$ is minimized. The goal is then to find the control gain at each time point, i.e.,$$ \text{argmin} _{\{L_t\}_{t=0}^{T-1}} J({\bf s},{\bf a}) \tag{4} $$ where $a_t = L_t s_t$. Section 2.2 Solving LQRThe solution to Equation (4), i.e. LQR for a finite time horizon, can be obtained via Dynamic Programming. For details, check out [this lecture by Stephen Boyd](https://stanford.edu/class/ee363/lectures/dlqr.pdf).For an infinite time horizon, one can obtain a closed-form solution using Riccati equations, and the solution for the control gain becomes time-invariant, i.e. $L_t \equiv L$. We will use this in Exercise 4. For details, check out [this other lecture by Stephen Boyd](https://stanford.edu/class/ee363/lectures/dlqr-ss.pdf).Additional reference for entire section: \\[Bertsekas, Dimitri P. "Dynamic programming and optimal control". Vol. 1. No. 2. Belmont, MA: Athena scientific, 1995.](http://www.athenasc.com/dpbook.html) Coding Exercise 2.2: Implement the cost functionThe cost function $J_{control}({\bf s}, {\bf a})$ can be divided into two parts: $J_{state}({\bf s})$ and $J_{control}({\bf a})$. Code up these two parts in the class methods `def calculate_J_state` and `def calculate_J_control` in the following helper class for LQR.
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 P[-1] = 1 for t in range(self.T - 1): P_t_1 = P[self.T - t - 1] P[self.T - t-2] = (1 + P_t_1 * D**2 - D * P_t_1 * B / ( rho + P_t_1 * B) * B**2 * P_t_1 * D) L[self.T - t-2] = - (1 / (rho + P_t_1 * B**2) * B * P_t_1 * D) return L def calculate_J_state(self, s:np.ndarray): ######################################################################## ## Insert your code here to calculate J_state(s) (see Eq. 3) ## complete the function and remove #raise NotImplementedError("Please complete 'calculate_J_state'") ######################################################################## # calculate the state J_state = np.sum((s-self.goal)**2) return J_state def calculate_J_control(self, a:np.ndarray): ######################################################################## ## Insert your code here to calculate J_control(a) (see Eq. 3). ## complete the function and remove #raise NotImplementedError("Please complete 'calculate_J_control'") ######################################################################## # calculate the control J_control = np.sum(a**2) return J_control # Test class test_lqr_class(LQR)
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 varying $\rho$ affects its actions by\\1. Using Equation 3, find a value for $\rho$ that will get you the same cost and control gain as Exercise 1.2. Pick a larger value for $\rho$ and see the effect on the action.3. Try increasing the rho to 2. What do you notice? \\4. For different values of $\rho$, how does the control gain vary?
#@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(figsize=(14, 4)) plt.suptitle('LQR Control for rho = {}'.format(rho), y=1.05) plt.subplot(1, 3, 1) plot_vs_time(s_lqr,'State evolution','b',goal=np.zeros(T)) plt.ylabel('State $s_t$') plt.subplot(1, 3, 2) plot_vs_time(a_lqr,'LQR Action','b') plt.ylabel('Action $a_t$') plt.subplot(1, 3, 3) plot_vs_time(L,'Control Gain','b') plt.ylabel('Control Gain $L_t$') plt.tight_layout() plt.show() widget=interactive(simulate_rho, {'manual': True}, rho=(0., 2., 0.5)) widget.children[-2].description = 'Run Simulation' widget.children[-2].style.button_color = 'lightgreen' controls = HBox(widget.children[:-1], layout=Layout(flex_flow='row wrap')) output = widget.children[-1] display(VBox([controls, output]))
_____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 class methods for the class LQR. We will now plot them against each other for varying values of $\rho$ to explore the tradeoff between state cost and control cost.
#@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_array)): lqr = LQR(T, ini_state, noise_var) L = lqr.control_gain_LQR(D, B, rho_array[i]) s_lqr, a_lqr = lqr.dynamics_closedloop(D, B, L) J_state[i] = lqr.calculate_J_state(s_lqr) J_control[i] = lqr.calculate_J_control(a_lqr) fig = plt.figure(figsize=(6, 6)) plt.plot(J_state, J_control, '.b') plt.xlabel("$J_{state} = \sum_{t = 0}^{T} (s_{t}-g)^2$", fontsize=14) plt.ylabel("$J_{control} = \sum_{t=0}^{T-1}a_{t}^2$" , fontsize=14) plt.title("Error vs control effort", fontsize=20) plt.show() calculate_plot_costs()
_____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 accept that amount of state cost. For example, if you know that you have a limited amount of fuel, which determines your maximum control cost to be $J_{control}^{max}$. You will be able to show that you will not be able to track your state with a higher accuracy than the corresponding $J_{state}$ as given by the graph above. This is thus an important curve when designing a system and exploring its control. --- Section 3: LQR for tracking a time-varying goal
# @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?bvid={0}&page={1}'.format(id, page) super(BiliVideo, self).__init__(src, width, height, **kwargs) video = BiliVideo(id="BV1up4y1S7gg", width=854, height=480, fs=1) print('Video available at https://www.bilibili.com/video/{0}'.format(video.id)) display(video) out1 = widgets.Output() with out1: from IPython.display import YouTubeVideo video = YouTubeVideo(id="HOoqM7kBWSY", width=854, height=480, fs=1, rel=0) print('Video available at https://youtube.com/watch?v=' + video.id) display(video) out = widgets.Tab([out1, out2]) out.set_title(0, 'Youtube') out.set_title(1, 'Bilibili') display(out)
_____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} (s_{t}- g_t) ^2 + \rho \sum_{t=0}^{T-1}(a_{t}-\bar a_t)^2$$Here, $\bar a_t$ is the desired action based on the goal trajectory. In other words, the controller considers the goal for the next time step, and designs a preliminary control action that gets the state at the next time step to the desired goal. Specifically, without taking into account noise $w_t$, we would like to design $\bar a_t$ such that $s_{t+1}=g_{t+1}$. Thus, from Equation $(1)$,\begin{eqnarray*}g_{t+1} &=& Ds_t + B \bar a_t\\\bar a_{t} &=& \frac{- Ds_t + g_{t+1}}{B}\\\end{eqnarray*}The final control action $a_t$ is produced by adding this desired action $\bar a_t$ with the term with the control gain $L_t(s_t - g_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) # states intialization s[0] = self.ini_state noise = np.random.normal(0, self.noise_var, self.T) a = np.zeros(self.T) # control intialization a_bar = np.zeros(self.T) for t in range(self.T - 1): a_bar[t] = ( - D * s[t] + self.goal[t + 1]) / B a[t] = L[t] * (s[t] - self.goal[t]) + a_bar[t] s[t + 1] = D * s[t] + B * a[t] + noise[t] return s, a, a_bar def calculate_J_state(self,s): J_state = np.sum((s-self.g)**2) return J_state def calculate_J_control(self, a, a_bar): J_control = np.sum((a-a_bar)**2) return J_control
_____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 step function and ramp.
#@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 / 3):] = 1. elif goal_func == 'ramp': goal = np.zeros(T) goal[int(T / 3):] = np.arange(T - int(T / 3)) / (T - int(T / 3)) lqr_time = LQR_tracking(T, ini_state, noise_var, goal) L = lqr_time.control_gain_LQR(D, B, rho) s_lqr_time, a_lqr_time, a_bar_lqr_time = lqr_time.dynamics_tracking(D, B, L) plt.figure(figsize=(13, 5)) plt.suptitle('LQR Control for time-varying goal', y=1.05) plt.subplot(1, 2, 1) plot_vs_time(s_lqr_time,'State evolution $s_t$','b',goal, ylabel="State") plt.subplot(1, 2, 2) plot_vs_time(a_lqr_time, 'Action $a_t$', 'b', ylabel="Action") plt.show() widget=interactive(simulate_tracking, {'manual': True}, rho=(0., 40., 10.), noise_var=(0., 1., .2), goal_func=['sin', 'step', 'ramp'] ) widget.children[-2].description = 'Run Simulation' widget.children[-2].style.button_color = 'lightgreen' controls = HBox(widget.children[:-1], layout=Layout(flex_flow='row wrap')) output = widget.children[-1] display(VBox([controls, output]))
_____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.bilibili.com/player.html?bvid={0}&page={1}'.format(id, page) super(BiliVideo, self).__init__(src, width, height, **kwargs) video = BiliVideo(id="BV1xZ4y1u73B", width=854, height=480, fs=1) print('Video available at https://www.bilibili.com/video/{0}'.format(video.id)) display(video) out1 = widgets.Output() with out1: from IPython.display import YouTubeVideo video = YouTubeVideo(id="c_D7iDLT_bw", width=854, height=480, fs=1, rel=0) print('Video available at https://youtube.com/watch?v=' + video.id) display(video) out = widgets.Tab([out1, out2]) out.set_title(0, 'Youtube') out.set_title(1, 'Bilibili') display(out)
_____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 based on this estimate. Fortunately, the separation principle tells us that it is optimal to do (1) and (2) separately. This makes our problem much easier, since we already know how to do each step. 1) *State Estimation* Can we recover the state from the measurement? From yesterday's lecture, it is known that the states $\hat{s}_t$ can be estimated from the measurements $m_t$ using the __Kalman filter__. 2) *Design Action* In Sections 2 and 3 above, we just learnt about the LQR controller which designs an action based on the state. The separation principle tells us that it is sufficient to replace the use of the state in LQR with the *estimated* state, i.e.$$a_t = L_t \hat s_t$$The state dynamics will then be:$$s_{t+1} = D s_t + B a_t + w_t$$where $w_t$ is the process noise (proc_noise), and the observation / measurement is:$$ y_t = C s_t + v_t$$ with $v_t$ being the measurement noise (meas_noise).The combination of (1) state estimation and (2) action design using LQR is known as a **linear quadratic gaussian (LQG)**. Yesterday, you completed the code for Kalman filter. Based on that, you will code up the LQG controller. For these exercises, we will resturn to using the goal $g=0$, as in Section 2. Interactive Demo 4.1: The Kalman filter in conjunction with a linear closed-loop controller (LQG Control)In the `MyKalmanFilter` class, the method `filter_control` implements filtering in closed-loop feedback. It is a combination of generating samples (states $s_t$) and filtering (generating state estimates $\hat s_t$), as you have seen in yesterday's tutorial. The only difference from yesterday is that today's Kalman filter is in closed loop with the controller. Thus, each $s_{t+1}$ gets an input $a_t$, which itself depends on the state estimate of the last time step $\hat s_t$.Below you find the code snipets for the Kalman filter in closed loop (`MyKalmanFilter`) class that provide you an insight in action update (`control_policy_LQG`) and state estimation (`state_dynamics_LQG`). Please feel free to inspect the helper functions and classes for the details. You should have seen the next cell containing `MyKalmanFilter` class yesterday, with the exception of the controller acting on the state estimate in feedback, using the methods/equations you will find below.
#@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_dim_state: dimension of the latent variables @param n_dim_obs: dimension of the observed variables @param transition_matrices: D @param transition_covariance: process noise @param observation_matrices: C @param observation_covariance: measurement noise @param initial_state_mean: initial state estimate @param initial_state_covariance: initial estimate on state variance @param control_matrices: B """ self.n_dim_state = n_dim_state self.n_dim_obs = n_dim_obs self.transition_matrices = transition_matrices self.transition_covariance = transition_covariance self.observation_matrices = observation_matrices self.observation_covariance = observation_covariance self.initial_state_mean = initial_state_mean self.initial_state_covariance = initial_state_covariance self.control_matrices = control_matrices def filter_control(self, n_timesteps, control_gain, use_myfilter=True): """ Method that performs Kalman filtering with a controller in feedback @param n_timesteps: length of the data sample @param control_gain: a numpy array whose dimension is [n_timesteps, self.n_dim_state] @output: filtered_state_means: a numpy array whose dimension is [n_timesteps, self.n_dim_state] @output: filtered_state_covariances: a numpy array whose dimension is [n_timesteps, self.n_dim_state, self.n_dim_state] @output: latent_state: a numpy array whose dimension is [n_timesteps, self.n_dim_state] @output: observed_state: a numpy array whose dimension is [n_timesteps, self.n_dim_obs] @output: control: a numpy array whose dimension is [n_timesteps, self.n_dim_state] """ # validate inputs # assert observed_dim == self.n_dim_obs n_example = n_timesteps observed_dim = self.n_dim_obs latent_state = [] observed_state = [] control = [] current_latent_state = self.initial_state_mean #initial_state control.append(self.initial_state_mean) latent_state.append(current_latent_state) observed_state.append(np.dot(self.observation_matrices, current_latent_state) + np.random.multivariate_normal(np.zeros(self.n_dim_obs), self.observation_covariance)) # create holders for outputs filtered_state_means = np.zeros([n_example, self.n_dim_state]) filtered_state_covariances = np.zeros([n_example, self.n_dim_state, self.n_dim_state]) if use_myfilter: # the first state mean and state covar is the initial expectation filtered_state_means[0] = self.initial_state_mean filtered_state_covariances[0] = self.initial_state_covariance # initialize internal variables current_state_mean = self.initial_state_mean.copy() current_state_covar = self.initial_state_covariance.copy() self.p_n_list = np.zeros((n_example, self.n_dim_obs, self.n_dim_obs)) for i in range(1, n_example): ## Use the code in Exercise 4.1 to get the current action current_action = control_policy_LQG(self,current_state_mean,control_gain[i]) control.append(current_action) ## Use the code in Exercise 4.1 to update the state current_latent_state = state_dynamics_LQG(self,current_latent_state, current_action) latent_state.append(current_latent_state) # use observation_matrices and observation_covariance to calculate next observed state observed_state.append(np.dot(self.observation_matrices, current_latent_state ) + np.random.multivariate_normal(np.zeros(self.n_dim_obs), self.observation_covariance)) current_observed_data = observed_state[-1] # run a single step forward filter # prediction step predicted_state_mean = np.dot(self.transition_matrices, current_state_mean ) + np.dot(self.control_matrices, current_action) predicted_state_cov = np.matmul(np.matmul(self.transition_matrices, current_state_covar), np.transpose(self.transition_matrices)) + self.transition_covariance # observation step innovation = current_observed_data - np.dot(self.observation_matrices, predicted_state_mean) innovation_covariance = np.matmul(np.matmul(self.observation_matrices, predicted_state_cov), np.transpose(self.observation_matrices)) + self.observation_covariance # update step kalman_gain = np.matmul(np.matmul(predicted_state_cov, np.transpose(self.observation_matrices)), np.linalg.inv(innovation_covariance)) current_state_mean = predicted_state_mean + np.dot(kalman_gain, innovation) current_state_covar = np.matmul((np.eye(current_state_covar.shape[0]) - np.matmul(kalman_gain, self.observation_matrices)), predicted_state_cov) # populate holders filtered_state_means[i, :] = current_state_mean filtered_state_covariances[i, :, :] = current_state_covar self.p_n_list[i, :, :] = predicted_state_cov # self.p_n_list[i-1, :, :] = predicted_state_cov # new # self.p_n_list[-1, :, :] = np.matmul(np.matmul(self.transition_matrices, filtered_state_covariances[-1,:,:]), # np.linalg.inv(self.transition_matrices)) + self.transition_covariance # else: # ################################################################################# # # below: this is an alternative if you do not have an implementation of filtering # kf = KalmanFilter(n_dim_state=self.n_dim_state, n_dim_obs=self.n_dim_obs) # need_params = ['transition_matrices', 'observation_matrices', 'transition_covariance', # 'observation_covariance', 'initial_state_mean', 'initial_state_covariance'] # for param in need_params: # setattr(kf, param, getattr(self, param)) # filtered_state_means, filtered_state_covariances = kf.filter(X) # ################################################################################# filtered_state_means = np.squeeze(np.array(filtered_state_means)) filtered_state_covariances = np.squeeze(np.array(filtered_state_covariances)) latent_state = np.squeeze(np.array(latent_state)) observed_state = np.squeeze(np.array(observed_state)) control = np.squeeze(np.array(control)) return filtered_state_means, filtered_state_covariances, latent_state, observed_state, control def plot_state_vs_time(self, n_timesteps, control_gain, title, use_myfilter=True, goal=None): filtered_state_means_impl, filtered_state_covariances_impl, latent, measurement, control = self.filter_control( n_timesteps, control_gain) fig = plt.figure(figsize=(12, 4)) plt.suptitle(title, y=1.05) gs = gridspec.GridSpec(1, 2, width_ratios=[1, 2]) ax0 = plt.subplot(gs[0]) ax0.plot(latent,filtered_state_means_impl, 'b.') ax0.set_xlabel('Latent State') ax0.set_ylabel('Estimated State') ax0.set_aspect('equal') ax1 = plt.subplot(gs[1]) ax1.plot(latent, 'b', label = 'Latent State') ax1.plot(filtered_state_means_impl, 'r', label = 'Estimated State') if goal is not None: ax1.plot(goal, 'm', label = 'goal') ax1.set_xlabel('Time') ax1.set_ylabel('State') ax1.legend(loc="upper right") plt.tight_layout() plt.show() # inspect the 'control_policy_LQG' and 'state_dynamics_LQG' methods: def control_policy_LQG(self, mean_estimated_state, control_gain): current_action = control_gain * mean_estimated_state return current_action def state_dynamics_LQG(self, current_latent_state, current_action): current_latent_state = np.dot(self.transition_matrices, current_latent_state)\ + np.dot(self.control_matrices, current_action)\ + np.random.multivariate_normal(np.zeros(self.n_dim_state), self.transition_covariance) return current_latent_state
_____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 a Kalman filter estimates state. `C` scales the observation matrix.
#@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_state = 1 n_dim_obs = 1 n_timesteps = T transition_matrices = np.eye(n_dim_state) * D transition_covariance = np.eye(n_dim_obs) * proc_noise # process noise observation_matrices = np.eye(n_dim_state) * C observation_covariance = np.eye(n_dim_obs) * meas_noise initial_state_mean = np.ones(n_dim_state) * ini_state initial_state_covariance = np.eye(n_dim_state) * .01 control_matrices = np.eye(n_dim_state) * B my_kf = MyKalmanFilter(n_dim_state, n_dim_obs, transition_matrices, transition_covariance, observation_matrices, observation_covariance, initial_state_mean, initial_state_covariance, control_matrices) my_kf.plot_state_vs_time(n_timesteps, control_gain, 'State estimation with KF (no control input)') widget=interactive(simulate_kf_no_control, {'manual': True}, D=fixed(.95), B=fixed(2.), C=(0., 3., 1.), proc_noise=(0., 1., .1), meas_noise=(0.1, 1., .1), T=fixed(50), L=fixed(0), ini_state=fixed(5.)) widget.children[-2].description = 'Run Simulation' widget.children[-2].style.button_color = 'lightgreen' controls = HBox(widget.children[:-1], layout=Layout(flex_flow='row wrap')) output = widget.children[-1] display(VBox([controls, output]))
_____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. We will first use an arbitary control gain and a fixed value for measurement noise. We will then use the control gain from the LQR for optimal performance, with varying values for $\rho$.(a) Visualize the system dynamics $s_t$ in closed-loop control with an arbitrary constant control gain. Vary this control gain.(b) Vary $\rho$ to visualize the output of the optimal LQG controller. Here, we will use an optimal *constant* control gain, which is optimal in the case of an infinite time horizon (get to the goal and stay there forever).
#@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_state = 1 n_dim_obs = 1 n_timesteps = T transition_matrices = np.eye(n_dim_state) * D transition_covariance = np.eye(n_dim_obs) * proc_noise # process noise observation_matrices = np.eye(n_dim_state) * C observation_covariance = np.eye(n_dim_obs) * meas_noise initial_state_mean = np.ones(n_dim_state) * ini_state initial_state_covariance = np.eye(n_dim_state) * .01 control_matrices = np.eye(n_dim_state) * B my_kf = MyKalmanFilter(n_dim_state, n_dim_obs, transition_matrices, transition_covariance, observation_matrices, observation_covariance, initial_state_mean, initial_state_covariance, control_matrices) my_kf.plot_state_vs_time(n_timesteps, control_gain, goal = np.zeros(T), title='State estimation with KF (controller gain = {})'.format(L)) widget=interactive(simulate_kf_with_control, {'manual': True}, D=fixed(.9), B=fixed(2.), C=(0., 3., 1.), proc_noise=(0., 1., .1), meas_noise=(0.1, 1., .1), T=fixed(50), L=(-0.5, 0., .1), ini_state=fixed(5.)) widget.children[-2].description = 'Run Simulation' widget.children[-2].style.button_color = 'lightgreen' controls = HBox(widget.children[:-1], layout=Layout(flex_flow='row wrap')) output = widget.children[-1] display(VBox([controls, output]))
_____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 large values, to see the effect on the state.
#@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_matrices): MyKalmanFilter.__init__(self,n_dim_state, n_dim_obs, transition_matrices, transition_covariance, observation_matrices,observation_covariance, initial_state_mean, initial_state_covariance, control_matrices) LQR.__init__(self,T, initial_state_mean, transition_covariance) def control_gain_LQR_infinite(self, rho): control_gain_LQR_finite = self.control_gain_LQR(self.transition_matrices, self.control_matrices, rho) return control_gain_LQR_finite[0] #@markdown Make sure you execute this cell to enable the widget! def simulate_kf_with_lqg(D=0.9, B=2., C=1., T=50, ini_state=5, proc_noise=0.1, meas_noise=0.2, rho=1.): # Format the above variables into a format acccepted by the Kalman Filter n_dim_state = 1 n_dim_obs = 1 n_timesteps = T transition_matrices = np.eye(n_dim_state) * D transition_covariance = np.eye(n_dim_obs) * proc_noise # process noise observation_matrices = np.eye(n_dim_state) * C observation_covariance = np.eye(n_dim_obs) * meas_noise initial_state_mean = np.ones(n_dim_state) * ini_state initial_state_covariance = np.eye(n_dim_state) * .01 control_matrices = np.eye(n_dim_state) * B my_kf = MyKalmanFilter(n_dim_state, n_dim_obs, transition_matrices, transition_covariance, observation_matrices, observation_covariance, initial_state_mean, initial_state_covariance, control_matrices) lqg = LQG(n_timesteps, n_dim_state, n_dim_obs, transition_matrices, transition_covariance, observation_matrices, observation_covariance, initial_state_mean, initial_state_covariance, control_matrices) control_gain_lqg = lqg.control_gain_LQR_infinite(rho) * np.ones(n_timesteps) lqg.plot_state_vs_time(n_timesteps, control_gain_lqg, goal = np.zeros(T), title='State estimation with KF (LQG controller)') widget=interactive(simulate_kf_with_lqg, {'manual': True}, D = fixed(.9), B = fixed(2.), C = fixed(1.), proc_noise = fixed(.1), meas_noise = fixed(.2), T = fixed(50), ini_state = fixed(5.), rho=(0., 5., 1.)) widget.children[-2].description = 'Run Simulation' widget.children[-2].style.button_color = 'lightgreen' controls = HBox(widget.children[:-1], layout = Layout(flex_flow='row wrap')) output = widget.children[-1] display(VBox([controls, output]));
_____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 for how process noise and measurement noise influences the controlled state. How are these two sources of noise different?(b) Next, for varying levels of process noise and measurement noise (note that the control policy is exactly the same for all these values), plot the mean squared error (MSE) between state and the goal, as well as the control cost. What do you notice?
#@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 acccepted by the Kalman Filter n_dim_state = 1 n_dim_obs = 1 n_timesteps = T transition_matrices = np.eye(n_dim_state) * D transition_covariance = np.eye(n_dim_obs) * proc_noise # process noise observation_matrices = np.eye(n_dim_state) * C observation_covariance = np.eye(n_dim_obs) * meas_noise initial_state_mean = np.ones(n_dim_state) * ini_state initial_state_covariance = np.eye(n_dim_state) * .01 control_matrices = np.eye(n_dim_state) * B rho = 1 lqg = LQG(n_timesteps, n_dim_state, n_dim_obs, transition_matrices, transition_covariance, observation_matrices, observation_covariance, initial_state_mean, initial_state_covariance, control_matrices) control_gain_lqg = lqg.control_gain_LQR_infinite(rho) * np.ones(n_timesteps) lqg.plot_state_vs_time(n_timesteps, control_gain_lqg, goal = np.zeros(n_timesteps), title='State estimation with KF (LQG controller)') widget=interactive(lqg_slider, {'manual': True}, D = fixed(.9), B = fixed(2.), C = fixed(1.), proc_noise = (0., 3., .1), meas_noise = (0.1, 3., .1), T = fixed(50), ini_state = fixed(5.), rho=fixed(1.)) widget.children[-2].description = 'Run Simulation' widget.children[-2].style.button_color = 'lightgreen' controls = HBox(widget.children[:-1], layout = Layout(flex_flow='row wrap')) output = widget.children[-1] display(VBox([controls, output]));
_____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 levels. To do so, we will run many simulations, stepping through levels of process and measurement noise, tracking MSE and cost of control for each. Run the cell below to perform this simulations and plot them. How do you interpret the results?
#@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_noise_var = 0.1 # process noise measurement_noise_var = 0.2 # measurement noise rho = 1 # Format the above variables into a format acccepted by the Kalman Filter n_dim_state = 1 n_dim_obs = 1 n_timesteps = T transition_matrices = np.eye(n_dim_state) * D transition_covariance = np.eye(n_dim_obs) * noise_var # process noise observation_matrices = np.eye(n_dim_state) * C observation_covariance = np.eye(n_dim_obs) * measurement_noise_var initial_state_mean = np.ones(n_dim_state) * ini_state initial_state_covariance = np.eye(n_dim_state) * .01 control_matrices = np.eye(n_dim_state) * B # Implement LQG control over n_iter iterations, and record the MSE between state and goal MSE_array_N_meas = [] MSE_array_N_proc = [] Jcontrol_array_N_meas = [] Jcontrol_array_N_proc = [] n_iter = 10 meas_noise_array = np.linspace(0,3,20) proc_noise_array = np.linspace(0.1,3,20) for i in range(n_iter): MSE_array = np.zeros(proc_noise_array.shape) Jcontrol_array = np.zeros(meas_noise_array.shape) for i in range(len(proc_noise_array)): transition_covariance = np.eye(n_dim_obs) * proc_noise_array[i] observation_covariance = np.eye(n_dim_obs) * measurement_noise_var lqg = LQG(n_timesteps, n_dim_state, n_dim_obs, transition_matrices, transition_covariance, observation_matrices, observation_covariance, initial_state_mean, initial_state_covariance, control_matrices) control_gain_lqg = lqg.control_gain_LQR_infinite(rho) * np.ones(n_timesteps) # Get the control gain filtered_state_means_impl, filtered_state_covariances_impl, latent, measurement, control = lqg.filter_control( n_timesteps, control_gain_lqg) MSE_array[i] = lqg.calculate_J_state(latent) Jcontrol_array[i] = lqg.calculate_J_control(control) MSE_array_N_proc.append(MSE_array) Jcontrol_array_N_proc.append(Jcontrol_array) MSE_array = np.zeros(meas_noise_array.shape) Jcontrol_array = np.zeros(meas_noise_array.shape) for i in range(len(meas_noise_array)): observation_covariance = np.eye(n_dim_obs) * meas_noise_array[i] transition_covariance = np.eye(n_dim_obs) * noise_var lqg = LQG(n_timesteps, n_dim_state, n_dim_obs, transition_matrices, transition_covariance, observation_matrices, observation_covariance, initial_state_mean, initial_state_covariance, control_matrices) control_gain_lqg = lqg.control_gain_LQR_infinite(rho) * np.ones(n_timesteps) # Get the control gain filtered_state_means_impl, filtered_state_covariances_impl, latent, measurement, control = lqg.filter_control( n_timesteps, control_gain_lqg) MSE_array[i] = lqg.calculate_J_state(latent) Jcontrol_array[i] = lqg.calculate_J_control(control) MSE_array_N_meas.append(MSE_array) Jcontrol_array_N_meas.append(Jcontrol_array) MSE_array_proc_mean = np.mean(np.array(MSE_array_N_proc), axis = 0) MSE_array_proc_std = np.std(np.array(MSE_array_N_proc), axis = 0) MSE_array_meas_mean = np.mean(np.array(MSE_array_N_meas), axis = 0) MSE_array_meas_std = np.std(np.array(MSE_array_N_meas), axis = 0) Jcontrol_array_proc_mean = np.mean(np.array(Jcontrol_array_N_proc), axis = 0) Jcontrol_array_proc_std = np.std(np.array(Jcontrol_array_N_proc), axis = 0) Jcontrol_array_meas_mean = np.mean(np.array(Jcontrol_array_N_meas), axis = 0) Jcontrol_array_meas_std = np.std(np.array(Jcontrol_array_N_meas), axis = 0) # Visualize the quantification f, axs = plt.subplots(2, 2, sharex=True, sharey=True, figsize=(10, 8)) axs[0,0].plot(proc_noise_array, MSE_array_proc_mean, 'r-') axs[0,0].fill_between(proc_noise_array, MSE_array_proc_mean+MSE_array_proc_std, MSE_array_proc_mean-MSE_array_proc_std, facecolor='tab:gray', alpha=0.5) axs[0,0].set_title('Effect of process noise') axs[0,0].set_ylabel('State Cost (MSE between state and goal)') axs[0,1].plot(meas_noise_array, MSE_array_meas_mean, 'r-') axs[0,1].fill_between(meas_noise_array, MSE_array_meas_mean+MSE_array_meas_std, MSE_array_meas_mean-MSE_array_meas_std, facecolor='tab:gray', alpha=0.5) axs[0,1].set_title('Effect of measurement noise') axs[1,0].plot(proc_noise_array, Jcontrol_array_proc_mean, 'r-') axs[1,0].fill_between(proc_noise_array, Jcontrol_array_proc_mean+Jcontrol_array_proc_std, Jcontrol_array_proc_mean-Jcontrol_array_proc_std, facecolor='tab:gray', alpha=0.5) axs[1,0].set_xlabel('Process Noise') axs[1,0].set_ylabel('Cost of Control') axs[1,1].plot(meas_noise_array, Jcontrol_array_meas_mean, 'r-') axs[1,1].fill_between(meas_noise_array, Jcontrol_array_meas_mean+Jcontrol_array_meas_std, Jcontrol_array_meas_mean-Jcontrol_array_meas_std, facecolor='tab:gray', alpha=0.5) axs[1,1].set_xlabel('Measurement Noise') plt.show()
_____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.Overview of concept: Accept three playlists. These playlists are, in theory, representative of independent users with distinct musical interests. Perform fuzzy clustering to identify 3 non-exclusive clusters Estimated time: ~8 hours Actual time: ~10 hours Extensible: Yes Next steps: Build a front-end application in JavaScript and move beyond demo playlists. Allow for retrieval of public playlists and selective inclusion of each playlist by contributing user. Utility FunctionsLocated in util.py. Will be integrated into dedicated application beyond Jupyter concept. get_users() get_playlists(spotify, users) get_track_features(spotify, playlist_information) plot_distributions(df, drop=None) Setting Up the EnvironmentPackages loaded. Local environment variables were created for SPOTIFY_CLIENT_ID, SPOTIFY_CLIENT_SECRET, and SPOTIFY_USER_ID to hide these sensitive items. Subsequently imported using the os module. Import packages
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 general familiarity with the music. For the purposes of this notebook, three playlists are loaded in below. However, if successfully authenticated through Spotify API, running the below code block will allow user to enter any number of Spotify usernames, view all public playlists, and opt to include the playlists in the analysis.Playlist composition can be viewed directly on Spotify.User 1 User 2 User 3
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 4HQZWfYLja8sps8Gkk10EY tracks https://api.spotify.com/v1/playlists/4HQZWfYLj... total_tracks 100 dtype: object Include playlist? [y/n] [> next user, q=done] n Playlist Information: name User3 description id 2I9p1xsjQGKljEviMQM5Lm tracks https://api.spotify.com/v1/playlists/2I9p1xsjQ... total_tracks 50 dtype: object Include playlist? [y/n] [> next user, q=done] y Playlist Information: name User2 description id 3gEikQyspYXdGwOdZwiFOj tracks https://api.spotify.com/v1/playlists/3gEikQysp... total_tracks 50 dtype: object Include playlist? [y/n] [> next user, q=done] y Playlist Information: name User1 description id 2V4jDbJJT7S575jdvrBuzV tracks https://api.spotify.com/v1/playlists/2V4jDbJJT... total_tracks 50 dtype: object Include playlist? [y/n] [> next user, q=done] y
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, I would like to allow for a nuanced approach to musical similarity by allowing clusters based on fuzzy sets (Zadeh, 1965). Given more time, I would like to pursue a density-based approach or overlapping clustering techniques (Baadel et al. 2016). Fuzzy clustering is a clustering technique that utilizes sets in which each element has degrees of membership in the others. Given that users may have overlapping musical interests, this clustering technique seems appropriate for experimentation. Fuzzy c-means is a computationally-intensive algorithm. Thus, I will standardize the input data and perform principal component analysis (PCA) to reduce dimensionality. Import Packages
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 believe this will lead to better playlist selections.
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, 1.2, color='r') pca_obj.explained_variance_ratio_
_____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 components.Context for each parameter can be found at scikit-fuzzy .
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 April 2019.
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 different results. May get better results by increasing range at the expense of computation time. *See considerations
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 fpc = new_model[-1] # Updates FPC
_____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-include/div/div/div[1]/div[2]/div[1]') header2 = t.read('/html/body/div[2]/div[2]/div/div[2]/div/div[1]/ng-include/div/div/div/div/md-list[2]/feed-item/ng-include/div/div/div[1]/div[2]/div[1]') header3 = t.read('/html/body/div[2]/div[2]/div/div[2]/div/div[1]/ng-include/div/div/div/div/md-list[3]/feed-item/ng-include/div/div/div[1]/div[2]/div[1]') header4 = t.read('/html/body/div[2]/div[2]/div/div[2]/div/div[1]/ng-include/div/div/div/div/md-list[4]/feed-item/ng-include/div/div/div[1]/div[2]/div[1]') header5 = t.read('/html/body/div[2]/div[2]/div/div[2]/div/div[1]/ng-include/div/div/div/div/md-list[5]/feed-item/ng-include/div/div/div[1]/div[2]/div[1]') search1 = 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-include/div/div/div[1]/div[3]/ng-include/div') search2 = t.read('/html/body/div[2]/div[2]/div/div[2]/div/div[1]/ng-include/div/div/div/div/md-list[2]/feed-item/ng-include/div/div/div[1]/div[3]/ng-include/div') search3 = t.read('/html/body/div[2]/div[2]/div/div[2]/div/div[1]/ng-include/div/div/div/div/md-list[3]/feed-item/ng-include/div/div/div[1]/div[3]/ng-include/div') search4 = t.read('/html/body/div[2]/div[2]/div/div[2]/div/div[1]/ng-include/div/div/div/div/md-list[4]/feed-item/ng-include/div/div/div[1]/div[3]/ng-include/div') search5 = t.read('/html/body/div[2]/div[2]/div/div[2]/div/div[1]/ng-include/div/div/div/div/md-list[5]/feed-item/ng-include/div/div/div[1]/div[3]/ng-include/div') t.snap('page','trend.png') t.close() ## We will do a simple score calculator here # print(score) class color: PURPLE = '\033[95m' CYAN = '\033[96m' DARKCYAN = '\033[36m' BLUE = '\033[94m' GREEN = '\033[92m' YELLOW = '\033[93m' RED = '\033[91m' BOLD = '\033[1m' UNDERLINE = '\033[4m' END = '\033[0m' #We will now remove all unnecessary whitespaces header1="".join(header1.split()) header2="".join(header2.split()) header3="".join(header3.split()) header4="".join(header4.split()) header5="".join(header5.split()) search1="".join(search1.split()) search2="".join(search2.split()) search3="".join(search3.split()) search4="".join(search4.split()) search5="".join(search5.split()) header1 = header1.replace("share","") header2= header2.replace("share","") header3 = header3.replace("share","") header4 = header4.replace("share","") header5 = header5.replace("share","") print(color.UNDERLINE+color.BOLD+'Top 5 Search Trends Today'+color.END) print("1) "+header1+" ("+search1+")") print("2) "+header2+" ("+search2+")") print("3) "+header3+" ("+search3+")") print("4) "+header4+" ("+search4+")") print("5) "+header5+" ("+search5+")") from IPython.display import Image from IPython.core.display import HTML Image(url= "trend.png") from IPython.display import HTML HTML('''<script> code_show=true; function code_toggle() { if (code_show){ $('div.input').hide(); } else { $('div.input').show(); } code_show = !code_show } $( document ).ready(code_toggle); </script> <form action="javascript:code_toggle()"><input type="submit" value="Click here to Hide/Show the raw code."></form>''')
_____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. The idea is to mimic the movement of a record in a "baby scratch". The user can enter the amount of speedup, the timestamp in the original track where they want to insert the scratching effect, and the number of scratches.
%%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 sys.path.append('/content/record-scratching/') import AudioS as asc from bokeh.io import output_notebook import IPython.display as ipd output_notebook()
_____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 is also asked to enter the timestamp (in milliseconds) where they want to insert the scratch effect. Using this timestamp and the scratch duration, we clip the appropriate portion of the original audio signal. Finally, the user is asked to enter the number of scratches to insert. The clipped audio is spedup in the forward direction and in the reverse direction. The forward and reserve audio signals are appended and repeated depending on the number of scratches entered by the user. Finally, the scracthed audio is inserted back into the original signal at the timestamp specifed earlier. An FFT of the audio clip that is modified and the original is calculated and the results plotted together for comparison. The user is also asked whether they would like to save the modified audio signal, i.e., signal with the scratched effect, to a file. A `.wav` file is exported from the modified audiosegment and saved in the samples directory.
# 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, you need the [Handsontable](http://handsontable.com) Javascript library. Below are the instructions to load this Javascript library in the IPython notebook.1. Go [here](https://github.com/warpech/jquery-handsontable/tree/master/dist).2. Download `jquery.handsontable.full.css` and `jquery.handsontable.full.js`, and put these two files in `~\.ipython\profile_default\static\custom\`.3. In this folder, add the following line in `custom.js`:`require(['/static/custom/jquery.handsontable.full.js']);`4. In this folder, add the following line in `custom.css`:`@import "/static/custom/jquery.handsontable.full.css"` Now, refresh the notebook! 1. Let's import a few functions and classes.
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. // Add a <div> in the widget area. this.$table = $('<div />') .attr('id', 'table_' + (table_id++)) .appendTo(this.$el); // Create the Handsontable table. this.$table.handsontable({ }); }, update: function() { // Python --> Javascript update. // Get the model's JSON string, and parse it. var data = $.parseJSON(this.model.get('value')); // Give it to the Handsontable widget. this.$table.handsontable({data: data}); // Don't touch this... return HandsonTableView.__super__.update.apply(this); }, // Tell Backbone to listen to the change event // of input controls. events: {"change": "handle_table_change"}, handle_table_change: function(event) { // Javascript --> Python update. // Get the table instance. var ht = this.$table.handsontable('getInstance'); // Get the data, and serialize it in JSON. var json = JSON.stringify(ht.getData()); // Update the model with the JSON string. this.model.set('value', json); // Don't touch this... this.touch(); }, }); // Register the HandsonTableView with the widget manager. WidgetManager.register_widget_view( 'HandsonTableView', HandsonTableView); });
_____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 a change in the `DataFrame`, but the converse is not true. We'll need to re-display the widget if we change the `DataFrame` in Python.
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, 'value') self._widget.on_displayed(self._on_displayed) def _on_displayed(self, e): # DataFrame ==> Widget (upon initialization only) json = self._df.to_json(orient='values') self._widget.value = json def _on_data_changed(self, e, val): # Widget ==> DataFrame (called every time the user # changes a value in the graphical widget) buf = StringIO(val) self._df = pd.read_json(buf, orient='values') def to_dataframe(self): return self._df def show(self): display(self._widget)
_____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 dump CLIENT_ID = "fOeRRL3Z7tI1i5iHRczz4B0X" CLIENT_SECRET = "WA1rPDSudxDcQsZpqZosQXGwMx57hghbdMCaE7FBe9OmQLqE" # Enter the following URL in your browser f"{lm_base_url}/oauth2/login/seek" # Then log in as username: user1 and password: workflowhub # Get an authorization token from LifeMonitor s = requests.session() s.verify = False s.headers.update({}) token_response = s.post( lm_token_url, data={ "client_id": CLIENT_ID, "client_secret": CLIENT_SECRET, "grant_type": "client_credentials", "scope": "registry.user" }, allow_redirects=True, verify=False) assert token_response.status_code == 200 token = token_response.json() token # Update headers with the OAuth2 token s.headers.update({'Authorization': f"Bearer {token['access_token']}"}) # Get registry users response = s.get(f"{lm_base_url}/registries/current/users") assert response.status_code == 200, f"Unexpected error {response.status_code}: {response.content}" registry_users = response.json() registry_users
/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 import webdriver options = webdriver.ChromeOptions() options.add_argument('--incognito') driver = webdriver.Chrome(executable_path='../../chromedriver', options=options) driver.get(url) #Usaremos el Xpath para obtener la lista de vuelos vuelos = driver.find_elements_by_xpath('//li[@class="flight"]') vuelo = vuelos[0]
_____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') boton_escalas = vuelo.find_element_by_xpath('.//div[@class="flight-summary-stops-description"]/button') boton_escalas boton_escalas.click() segmentos = vuelo.find_elements_by_xpath('//div[@class="segments-graph"]/div[@class="segments-graph-segment"]') segmentos escalas = len(segmentos) - 1 #0 escalas si es un vuelo directo
_____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