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 |
|---|---|---|---|---|---|
-----Hmm, it seems it wasn't so easy in this case. Non-trivial models have non-trivial issues!Remember, our NeMoGPT model sets its self.vocab inside the `setup_train_data` step. But that depends on the vocabulary generated by the train set... which is **not** restored during model restoration (unless you call `setup_tr... | class NeMoGPTv2(NeMoGPT):
def setup_training_data(self, train_data_config: OmegaConf):
self.vocab = None
self._train_dl = self._setup_data_loader(train_data_config)
# Save the vocab into a text file for now
with open('vocab.txt', 'w') as f:
for token in self.vocab:
f.write(f"{token}<... | _____no_output_____ | Apache-2.0 | tutorials/01_NeMo_Models.ipynb | mcdavid109/NeMo |
Cartesian CoordinatesThe default coordinate system.See`coord_cartesian() `__. | import pandas as pd
from lets_plot import *
LetsPlot.setup_html()
df = pd.read_csv('https://raw.githubusercontent.com/JetBrains/lets-plot-docs/master/data/mpg.csv')
p = ggplot(df, aes(x='fl')) + geom_bar()
p1 = p + ggtitle('Default')
p2 = p + coord_cartesian(ylim=[0, 250]) + ggtitle('With Specified Coordinates')
w, h... | _____no_output_____ | MIT | docs/_downloads/06ac615a764ea75899d9a8dd43c871d1/plot__cartesian_coordinates.ipynb | IKupriyanov-HORIS/lets-plot-docs |
Fundus Analysis - Pathological Myopia
| !nvidia-smi | Wed Jan 20 14:13:47 2021
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 460.32.03 Driver Version: 418.67 CUDA Version: 10.1 |
|-------------------------------+----------------------+----------------------+
| GPU Name Persistence-M| Bus-Id ... | MIT | notebooks/Fundus/Single/Fundus_Analysis_Myopia.ipynb | mfc2496/EyeSee-Server |
**Import Data from Google Drive** | from google.colab import drive
drive.mount('/content/gdrive')
import os
os.environ['KAGGLE_CONFIG_DIR'] = "/content/gdrive/My Drive/Kaggle"
%cd /content/gdrive/My Drive/Kaggle
pwd | _____no_output_____ | MIT | notebooks/Fundus/Single/Fundus_Analysis_Myopia.ipynb | mfc2496/EyeSee-Server |
**Download Data in Colab** | !kaggle datasets download -d andrewmvd/ocular-disease-recognition-odir5k
!ls | full_df.csv
imagenet_class_index.json
inception_resnet_v2_weights_tf_dim_ordering_tf_kernels.h5
inception_resnet_v2_weights_tf_dim_ordering_tf_kernels_notop.h5
inception_v3_weights_tf_dim_ordering_tf_kernels.h5
inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5
kaggle.json
Kuszma.JPG
ocular-disease-recognition-od... | MIT | notebooks/Fundus/Single/Fundus_Analysis_Myopia.ipynb | mfc2496/EyeSee-Server |
**Un-zip the Data** | !unzip \*.zip && rm *.zip | [1;30;43mStreaming output truncated to the last 5000 lines.[0m
inflating: preprocessed_images/2179_left.jpg
inflating: preprocessed_images/2179_right.jpg
inflating: preprocessed_images/217_left.jpg
inflating: preprocessed_images/217_right.jpg
inflating: preprocessed_images/2180_left.jpg
inflatin... | MIT | notebooks/Fundus/Single/Fundus_Analysis_Myopia.ipynb | mfc2496/EyeSee-Server |
Classfication Import Statements | import numpy as np
import pandas as pd
import cv2
import random
from tqdm import tqdm
from sklearn.metrics import roc_curve, auc
import matplotlib.pyplot as plt
from tensorflow.keras.preprocessing.image import ImageDataGenerator, load_img, img_to_array
import numpy as np
import matplotlib.pyplot as plt
from i... | ['3332_left.jpg' '4059_left.jpg' '69_left.jpg' '2415_left.jpg'
'4176_left.jpg' '2711_left.jpg' '4614_left.jpg' '3174_left.jpg'
'2862_left.jpg' '2424_left.jpg']
['2964_right.jpg' '680_right.jpg' '500_right.jpg' '2368_right.jpg'
'2820_right.jpg' '2769_right.jpg' '2696_right.jpg' '2890_right.jpg'
'940_right.jpg' '2553... | MIT | notebooks/Fundus/Single/Fundus_Analysis_Myopia.ipynb | mfc2496/EyeSee-Server |
Left and Right Images Together | myopia = np.concatenate((left_myopia,right_myopia),axis=0)
normal = np.concatenate((left_normal,right_normal),axis=0)
print("myopia: {}".format(len(myopia)))
print("Normal: {}".format(len(normal)))
dataset_dir = "/content/gdrive/MyDrive/Kaggle/preprocessed_images/"
image_size = 224
labels = []
dataset = []
... | _____no_output_____ | MIT | notebooks/Fundus/Single/Fundus_Analysis_Myopia.ipynb | mfc2496/EyeSee-Server |
**Keras Pretrained Models** | !kaggle datasets download -d gaborfodor/keras-pretrained-models
!unzip \*.zip && rm *.zip
!ls
pwd
from keras.applications.vgg16 import VGG16, preprocess_input
vgg16_weight_path = '/content/gdrive/MyDrive/Kaggle/vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5'
vgg = VGG16(
weights = vgg16_weight_path,
... | _____no_output_____ | MIT | notebooks/Fundus/Single/Fundus_Analysis_Myopia.ipynb | mfc2496/EyeSee-Server |
**Model** | from tensorflow.keras import Sequential
from keras import layers
from tensorflow.keras.layers import Flatten ,Dense
model = Sequential()
model.add(vgg)
model.add(Dense(256, activation='relu'))
model.add(layers.Dropout(rate=0.5))
model.add(Dense(128, activation='sigmoid'))
model.add(layers.Dropout(rate=0.2))... | _____no_output_____ | MIT | notebooks/Fundus/Single/Fundus_Analysis_Myopia.ipynb | mfc2496/EyeSee-Server |
Model's Summary | model.summary()
model.compile(optimizer="adam", loss="binary_crossentropy", metrics=["accuracy"])
history = model.fit(x_train, y_train,
batch_size = 32,
epochs = 30,
validation_data = (x_test, y_test)
)
%cd /content/gdrive/MyDrive/Kaggl... | precision recall f1-score support
0 0.97 0.97 0.97 118
1 0.97 0.97 0.97 118
accuracy 0.97 236
macro avg 0.97 0.97 0.97 236
weighted avg 0.97 0.97 0.97 ... | MIT | notebooks/Fundus/Single/Fundus_Analysis_Myopia.ipynb | mfc2496/EyeSee-Server |
Predictions | # from IPython.display import Image, display
# images = ["/content/gdrive/MyDrive/Kaggle/preprocessed_images/560_right.jpg",
# "/content/gdrive/MyDrive/Kaggle/preprocessed_images/1550_right.jpg",
# "/content/gdrive/MyDrive/Kaggle/preprocessed_images/2330_right.jpg",
# "/content/gdriv... | _____no_output_____ | MIT | notebooks/Fundus/Single/Fundus_Analysis_Myopia.ipynb | mfc2496/EyeSee-Server |
Loaded Model | pwd
from tensorflow import keras
model = keras.models.load_model('/content/gdrive/MyDrive/Kaggle/fundus_model_MYO.h5')
print('loaded')
model.summary()
from keras.utils.vis_utils import plot_model
plot_model(model, to_file='vgg.png')
from keras.preprocessing.image import load_img
image = load_img("/content/gdri... | _____no_output_____ | MIT | notebooks/Fundus/Single/Fundus_Analysis_Myopia.ipynb | mfc2496/EyeSee-Server |
Normal Fundus | def disease(predic):
if predic > 0.75:
return 'Pathological Myopia'
return 'Normal'
pred = model.predict(image)
status = disease(pred[0])
print("Situation: {}".format(status))
print("Percentage: {}".format(round(int(pred[0]), 1))) | Situation: Normal
Percentage: 0
| MIT | notebooks/Fundus/Single/Fundus_Analysis_Myopia.ipynb | mfc2496/EyeSee-Server |
Myopic Fundus | def ready_image(img_path):
image = load_img(img_path, target_size=(224, 224))
image = img_to_array(image)
image = image.reshape((1, image.shape[0], image.shape[1], image.shape[2]))
image = preprocess_input(image)
return image
image = ready_image("/content/gdrive/MyDrive/Kaggle/preprocessed_images/13_r... | Situation: Pathological Myopia
Percentage: 0
| MIT | notebooks/Fundus/Single/Fundus_Analysis_Myopia.ipynb | mfc2496/EyeSee-Server |
Started 15:05. Ended | cluster = gateway.new_cluster(image=os.environ['JUPYTER_IMAGE']) | _____no_output_____ | MIT | eksctl/dask-gateway-test.ipynb | salvis2/terraform-aws |
Build a kernel Matrix | # load the structures
frames = read('data/dft-smiles_500.xyz',':')
global_species = []
for frame in frames:
global_species.extend(frame.get_atomic_numbers())
global_species = np.unique(global_species)
# split the structures in 2 sets
frames_train = frames[:300]
frames_test = frames[300:]
# set up the soap paramete... | _____no_output_____ | MIT | examples/simple_molecule_examples.ipynb | felixmusil/ml_tools |
FPS selection of the samples | # load the structures
frames = read('data/dft-smiles_500.xyz',':300')
global_species = []
for frame in frames:
global_species.extend(frame.get_atomic_numbers())
global_species = np.unique(global_species)
# set up the soap parameters
soap_params = dict(rc=3.5, nmax=6, lmax=6, awidth=0.4,
global_sp... | _____no_output_____ | MIT | examples/simple_molecule_examples.ipynb | felixmusil/ml_tools |
FPS selection of the features | # load the structures
frames = read('data/dft-smiles_500.xyz',':300')
global_species = []
for frame in frames:
global_species.extend(frame.get_atomic_numbers())
global_species = np.unique(global_species)
# set up the soap parameters
soap_params = dict(rc=3.5, nmax=6, lmax=6, awidth=0.4,
global_sp... | _____no_output_____ | MIT | examples/simple_molecule_examples.ipynb | felixmusil/ml_tools |
get a cross validation score | # load the structures
frames = read('data/dft-smiles_500.xyz',':')
global_species = []
y = []
for frame in frames:
global_species.extend(frame.get_atomic_numbers())
y.append(frame.info['dft_formation_energy_per_atom_in_eV'])
y = np.array(y)
global_species = np.unique(global_species)
# set up the soap parameters... | _____no_output_____ | MIT | examples/simple_molecule_examples.ipynb | felixmusil/ml_tools |
LC | # load the structures
frames = read('data/dft-smiles_500.xyz',':')
global_species = []
y = []
for frame in frames:
global_species.extend(frame.get_atomic_numbers())
y.append(frame.info['dft_formation_energy_per_atom_in_eV'])
y = np.array(y)
global_species = np.unique(global_species)
# set up the soap parameters... | _____no_output_____ | MIT | examples/simple_molecule_examples.ipynb | felixmusil/ml_tools |
Table of Contents | %load_ext autoreload
%autoreload 2
from argo.workflows.dsl import Workflow
from argo.workflows.dsl import task
from argo.workflows.dsl import template
from argo.workflows.dsl.templates import V1Container
from argo.workflows.dsl.templates import V1alpha1Template
import yaml
from pprint import pprint
from argo.workflo... | _____no_output_____ | Apache-2.0 | examples/hello-world-single-task.ipynb | moshewe/argo-python-dsl |
--- | !sh -c '[ -f "hello-world-single-task.yaml" ] || curl -LO https://raw.githubusercontent.com/CermakM/argo-python-dsl/master/examples/hello-world-single-task.yaml'
from pathlib import Path
manifest = Path("./hello-world-single-task.yaml").read_text()
print(manifest)
class HelloWorld(Workflow):
@task
def A(s... | api_version: argoproj.io/v1alpha1
kind: Workflow
metadata:
generate_name: hello-world-
name: hello-world
spec:
entrypoint: main
templates:
- dag:
tasks:
- name: A
template: whalesay
name: main
- container:
args:
- hello world
command:
- cowsay
image: doc... | Apache-2.0 | examples/hello-world-single-task.ipynb | moshewe/argo-python-dsl |
--- | pprint(sanitize_for_serialization(wf))
pprint(yaml.safe_load(manifest))
assert sanitize_for_serialization(wf) == yaml.safe_load(manifest), "Manifests don't match." | _____no_output_____ | Apache-2.0 | examples/hello-world-single-task.ipynb | moshewe/argo-python-dsl |
How to detect breast cancer with a Support Vector Machine (SVM) and k-nearest neighbours clustering and compare results. Load some packages | import scipy
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import sklearn
from sklearn import preprocessing
from sklearn.model_selection import train_test_split # cross_validation is deprecated
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from skle... | NumPy must be 1.14 to run this, it is 1.20.3
Python should be version 2.7 or higher, it is 3.9.5 (tags/v3.9.5:0a7dcbd, May 3 2021, 17:27:52) [MSC v.1928 64 bit (AMD64)]
| MIT | ML_breast_cancer_detection_with_SVM_KNN.ipynb | psychty/jubilant-potato |
Read in the dataset from thw UCI data repository.
This details a lot of information from cells, such as their size, clump thickness, shape etc. A pathologist would consider these to determine whether a cell had cancer.
Specifically, we use the read_csv command from pd (pandas) package and supply a url of the dataset... | # Load Dataset
url = "https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/breast-cancer-wisconsin.data"
names = ['id', 'clump_thickness', 'uniform_cell_size', 'uniform_cell_shape',
'marginal_adhesion', 'single_epithelial_size', 'bare_nuclei',
'bland_chromatin', 'normal_nu... | _____no_output_____ | MIT | ML_breast_cancer_detection_with_SVM_KNN.ipynb | psychty/jubilant-potato |
Get some summary statistics for each of our variables | df.describe() | _____no_output_____ | MIT | ML_breast_cancer_detection_with_SVM_KNN.ipynb | psychty/jubilant-potato |
The dataset has some missing values. you can use .isnull() to return booleen true false and then tabulate that using .describe to say how many occurrences of true or false there are. | df.isnull().describe() | _____no_output_____ | MIT | ML_breast_cancer_detection_with_SVM_KNN.ipynb | psychty/jubilant-potato |
If you have missing data, you can replace it. | df.replace('?', -9999, inplace = True) | _____no_output_____ | MIT | ML_breast_cancer_detection_with_SVM_KNN.ipynb | psychty/jubilant-potato |
Class contains information on whether the tumour is benign (class = 2) or malignant (class = 4).
Next we plot a histogram of all variables to show the distrubition. | df.hist(figsize = (15,15))
plt.show() # by using plt.show() you render just the plot itself, because python will always display only the last command. | _____no_output_____ | MIT | ML_breast_cancer_detection_with_SVM_KNN.ipynb | psychty/jubilant-potato |
Look at the relationship between variables with a scatter matrix.
There looks like a pretty strong linear relationship between unifrorm cell shape and uniform cell size.
If you look at the cells representing comparisons with class (our outcome variable), it appears that there are a range of values for each of the ite... | scatter_matrix(df, figsize = (15,15))
plt.show() # by using plt.show() you render just the plot itself, because python will always display only the last command. | _____no_output_____ | MIT | ML_breast_cancer_detection_with_SVM_KNN.ipynb | psychty/jubilant-potato |
Models Create training and testing datasets.
We need to keep some of the data back to validate the model, seeing how well it generalises to other data.
x data will contain all the potential explanatory variables (called features I think in this context)
y will contain the outcome data (called label in ML) | X_df = np.array(df.drop(['class'], 1)) # this will create a variable called X_df which is df except class
y_df = np.array(df['class']) # this is just the class field
X_train, X_test, y_train, y_test = train_test_split(X_df, y_df, test_size=0.2) # split the dataset into four, two with features, two with labels (and ... | _____no_output_____ | MIT | ML_breast_cancer_detection_with_SVM_KNN.ipynb | psychty/jubilant-potato |
Add a seed to make the data reproducible (this will change the results a little each time we run the model) | seed = 8
scoring = 'accuracy' | _____no_output_____ | MIT | ML_breast_cancer_detection_with_SVM_KNN.ipynb | psychty/jubilant-potato |
Create training models make an empty list then append | models = []
models.append(('KNN', KNeighborsClassifier(n_neighbors = 5))) # You can alter the number of neighbours
models.append(('SVM', SVC()))
results = [] # also create lists for results and names. We use this to print out the results
names = [] | _____no_output_____ | MIT | ML_breast_cancer_detection_with_SVM_KNN.ipynb | psychty/jubilant-potato |
Evaluate each model in turn | for name, model in models:
kfold = model_selection.KFold(n_splits=10, random_state = seed, shuffle = True)
cv_results = model_selection.cross_val_score(model, X_train, y_train, cv=kfold, scoring=scoring)
results.append(cv_results)
names.append(name)
msg = "%s: %f (%f)" % (name, cv_results.mean(... | KNN: 0.967825 (0.023671)
SVM: 0.638539 (0.053601)
| MIT | ML_breast_cancer_detection_with_SVM_KNN.ipynb | psychty/jubilant-potato |
created by Ignacio Oguiza - email: timeseriesAI@gmail.com ROCKET (RandOm Convolutional KErnel Transform) is a new Time Series Classification (TSC) method that has just been released (Oct 29th, 2019), and has achieved **state-of-the-art performance on the UCR univariate time series classification datasets, surpassing ... | # ## NOTE: UNCOMMENT AND RUN THIS CELL IF YOU NEED TO INSTALL/ UPGRADE TSAI
# stable = False # True: latest version from github, False: stable version in pip
# if stable:
# !pip install -Uqq tsai
# else:
# !pip install -Uqq git+https://github.com/timeseriesAI/tsai.git
# ## NOTE: REMEMBER TO RESTART YOUR... | /usr/local/lib/python3.6/dist-packages/numba/np/ufunc/parallel.py:363: NumbaWarning: The TBB threading layer requires TBB version 2019.5 or later i.e., TBB_INTERFACE_VERSION >= 11005. Found TBB_INTERFACE_VERSION = 9107. The TBB threading layer is disabled.
warnings.warn(problem)
| Apache-2.0 | tutorial_nbs/02_ROCKET_a_new_SOTA_classifier.ipynb | duyniem/tsai |
How to use the original ROCKET method? 🚀 ROCKET is applied in 2 phases:1. Generate features from each time series: ROCKET calculates 20k features from each time series, independently of the sequence length. 2. Apply a classifier to those calculated features. Those features are then used by the classifier of your choi... | X_train, y_train, X_valid, y_valid = get_UCR_data('OliveOil')
seq_len = X_train.shape[-1]
X_train = X_train[:, 0]
X_valid = X_valid[:, 0]
labels = np.unique(y_train)
transform = {}
for i, l in enumerate(labels): transform[l] = i
y_train = np.vectorize(transform.get)(y_train)
y_valid = np.vectorize(transform.get)(y_vali... | _____no_output_____ | Apache-2.0 | tutorial_nbs/02_ROCKET_a_new_SOTA_classifier.ipynb | duyniem/tsai |
Now we normalize the data to mean 0 and std 1 **'per sample'** (recommended by the authors), that is they set each sample to mean 0 and std 1). | X_train = (X_train - X_train.mean(axis = 1, keepdims = True)) / (X_train.std(axis = 1, keepdims = True) + 1e-8)
X_valid = (X_valid - X_valid.mean(axis = 1, keepdims = True)) / (X_valid.std(axis = 1, keepdims = True) + 1e-8)
X_train.mean(axis = 1, keepdims = True).shape | _____no_output_____ | Apache-2.0 | tutorial_nbs/02_ROCKET_a_new_SOTA_classifier.ipynb | duyniem/tsai |
To generate the features, we first need to create the 10k random kernels that will be used to process the data. | kernels = generate_kernels(seq_len, 10000) | _____no_output_____ | Apache-2.0 | tutorial_nbs/02_ROCKET_a_new_SOTA_classifier.ipynb | duyniem/tsai |
Now we apply those ramdom kernels to the data | X_train_tfm = apply_kernels(X_train, kernels)
X_valid_tfm = apply_kernels(X_valid, kernels) | _____no_output_____ | Apache-2.0 | tutorial_nbs/02_ROCKET_a_new_SOTA_classifier.ipynb | duyniem/tsai |
2️⃣ Apply a classifierSo now we have the features, and we are ready to apply a classifier. Let's use a simple, linear RidgeClassifierCV as they propose in the paper. We first instantiate it. Note:alphas: Array of alpha values to try. Regularization strength; must be a positive float. Regularization improves the condit... | from sklearn.linear_model import RidgeClassifierCV
classifier = RidgeClassifierCV(alphas=np.logspace(-3, 3, 7), normalize=True)
classifier.fit(X_train_tfm, y_train)
classifier.score(X_valid_tfm, y_valid) | _____no_output_____ | Apache-2.0 | tutorial_nbs/02_ROCKET_a_new_SOTA_classifier.ipynb | duyniem/tsai |
☣️ **This is pretty impressive! It matches or exceeds the state-of-the-art performance without any fine tuning in <2 seconds!!!** | kernels = generate_kernels(seq_len, 10000)
X_train_tfm = apply_kernels(X_train, kernels)
X_valid_tfm = apply_kernels(X_valid, kernels)
from sklearn.linear_model import RidgeClassifierCV
classifier = RidgeClassifierCV(alphas=np.logspace(-3, 3, 7), normalize=True)
classifier.fit(X_train_tfm, y_train)
classifier.score(X_v... | _____no_output_____ | Apache-2.0 | tutorial_nbs/02_ROCKET_a_new_SOTA_classifier.ipynb | duyniem/tsai |
⚠️ Bear in mind that this process is not deterministic since there is randomness involved in the kernels. In thiis case, performance may vary between .9 to .933 How to use ROCKET with large and/ or multivariate datasets on GPU? - Recommended ⭐️ As stated before, the current ROCKET method doesn't support multivariate t... | X, y, splits = get_UCR_data('HandMovementDirection', split_data=False)
tfms = [None, [Categorize()]]
batch_tfms = [TSStandardize(by_sample=True)]
dls = get_ts_dls(X, y, splits=splits, tfms=tfms, drop_last=False, shuffle_train=False, batch_tfms=batch_tfms, bs=10_000) | _____no_output_____ | Apache-2.0 | tutorial_nbs/02_ROCKET_a_new_SOTA_classifier.ipynb | duyniem/tsai |
☣️☣️ You will be able to create a dls (TSDataLoaders) object with unusually large batch sizes. I've tested it with a large dataset and a batch size = 100_000 and it worked fine. This is because ROCKET is not a usual Deep Learning model. It just applies convolutions (kernels) one at a time to create the features. Instan... | model = build_ts_model(ROCKET, dls=dls) # n_kernels=10_000, kss=[7, 9, 11] set by default, but you can pass other values as kwargs | _____no_output_____ | Apache-2.0 | tutorial_nbs/02_ROCKET_a_new_SOTA_classifier.ipynb | duyniem/tsai |
Now generate rocket features for the entire train and valid datasets using the create_rocket_features convenience function `create_rocket_features`. And we now transform the original data, creating 20k features per sample | X_train, y_train = create_rocket_features(dls.train, model)
X_valid, y_valid = create_rocket_features(dls.valid, model)
X_train.shape, X_valid.shape | _____no_output_____ | Apache-2.0 | tutorial_nbs/02_ROCKET_a_new_SOTA_classifier.ipynb | duyniem/tsai |
2️⃣ Apply a classifier Once you build the 20k features per sample, you can use them to train any classifier of your choice. RidgeClassifierCV And now you apply a classifier of your choice. With RidgeClassifierCV in particular, there's no need to normalize the calculated features before passing them to the classifier,... | from sklearn.linear_model import RidgeClassifierCV
ridge = RidgeClassifierCV(alphas=np.logspace(-8, 8, 17), normalize=True)
ridge.fit(X_train, y_train)
print(f'alpha: {ridge.alpha_:.2E} train: {ridge.score(X_train, y_train):.5f} valid: {ridge.score(X_valid, y_valid):.5f}') | alpha: 1.00E+01 train: 1.00000 valid: 0.50000
| Apache-2.0 | tutorial_nbs/02_ROCKET_a_new_SOTA_classifier.ipynb | duyniem/tsai |
This result is amazing!! The previous state of the art (Inceptiontime) was .37837 Logistic Regression In the case of other classifiers (like Logistic Regression), the authors recommend a per-feature normalization. | eps = 1e-6
Cs = np.logspace(-5, 5, 11)
from sklearn.linear_model import LogisticRegression
best_loss = np.inf
for i, C in enumerate(Cs):
f_mean = X_train.mean(axis=0, keepdims=True)
f_std = X_train.std(axis=0, keepdims=True) + eps # epsilon to avoid dividing by 0
X_train_tfm2 = (X_train - f_mean) / f_std
... | 0 eps: 1.00E-06 C: 1.00E-05 loss: 1.35151 train_acc: 0.80000 valid_acc: 0.41892
1 eps: 1.00E-06 C: 1.00E-04 loss: 1.15433 train_acc: 1.00000 valid_acc: 0.45946
2 eps: 1.00E-06 C: 1.00E-03 loss: 0.85364 train_acc: 1.00000 valid_acc: 0.48649
3 eps: 1.00E-06 C: 1.00E-02 loss: 0.76183 train_acc: 1.00000 ... | Apache-2.0 | tutorial_nbs/02_ROCKET_a_new_SOTA_classifier.ipynb | duyniem/tsai |
☣️ Note: Epsilon has a large impact on the result. You can actually test several values to find the one that best fits your problem, but bear in mind you can only select C and epsilon based on train data!!! RandomSearch One way to do this would be to perform a random search using several epsilon and C values | n_tests = 10
epss = np.logspace(-8, 0, 9)
Cs = np.logspace(-5, 5, 11)
from sklearn.linear_model import LogisticRegression
best_loss = np.inf
for i in range(n_tests):
eps = np.random.choice(epss)
C = np.random.choice(Cs)
f_mean = X_train.mean(axis=0, keepdims=True)
f_std = X_train.std(axis=0, keepdims=T... | 0 eps: 1.00E-03 C: 1.00E-03 loss: 0.85501 train_acc: 1.00000 valid_acc: 0.48649
1 eps: 1.00E-02 C: 1.00E-03 loss: 0.86484 train_acc: 1.00000 valid_acc: 0.47297
2 eps: 1.00E-06 C: 1.00E+03 loss: 0.74367 train_acc: 1.00000 valid_acc: 0.48649
3 eps: 1.00E-04 C: 1.00E-05 loss: 1.35157 train_acc: 0.80... | Apache-2.0 | tutorial_nbs/02_ROCKET_a_new_SOTA_classifier.ipynb | duyniem/tsai |
In general, the original method may be a bit faster than the GPU method, but for larger datasets, there's a great benefit in using the GPU version. In addition to this, I have also run the code on the TSC UCR multivariate datasets (all the ones that don't contain nan values), and the results are also very good, beating... | X = concat(X_train, X_valid)
y = concat(y_train, y_valid)
splits = get_predefined_splits(X_train, X_valid)
tfms = [None, [Categorize()]]
dsets = TSDatasets(X, y, tfms=tfms, splits=splits)
dls = TSDataLoaders.from_dsets(dsets.train, dsets.valid, bs=128, batch_tfms=[TSStandardize(by_var=True)])# per feature normalizat... | _____no_output_____ | Apache-2.0 | tutorial_nbs/02_ROCKET_a_new_SOTA_classifier.ipynb | duyniem/tsai |
XGBoost | eps = 1e-6
# normalize 'per feature'
f_mean = X_train.mean(axis=0, keepdims=True)
f_std = X_train.std(axis=0, keepdims=True) + eps
X_train_norm = (X_train - f_mean) / f_std
X_valid_norm = (X_valid - f_mean) / f_std
import xgboost as xgb
classifier = xgb.XGBClassifier(max_depth=3,
learni... | _____no_output_____ | Apache-2.0 | tutorial_nbs/02_ROCKET_a_new_SOTA_classifier.ipynb | duyniem/tsai |
Brownian process in stock price dynamics Brownian Moton:source: https://en.wikipedia.org/wiki/Brownian_motion A **random-walk** can be seen as a **motion** resulting from a succession of discrete **random steps**.The random-walk after t... | # conda install -c anaconda pandas-datareader
# pip install pandas-datareader
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
# Possible steps
steps = [-1,1] # backward and forward of 1 units
# Nr of steps n_steps
n_steps = 100
# Initialise the random walk variable X
X = np.zeros(n_... | _____no_output_____ | MIT | Brownian_motion.ipynb | CarSomma/Brownian-Process |
**If we repeat the experiment where does the man end up in average?** | # Repeat the random walk n_trials time
# Record the last position for each trial
def monte_random_walk(n_steps,steps,n_trials):
X_fin = np.zeros(n_trials)#<-- X_fin numpy array of (N=n_trial) zeros
for i in range(n_trials):
X_fin[i] =random_walk(steps,n_steps)[-1]
return X_fin
n_trial = 20000
step... | _____no_output_____ | MIT | Brownian_motion.ipynb | CarSomma/Brownian-Process |
We can see a Brownian process $B(t)$ as a **continuous Gaussian** random walk. **Gaussian & continuous**: we divide the observation time $t$ into $N$ small timestep $\Delta t$, so that $t=N\cdot\Delta t$.For any time $t_i=i\cdot\Delta t$, the change in $B$ is normally distributed:$... | def brownian_motion(T,N,n_trials,random_seed = None):
np.random.seed(random_seed)
dt = T/N
random_steps = np.sqrt(dt)*np.random.normal(loc = 0,scale = 1,size = (N,n_trials))
random_steps[0,:] = 0
X = np.cumsum(random_steps,axis=0)
return X
T=7
N=100
n_trials=2000
random_seed = 1
dt=T/N
dt
X... | _____no_output_____ | MIT | Brownian_motion.ipynb | CarSomma/Brownian-Process |
Connection to stock-priceThe dynamics of stock-prices can be modeled by the following equation:\begin{equation}\tag{2}\Delta S_{t} = \mu S_{t} \Delta t + \sigma S_{t}\Delta B_{t}\end{equation}being:$S$ the stock price,$\mu$ the drift coefficient (a.k.a the mean of returns),$\sigma$ the diffusion coefficient (a.k.a the... | def stock_price(N,S0,u,sigma,T,n_trials,random_seed = None):
"""
N: number of intervals
S0: initial stock price
u: mean of returns over some period
sigma: volatility a.k.a. standard deviation of returns
random_seed: seed for pseudorandom generator
T: observation time
m: number of brownia... | _____no_output_____ | MIT | Brownian_motion.ipynb | CarSomma/Brownian-Process |
Scraping from Yahoo Finance | from pandas_datareader import data as scraper
import pandas as pd
symbol = 'FB' # 'FB'Facebook, 'FCA.MI' FIAT Crysler, 'AAPL' Apple
start_date = '2020-01-01'
end_date = '2020-12-31'
df = scraper.DataReader(symbol, 'yahoo', start_date, end_date)
df.head()
df.describe()
#close price
close_price = df['Close']
close_pri... | _____no_output_____ | MIT | Brownian_motion.ipynb | CarSomma/Brownian-Process |
what is the probability of having a loss after one year? | # Annual Return
annual_return_pct = (S_fin -S0)/S0
# Calculate mean and std from S_fin
mean_ar = np.mean(annual_return_pct)
median_ar=np.median(annual_return_pct)
std_ar = np.std(annual_return_pct)
min_ar = np.min(annual_return_pct)
max_ar = np.max(annual_return_pct)
print('*******************')
print(f' * Statistics ... | _____no_output_____ | MIT | Brownian_motion.ipynb | CarSomma/Brownian-Process |
Analysis of underlying distribution | x_min=-5
x_max=6
dx=.001
# Distribution and mode
lnd_ar,lognormal_pdf_ar,mode_ar,x_ar = lognorm_fit(annual_return_pct,x_min,x_max,dx)
# Plot distribution of simulated annual return
sns.distplot(annual_return_pct);
sns.lineplot(x_ar,lognormal_pdf_ar,label = 'log-normal');
plt.plot([mode_ar,mode_ar],[0,.9],'k-.',label= '... | **************************************
* Results *
**************************************
Return_1 Return_2 Probability
Loss 28.48 %
Gain 0.1% 1% 46.65 %
Gain 1% 2% 13.91 %
| MIT | Brownian_motion.ipynb | CarSomma/Brownian-Process |
City street network orientationsCompare the spatial orientations of city street networks with OSMnx. - [Overview of OSMnx](http://geoffboeing.com/2016/11/osmnx-python-street-networks/) - [GitHub repo](https://github.com/gboeing/osmnx) - [Examples, demos, tutorials](https://github.com/gboeing/osmnx-examples) - [Doc... | import matplotlib.pyplot as plt
import numpy as np
import osmnx as ox
import pandas as pd
ox.config(log_console=True, use_cache=True)
weight_by_length = False
ox.__version__
# define the study sites as label : query
places = {'Atlanta' : 'Atlanta, GA, USA',
'Boston' : 'Boston, MA, USA',
... | _____no_output_____ | MIT | notebooks/17-street-network-orientations.ipynb | baerbelblume/osmnx-examples |
Get the street networks and their edge bearings | def reverse_bearing(x):
return x + 180 if x < 180 else x - 180
bearings = {}
for place in sorted(places.keys()):
# get the graph
query = places[place]
G = ox.graph_from_place(query, network_type='drive')
# calculate edge bearings
Gu = ox.add_edge_bearings(ox.get_undirected(G))
... | _____no_output_____ | MIT | notebooks/17-street-network-orientations.ipynb | baerbelblume/osmnx-examples |
Visualize it | def count_and_merge(n, bearings):
# make twice as many bins as desired, then merge them in pairs
# prevents bin-edge effects around common values like 0° and 90°
n = n * 2
bins = np.arange(n + 1) * 360 / n
count, _ = np.histogram(bearings, bins=bins)
# move the last bin to the front, so eg ... | _____no_output_____ | MIT | notebooks/17-street-network-orientations.ipynb | baerbelblume/osmnx-examples |
Modelado de Robots Recordando la práctica anterior, tenemos que la ecuación diferencial que caracteriza a un sistema masa-resorte-amoritguador es:$$m \ddot{x} + c \dot{x} + k x = F$$y revisamos 3 maneras de obtener el comportamiento de ese sistema, sin embargo nos interesa saber el comportamiento de un sistema mas com... | from scipy.integrate import odeint
from numpy import linspace | _____no_output_____ | MIT | Practicas/.ipynb_checkpoints/Practica 5 - Modelado de Robots-checkpoint.ipynb | robblack007/clase-dinamica-robot |
y definiendo una función que devuelva un arreglo con los valores de $f(x)$ | def f(x, t):
from numpy import cos
q, q̇ = x
τ = 0
m = 1
g = 9.81
l = 1
return [q̇, τ - m*g*l*cos(q)/(m*l**2)] | _____no_output_____ | MIT | Practicas/.ipynb_checkpoints/Practica 5 - Modelado de Robots-checkpoint.ipynb | robblack007/clase-dinamica-robot |
Vamos a simular desde el tiempo $0$, hasta $10$, y las condiciones iniciales del pendulo son $q=0$ y $\dot{q} = 0$. | ts = linspace(0, 10, 100)
x0 = [0, 0] | _____no_output_____ | MIT | Practicas/.ipynb_checkpoints/Practica 5 - Modelado de Robots-checkpoint.ipynb | robblack007/clase-dinamica-robot |
Utilizamos la función ```odeint``` para simular el comportamiento del pendulo, dandole la función que programamos con la dinámica de $f(x)$ y sacamos los valores de $q$ y $\dot{q}$ que nos devolvió ```odeint``` envueltos en el estado $x$ | xs = odeint(func = f, y0 = x0, t = ts)
qs, q̇s = list(zip(*xs.tolist())) | _____no_output_____ | MIT | Practicas/.ipynb_checkpoints/Practica 5 - Modelado de Robots-checkpoint.ipynb | robblack007/clase-dinamica-robot |
En este punto ya tenemos nuestros datos de la simulación, tan solo queda graficarlos para interpretar los resultados: | %matplotlib inline
from matplotlib.pyplot import style, plot, figure
style.use("ggplot")
fig1 = figure(figsize = (8, 8))
ax1 = fig1.gca()
ax1.plot(xs);
fig2 = figure(figsize = (8, 8))
ax2 = fig2.gca()
ax2.plot(qs)
ax2.plot(q̇s); | _____no_output_____ | MIT | Practicas/.ipynb_checkpoints/Practica 5 - Modelado de Robots-checkpoint.ipynb | robblack007/clase-dinamica-robot |
Pero las gráficas de trayectoria son aburridas, recordemos que podemos hacer una animación con matplotlib: | from matplotlib import animation
from numpy import sin, cos, arange
# Se define el tamaño de la figura
fig = figure(figsize=(8, 8))
# Se define una sola grafica en la figura y se dan los limites de los ejes x y y
axi = fig.add_subplot(111, autoscale_on=False, xlim=(-1.5, 1.5), ylim=(-2, 1))
# Se utilizan graficas de ... | _____no_output_____ | MIT | Practicas/.ipynb_checkpoints/Practica 5 - Modelado de Robots-checkpoint.ipynb | robblack007/clase-dinamica-robot |
Load the data Without the known blooming bacteria (from American Gut paper) | ca.set_log_level('ERROR')
ratios=ca.read_amplicon('../lefse_ratios/ratios.biom','../studies/index.csv',
feature_metadata_file='../taxonomy/DB1-15_taxonomy_svs_numbers.tsv',normalize=None, min_reads=None)
ca.set_log_level('INFO')
ratios.sparse = False
ratios
np.sum(np.sum(ratios.data==0,axis=0)>3... | _____no_output_____ | MIT | scripts/ratios-lefse.ipynb | amnona/paper-metaanalysis |
Fix taxonomy and filter chloroplast/mitochondria | ratios.feature_metadata['taxonomy'] = ratios.feature_metadata.Taxon
ratios.feature_metadata['taxonomy'].fillna('NA',inplace=True)
ratios = ratios.filter_by_taxonomy(['chloroplast','cyanobacteria','mitochondria'],negate=True)
disease_colors = {}
disease_colors = {xx: (0,0,0) for xx in ratios.sample_metadata.disease.uniq... | _____no_output_____ | MIT | scripts/ratios-lefse.ipynb | amnona/paper-metaanalysis |
creat a chart pie for diseases | ratios.sample_metadata['pie_disease']=ratios.sample_metadata.disease.copy()
ratios.sample_metadata.pie_disease.replace('Gout','Other',inplace=True)
ratios.sample_metadata.pie_disease.replace('Irritable bowel syndrom','IBS',inplace=True)
ratios.sample_metadata.pie_disease.replace('Hepatitis B','Other',inplace=True)
rati... | _____no_output_____ | MIT | scripts/ratios-lefse.ipynb | amnona/paper-metaanalysis |
Prepare the colormap for the heatmapsWe want coolwarm, with white for exact 0s (which mean not present) | current_cmap = mpl.cm.get_cmap('coolwarm')
current_cmap.set_bad(color='red')
ncm = current_cmap(np.linspace(0,1,1000000))
ncm[500000]=(1,1,1,1)
ncm=mpl.colors.ListedColormap(ncm) | _____no_output_____ | MIT | scripts/ratios-lefse.ipynb | amnona/paper-metaanalysis |
Look at the data | ratios.feature_metadata
ratios.plot(gui='cli',norm=None,cmap=ncm ,clim=[-0.5,0.5], bad_color='w')
ratios.plot(gui='cli',norm=None,cmap=ncm ,clim=[-1,1], bad_color='w')
ratios=ratios.sort_abundance(key=np.mean)
ratios.plot(gui='cli',norm=None,cmap=ncm ,clim=[-1,1], bad_color='w')
# cu.splot(ratios,'disease',norm=None,cm... | _____no_output_____ | MIT | scripts/ratios-lefse.ipynb | amnona/paper-metaanalysis |
Plot all bacteria aggregate all samples by disease so CD/UC count as 1 | ratios_agg=ratios.aggregate_by_metadata('disease',agg='mean')
ratios_agg
# cu.splot(ratios_agg,'disease',norm=None,cmap=ncm,clim=[-0.25,0.25],xticks_max=None)
ratios_agg.plot(sample_field='disease',norm=None,cmap=ncm,clim=[-0.25,0.25],xticks_max=None)
ratios
np.sum(ratios_agg.data[:]>0)
np.sum(ratios_agg.data[:]<0)
np.... | _____no_output_____ | MIT | scripts/ratios-lefse.ipynb | amnona/paper-metaanalysis |
Sort by mean abundance over all diseaseWith 1 sample per disease (aggregation by mean) | ratios_agg=ratios_agg.sort_abundance(key=np.mean)
# cu.splot(ratios_agg,'disease',norm=None,cmap=ncm,clim=[-0.25,0.25],xticks_max=None)
allbact = ratios.filter_ids(ratios_agg.feature_metadata.index)
allbact = allbact.sort_samples('disease')
allbact
f=allbact.plot(sample_field='disease',norm=None,cmap=ncm,clim=[-1,1],xt... | _____no_output_____ | MIT | scripts/ratios-lefse.ipynb | amnona/paper-metaanalysis |
Plot the non-specific bacteriaUsing the binomial sign test (only on experiments where the bacteria is present), with at least 4 experiments per bacteria. FDR=0.1The test is done on 1 aggregated sample per disease to prevent bias by disease with many studies | np.random.seed(2020)
nonspecific_agg=cu.get_sign_pvals(ratios_agg,alpha=0.25,min_present=4)
nonspecific = ratios.filter_ids(nonspecific_agg.feature_metadata.index)
nonspecific = nonspecific.sort_samples('disease')
nonspecific.feature_metadata = nonspecific.feature_metadata.join(nonspecific_agg.feature_metadata,lsuffix=... | _____no_output_____ | MIT | scripts/ratios-lefse.ipynb | amnona/paper-metaanalysis |
Save the non-secific bacteria | nonspecific_agg.save('../lefse_ratios/nonspecific/nonspecific')
nonspecific_agg.save_fasta('../lefse_ratios/nonspecific/nonspecific.fa',header='seq')
nonspecific.save('../lefse_ratios/nonspecific/nonspecific_all',fmt='txt') | 2022-01-05 19:09:04 WARNING .txt format does not support taxonomy information in save. Saving without taxonomy.
| MIT | scripts/ratios-lefse.ipynb | amnona/paper-metaanalysis |
Also save only the ones going up or down | nsup_ids=nonspecific_agg.feature_metadata[nonspecific_agg.feature_metadata.esize > 0]
nsdown_ids=nonspecific_agg.feature_metadata[nonspecific_agg.feature_metadata.esize < 0]
len(nsup_ids)
len(nsdown_ids)
nsup = nonspecific.filter_ids(nsup_ids.index)
nsup.save('../lefse_ratios/nonspecific/nonspecific-up')
nsdown = nonsp... | _____no_output_____ | MIT | scripts/ratios-lefse.ipynb | amnona/paper-metaanalysis |
how many higher/lower in non-specific | np.sum(nonspecific_agg.feature_metadata.esize<0)
np.sum(nonspecific_agg.feature_metadata.esize>0) | _____no_output_____ | MIT | scripts/ratios-lefse.ipynb | amnona/paper-metaanalysis |
Get the enriched dbBact terms | nonspecific_agg.feature_metadata['_calour_stat'] = nonspecific_agg.feature_metadata['esize']
nonspecific_agg.feature_metadata['_calour_direction'] = 'down'
nonspecific_agg.feature_metadata.loc[nonspecific_agg.feature_metadata['esize']>0,'_calour_direction']='up'
f,dterms = nonspecific_agg.plot_diff_abundance_enrichment... | _____no_output_____ | MIT | scripts/ratios-lefse.ipynb | amnona/paper-metaanalysis |
Draw the dbbact term wordcloud for the non-specific bacteria | dbbact=ca.database._get_database_class('dbbact')
f=dbbact.draw_wordcloud(nonspecific)
f.savefig('../figures/sup-wordcloud-nonspecific-lefse.pdf')
f=dbbact.draw_wordcloud(nsup)
f.savefig('../figures/sup-wordcloud-nonspecific-up-lefse.pdf')
f=dbbact.draw_wordcloud(nsdown)
f.savefig('../figures/sup-wordcloud-nonspecific-d... | _____no_output_____ | MIT | scripts/ratios-lefse.ipynb | amnona/paper-metaanalysis |
IBD specific | def nzdiff(data,labels):
'''Calculate the mean difference between two groups without using 0s
used for the calour.diff_abundance for only non-zero samples
Parameters
----------
data: np.array
sample * feature(similar to calour Experiment.data)
labels:::: np.array of 0s and 1s
... | _____no_output_____ | MIT | scripts/ratios-lefse.ipynb | amnona/paper-metaanalysis |
remove the biopsies studies | ratios_no_biop = ratios.filter_samples('_sample_id',['23', '29', '49', '52'],negate=True)
ratios_no_biop | _____no_output_____ | MIT | scripts/ratios-lefse.ipynb | amnona/paper-metaanalysis |
Calculate the specific bacteria without the Gevers biopsies studies | def nice_taxonomy(exp):
'''add nice taxonomy string (only phyla+genus+species if available) for heatmap
Parameters
----------
exp: calour.AmpliconExperiment
with the taxonomy in 'Taxon' field
Returns
-------
exp: calour.AmpliconExperiment, with added feature metadata field ... | _____no_output_____ | MIT | scripts/ratios-lefse.ipynb | amnona/paper-metaanalysis |
draw the wordcloud for the CD/UC specific bacteria | f=dbbact.draw_wordcloud(specific_no_biop)
f.savefig('../figures/sup-wordcloud-specific-lefse.pdf') | _____no_output_____ | MIT | scripts/ratios-lefse.ipynb | amnona/paper-metaanalysis |
Venn comparison to main analysis | import matplotlib_venn
ns_norarefaction_down = pd.read_csv('../ratios/nonspecific/nonspecific-down_feature.txt',sep='\t')
ns_lefse_down = pd.read_csv('../lefse_ratios/nonspecific/nonspecific-down_feature.txt',sep='\t')
ns_norarefaction_up = pd.read_csv('../ratios/nonspecific/nonspecific-up_feature.txt',sep='\t')
ns_le... | _____no_output_____ | MIT | scripts/ratios-lefse.ipynb | amnona/paper-metaanalysis |
compare lefse to nrmd using all lefse features and direction of change | nrmd_up=pd.read_csv('../ratios/nonspecific/nonspecific-up_feature.txt',sep='\t',index_col=0)
nrmd_down=pd.read_csv('../ratios/nonspecific/nonspecific-down_feature.txt',sep='\t',index_col=0)
all_lefse = pd.read_csv('../lefse_ratios/all_lefse_ratios.txt',sep='\t',index_col=0)
up_dir=all_lefse.filter(nrmd_up.index,axis='i... | _____no_output_____ | MIT | scripts/ratios-lefse.ipynb | amnona/paper-metaanalysis |
Use BlackJAX with Numpyro BlackJAX can take any log-probability function as long as it is compatible with JAX's JIT. In this notebook we show how we can use Numpyro as a modeling language and BlackJAX as an inference library.We reproduce the Eight Schools example from the [Numpyro documentation](https://github.com/pyr... | import jax
import numpy as np
import numpyro
import numpyro.distributions as dist
from numpyro.infer.reparam import TransformReparam
from numpyro.infer.util import initialize_model
import blackjax
num_warmup = 1000
# We can use this notebook for simple benchmarking by setting
# below to True and run from Terminal.
# ... | _____no_output_____ | Apache-2.0 | examples/use_with_numpyro.ipynb | hriebl/blackjax |
Data | # Data of the Eight Schools Model
J = 8
y = np.array([28.0, 8.0, -3.0, 7.0, -1.0, 1.0, 18.0, 12.0])
sigma = np.array([15.0, 10.0, 16.0, 11.0, 9.0, 11.0, 10.0, 18.0]) | _____no_output_____ | Apache-2.0 | examples/use_with_numpyro.ipynb | hriebl/blackjax |
Model We use the non-centered version of the model described towards the end of the README on Numpyro's repository: | # Eight Schools example - Non-centered Reparametrization
def eight_schools_noncentered(J, sigma, y=None):
mu = numpyro.sample("mu", dist.Normal(0, 5))
tau = numpyro.sample("tau", dist.HalfCauchy(5))
with numpyro.plate("J", J):
with numpyro.handlers.reparam(config={"theta": TransformReparam()}):
... | _____no_output_____ | Apache-2.0 | examples/use_with_numpyro.ipynb | hriebl/blackjax |
We need to translate the model into a log-probability function that will be used by BlackJAX to perform inference. For that we use the `initialize_model` function in Numpyro's internals. We will also use the initial position it returns: | rng_key = jax.random.PRNGKey(0)
init_params, potential_fn_gen, *_ = initialize_model(
rng_key,
eight_schools_noncentered,
model_args=(J, sigma, y),
dynamic_args=True,
) | _____no_output_____ | Apache-2.0 | examples/use_with_numpyro.ipynb | hriebl/blackjax |
Now we create the potential using the `potential_fn_gen` provided by Numpyro and initialize the NUTS state with BlackJAX: | if RUN_BENCHMARK:
print("\nBlackjax:")
print("-> Running warmup.") | _____no_output_____ | Apache-2.0 | examples/use_with_numpyro.ipynb | hriebl/blackjax |
We now run the window adaptation in BlackJAX: | %%time
initial_position = init_params.z
logprob = lambda position: -potential_fn_gen(J, sigma, y)(position)
adapt = blackjax.window_adaptation(
blackjax.nuts, logprob, num_warmup, target_acceptance_rate=0.8
)
last_state, kernel, _ = adapt.run(rng_key, initial_position) | CPU times: user 2.43 s, sys: 7.96 ms, total: 2.44 s
Wall time: 2.42 s
| Apache-2.0 | examples/use_with_numpyro.ipynb | hriebl/blackjax |
Let us now perform inference using the previously computed step size and inverse mass matrix. We also time the sampling to give you an idea of how fast BlackJAX can be on simple models: | if RUN_BENCHMARK:
print("-> Running sampling.")
%%time
def inference_loop(rng_key, kernel, initial_state, num_samples):
@jax.jit
def one_step(state, rng_key):
state, info = kernel(rng_key, state)
return state, (state, info)
keys = jax.random.split(rng_key, num_samples)
_, (states,... | CPU times: user 2.25 s, sys: 30.2 ms, total: 2.28 s
Wall time: 2.26 s
| Apache-2.0 | examples/use_with_numpyro.ipynb | hriebl/blackjax |
Let us compute the average acceptance probability and check the number of divergences (to make sure that the model sampled correctly, and that the sampling time is not a result of a majority of divergent transitions): | acceptance_rate = np.mean(infos[0])
num_divergent = np.mean(infos[1])
print(f"\nAcceptance rate: {acceptance_rate:.2f}")
print(f"{100*num_divergent:.2f}% divergent transitions") |
Acceptance rate: 0.89
0.02% divergent transitions
| Apache-2.0 | examples/use_with_numpyro.ipynb | hriebl/blackjax |
Let us now plot the distribution of the parameters. Note that since we use a transformed variable, Numpyro does not output the school treatment effect directly: | if not RUN_BENCHMARK:
import seaborn as sns
from matplotlib import pyplot as plt
samples = states.position
fig, axes = plt.subplots(ncols=2)
fig.set_size_inches(12, 5)
sns.kdeplot(samples["mu"], ax=axes[0])
sns.kdeplot(samples["tau"], ax=axes[1])
axes[0].set_xlabel("mu")
axes[1].se... | Relative treatment effect for school 0: 0.34
Relative treatment effect for school 1: 0.11
Relative treatment effect for school 2: -0.09
Relative treatment effect for school 3: 0.07
Relative treatment effect for school 4: -0.16
Relative treatment effect for school 5: -0.07
Relative treatment effect for school 6: 0.35
Re... | Apache-2.0 | examples/use_with_numpyro.ipynb | hriebl/blackjax |
Compare sampling time with NumpyroWe compare the time it took BlackJAX to do the warmup for 1,000 iterations and then taking 100,000 samples with Numpyro's: | from numpyro.infer import MCMC, NUTS
if RUN_BENCHMARK:
print("\nNumpyro:")
print("-> Running warmup+sampling.")
%%time
nuts_kernel = NUTS(eight_schools_noncentered, target_accept_prob=0.8)
mcmc = MCMC(
nuts_kernel, num_warmup=num_warmup, num_samples=num_sample, progress_bar=False
)
rng_key = jax.random.PR... |
Blackjax average 7.11 leapfrog per iteration.
Numpyro average 8.91 leapfrog per iteration.
| Apache-2.0 | examples/use_with_numpyro.ipynb | hriebl/blackjax |
The visualization used for this homework is based on Alexandr Verinov's code. Generative models In this homework we will try several criterions for learning an implicit model. Almost everything is written for you, and you only need to implement the objective for the game and play around with the model. **0)** Read t... | #!L
"""
Please, implement everything in one notebook, using if statements to switch between the tasks
"""
TASK = 1 # 2, 3, 4, 5 | _____no_output_____ | MIT | homework03/homework03_part3_gan_basic.ipynb | VendettaPrime/Practical_DL |
Imports | #!L
import numpy as np
import time
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torch
import matplotlib.pyplot as plt
%matplotlib inline
np.random.seed(12345)
lims=(-5, 5) | _____no_output_____ | MIT | homework03/homework03_part3_gan_basic.ipynb | VendettaPrime/Practical_DL |
Define sampler from real data and Z | #!L
from scipy.stats import rv_discrete
MEANS = np.array(
[[-1,-3],
[1,3],
[-2,0],
])
COVS = np.array(
[[[1,0.8],[0.8,1]],
[[1,-0.5],[-0.5,1]],
[[1,0],[0,1]],
])
PROBS = np.array([
0.2,
0.5,
0.3
])
assert len(MEANS) == le... | _____no_output_____ | MIT | homework03/homework03_part3_gan_basic.ipynb | VendettaPrime/Practical_DL |
Visualization functions | #!L
def vis_data(data):
"""
Visualizes data as histogram
"""
hist = np.histogram2d(data[:, 1], data[:, 0], bins=100, range=[lims, lims])
plt.pcolormesh(hist[1], hist[2], hist[0], alpha=0.5)
fixed_noise = sample_noise(1000)
def vis_g():
"""
Visualizes generator's samples as circles
... | _____no_output_____ | MIT | homework03/homework03_part3_gan_basic.ipynb | VendettaPrime/Practical_DL |
Define architectures After you've passed task 1 you can play with architectures. Generator | #!L
class Generator(nn.Module):
def __init__(self, noise_dim, out_dim, hidden_dim=100):
super(Generator, self).__init__()
self.fc1 = nn.Linear(noise_dim, hidden_dim)
nn.init.xavier_normal_(self.fc1.weight)
nn.init.constant_(self.fc1.bias, 0.0)
self.fc2 = nn.... | _____no_output_____ | MIT | homework03/homework03_part3_gan_basic.ipynb | VendettaPrime/Practical_DL |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.