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 see that the ``first`` key in this example ``Series`` data is the tuple (0,0,0), corresponding to an x, y, z coordinate of an original movie. | key | _____no_output_____ | Apache-2.0 | python/doc/tutorials/src/basic_usage.ipynb | broxtronix/thunder |
The value in this case is a time series of 240 observations, represented as a 1d numpy array. | value.shape | _____no_output_____ | Apache-2.0 | python/doc/tutorials/src/basic_usage.ipynb | broxtronix/thunder |
We can extract a random subset of records and plot their time series, after converting to `TimeSeries` (which enables time-specific methods), and applying a simple baseline normalization. Here and elsewhere, we'll use the excellent ``seaborn`` package for styling figures, but this is entirely optional. | %matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_context("notebook")
examples = data.toTimeSeries().normalize().subset(50, thresh=0.05)
sns.set_style('darkgrid')
plt.plot(examples.T); | _____no_output_____ | Apache-2.0 | python/doc/tutorials/src/basic_usage.ipynb | broxtronix/thunder |
We can also compute a statistic for each record using the method: | means = data.seriesStdev()
means.first() | _____no_output_____ | Apache-2.0 | python/doc/tutorials/src/basic_usage.ipynb | broxtronix/thunder |
``means`` is now itself a ``Series``, where the value of each record is the mean across time For this ``Series``, since the keys correspond to spatial coordinates, we can ``pack`` the results back into a local array. ``pack`` is an operation that converts ``Series`` data, with spatial coordinates as keys, into an n-dim... | img = means.pack()
img.shape | _____no_output_____ | Apache-2.0 | python/doc/tutorials/src/basic_usage.ipynb | broxtronix/thunder |
``pack`` is an example of a local operation, meaning that all the data involved will be sent to the Spark driver node. For larger data sets, this can be very problematic - it's a good idea to downsample, subselect, or otherwise reduce the size of your data before attempting to ``pack`` large data sets!To look at this a... | from thunder import Colorize
image = Colorize.image
image(img[:,:,0]) | _____no_output_____ | Apache-2.0 | python/doc/tutorials/src/basic_usage.ipynb | broxtronix/thunder |
It's also easy to export the result to a ``numpy`` or ``MAT`` file. ```tsc.export(img, "directory", "npy")tsc.export(img, "directory", "mat")``` This will put a ``npy`` file or ``MAT`` file called ``meanval`` in the folder ``directory`` in your current directory. You can also export to a location of Amazon S3 or Google... | tsc.loadExample() | _____no_output_____ | Apache-2.0 | python/doc/tutorials/src/basic_usage.ipynb | broxtronix/thunder |
Some of them are `Series`, some are `Images`, and some are associated `Params` (e.g. covariates). Let's load an `Images` dataset: | images = tsc.loadExample('mouse-images')
images | _____no_output_____ | Apache-2.0 | python/doc/tutorials/src/basic_usage.ipynb | broxtronix/thunder |
Now every record is an key-value pair where the key is an identifier, and the value is an image | key, value = images.first() | _____no_output_____ | Apache-2.0 | python/doc/tutorials/src/basic_usage.ipynb | broxtronix/thunder |
The key is an integer | key | _____no_output_____ | Apache-2.0 | python/doc/tutorials/src/basic_usage.ipynb | broxtronix/thunder |
And the value is a two-dimensional array | value.shape | _____no_output_____ | Apache-2.0 | python/doc/tutorials/src/basic_usage.ipynb | broxtronix/thunder |
Although `images` is not an array, some syntactic sugar supports easy indexing: | im = images[0]
image(im) | _____no_output_____ | Apache-2.0 | python/doc/tutorials/src/basic_usage.ipynb | broxtronix/thunder |
And we can now apply simple parallelized image processing routines | im = images.gaussianFilter(3).subsample(3)[0]
image(im) | _____no_output_____ | Apache-2.0 | python/doc/tutorials/src/basic_usage.ipynb | broxtronix/thunder |
Print Cirq Circuit and Statevector | # importing Qiskit
from qiskit import Aer, transpile, assemble
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit.visualization import plot_histogram, plot_bloch_multivector
from qiskit.visualization import plot_state_paulivec, plot_state_hinton, plot_state_city
from qiskit.visualization ... | _____no_output_____ | MIT | Paper Figures/Introspection Code/Introspection Qiskit.ipynb | Lilgabz/Quantum-Algorithm-Implementations |
Args | class args:
save_dir = "weights/"
debug = True
# model
routings = 1
# hp
batch_size = 32
lr = 0.001
lr_decay = 1.0
lam_recon = 0.392
# training
epochs = 3
shift_fraction = 0.1
digit = 5 | _____no_output_____ | MIT | run.ipynb | ghetthub/capsnet |
Load data | (x_train, y_train), (x_test, y_test) = capsulenet.load_mnist() | _____no_output_____ | MIT | run.ipynb | ghetthub/capsnet |
Define model | model, eval_model, manipulate_model = capsulenet.CapsNet(input_shape=x_train.shape[1:],
n_class=len(np.unique(np.argmax(y_train, 1))),
routings=args.routings) | _____no_output_____ | MIT | run.ipynb | ghetthub/capsnet |
Training | capsulenet.train(model=model, data=((x_train, y_train), (x_test, y_test)), args=args)
capsulenet.test(eval_model, data=(x_test, y_test), args=args) | ------------------------------Begin: test------------------------------
Test acc: 0.9784
Reconstructed images are saved to weights//real_and_recon.png
------------------------------End: test------------------------------
| MIT | run.ipynb | ghetthub/capsnet |
Recordá abrir en una nueva pestaña Modelos no paramétricos: K-Nearest Neighbours y Árboles de decisiónDocumentación:- KNN para clasificación: https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsClassifier.htmlsklearn.neighbors.KNeighborsClassifier- KNN para regresión: https://scikit-learn... | import os
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import seaborn as sns
import pandas as pd
import numpy as np
from sklearn.datasets import make_classification, make_blobs, load_breast_cancer
from sklearn.preprocessing import OrdinalEncoder
from sklearn.model_selection import train... | _____no_output_____ | MIT | MachineLearning/5_KNNyArbolesDeDecision/KNN_Arboles.ipynb | guillelencina/cursos-python |
1. KNN 1.1 Introducción: Fronteras de decisiónPara familirizarnos con este modelo y podervisualizar como quedan las fronteras de decisión empezaremos con un problema de clasificación binaria con dos features con un dataset de juguete que generaremos nosotros con la función [make_classification](https://scikit-learn.o... | # construyamos el dataset para un problema de clasificación binaria de dos dimensiones
X, y = make_classification(n_samples=200, n_features=2, n_informative=2, n_redundant=0, n_classes=2,n_clusters_per_class=1,
random_state=1, class_sep=1.1)
# scatter plot, colores por etiquetas
df = pd.DataF... | _____no_output_____ | MIT | MachineLearning/5_KNNyArbolesDeDecision/KNN_Arboles.ipynb | guillelencina/cursos-python |
1.2 Conjunto de datos de cáncer de mamaEl conjunto de datos etiquetado proviene de la "Base de datos (diagnóstico) de cáncer de mama de Wisconsin" disponible gratuitamente en la biblioteca sklearn de python. Para obtener más detalles, consulte:https://archive.ics.uci.edu/ml/datasets/Breast+Cancer+Wisconsin+%28Diagnost... | data = load_breast_cancer()
#print(data.DESCR)
print("Descripción:")
print(data.keys()) # dict_keys(['target_names', 'target', 'feature_names', 'data', 'DESCR'])
print("---")
# Note that we need to reverse the original '0' and '1' mapping in order to end up with this mapping:
# Benign = 0 (negative class)
# Malignant... | _____no_output_____ | MIT | MachineLearning/5_KNNyArbolesDeDecision/KNN_Arboles.ipynb | guillelencina/cursos-python |
1.3 Overfitting: cantidad de vecinos y pesos | # veamos como le va a nuestro modelo variando la cantidad de vecinos y el tipo de peso
valores_k = list(range(1,50,4))
resultados_train_u = []
resultados_test_u = []
resultados_train_w = []
resultados_test_w = []
for k in valores_k:
# instanciamos el modelo uniforme
clf_u = KNeighborsClassifier(n_neighbors=k... | precision recall f1-score support
benign 0.96 0.98 0.97 90
malignant 0.96 0.92 0.94 53
accuracy 0.96 143
macro avg 0.96 0.95 0.95 143
weighted avg 0.96 0.96 0.96 ... | MIT | MachineLearning/5_KNNyArbolesDeDecision/KNN_Arboles.ipynb | guillelencina/cursos-python |
1.4 Efectos de escalaDado que KNN esta basado en distancias si no usamos una distancia que involucra la varianza entre variables como la distancia de Mahalabois, nuestro modelo se verá afectado
XX[:,0] = XX[:,0]*30 + 150
print('Media x: {}'.format(np.mean(XX[:,0])))
print('SD x: {}'.format(np.std(XX[:,0])))
print('Medi... | 0.9675
| MIT | MachineLearning/5_KNNyArbolesDeDecision/KNN_Arboles.ipynb | guillelencina/cursos-python |
*** 2. Árboles de decisiónContinuaremos trabajando con el dataset de cancer de mama para familiarizarnos con los árboles de decisión 2.1 Mi primer arbolito | # instanciemos el modelo y entremoslo en el conjunto de autos
arbol = DecisionTreeClassifier(criterion='gini', max_depth=2, min_samples_leaf=1, min_samples_split=2, ccp_alpha=0)
arbol.fit(X_train,y_train)
accuracy_score(y_train, arbol.predict(X_train))
# veamos que tan bien le fue a este modelo
print(classification_rep... | _____no_output_____ | MIT | MachineLearning/5_KNNyArbolesDeDecision/KNN_Arboles.ipynb | guillelencina/cursos-python |
2.2 Feature importanceLos árboles nos permiten definir una manera de medir la importancia de los features (o *Feature Importances*) basado en la ganancia de información obtenida cada vez que se utilizo cada feature para hacer un split. Para esto, una vez entrando el árbol, el método que utilizaremos es: ``` arbol.feat... | # calculando las 5 feature importances mas altas
importances = pd.Series(arbol.feature_importances_).sort_values(ascending=False)[:5]
importances
f5_names = list(pd.Series(data.feature_names)[importances.index.to_list()])
fig, ax = plt.subplots()
importances.plot.barh(ax=ax)
ax.set_yticklabels(f5_names)
ax.invert_yaxis... | _____no_output_____ | MIT | MachineLearning/5_KNNyArbolesDeDecision/KNN_Arboles.ipynb | guillelencina/cursos-python |
2.3 Desbalance de clasesComo este dataset tiene un desbalance de clases, podes incluir eso en el modelo utilizando el parámetro class_weight que nos permite manejar directamente el desbalance | arbol = DecisionTreeClassifier(criterion='gini', max_depth=2, min_samples_leaf=1,
min_samples_split=2, ccp_alpha=0, class_weight="balanced")
arbol.fit(X_train, y_train)
accuracy_score(y_train, arbol.predict(X_train))
print(classification_report(y_true=y_test,y_pred=arbol.predict(X_test)))... | _____no_output_____ | MIT | MachineLearning/5_KNNyArbolesDeDecision/KNN_Arboles.ipynb | guillelencina/cursos-python |
2.4 VisualizaciónPara visualizar el árbol sklearn tiene el método tree.plot_tree: | plot_tree(arbol); | _____no_output_____ | MIT | MachineLearning/5_KNNyArbolesDeDecision/KNN_Arboles.ipynb | guillelencina/cursos-python |
Podemos obtener una representación mas estilizada con la ayuda de las librerías *graphviz* + *dot*. Ref: https://towardsdatascience.com/visualizing-decision-trees-with-python-scikit-learn-graphviz-matplotlib-1c50b4aa68dc | # libreria
from sklearn.externals.six import StringIO
from IPython.display import Image
from sklearn.tree import export_graphviz
import pydotplus
import matplotlib.pyplot as plt
dot_data = StringIO()
export_graphviz(arbol, out_file=dot_data,
filled=True, rounded=True,
special_chara... | /usr/local/lib/python3.7/dist-packages/sklearn/externals/six.py:31: FutureWarning: The module is deprecated in version 0.21 and will be removed in version 0.23 since we've dropped support for Python 2.7. Please rely on the official version of six (https://pypi.org/project/six/).
"(https://pypi.org/project/six/).", Fu... | MIT | MachineLearning/5_KNNyArbolesDeDecision/KNN_Arboles.ipynb | guillelencina/cursos-python |
2.5 Overfitting: profundidad del árbol y post-pruningDado que los árboles son modelos que tienden a overfittear tenemos que recurrir a distintas técnicas para mitigar este problema. Veamos primero el efecto de la profundidad del árbol en el trade-off sesgo varianza. | profundidad = list(range(1,20))
resultados_train = []
resultados_test = []
for depth in profundidad:
# instanciamos el modelo uniforme
arbol = DecisionTreeClassifier(criterion='gini', max_depth=depth, min_samples_leaf=1, min_samples_split=2, ccp_alpha=0, class_weight="balanced")
arbol.fit(X_train, y_train... | _____no_output_____ | MIT | MachineLearning/5_KNNyArbolesDeDecision/KNN_Arboles.ipynb | guillelencina/cursos-python |
Una técnica que nos permite mitigar el overfitting es lo que se conoce como post-prunning. El objetivo de esta técnica es *podar* el árbol entrenado, penalizando de alguna forma los árboles más complejos. El algortimo de poda que tenemos implementado en Scikit-Learn es el [Minimal Cost-Complexity Pruning](https://sciki... | arbol = DecisionTreeClassifier(criterion='gini', ccp_alpha=0.01)
arbol.fit(X_train, y_train)
#print(classification_report(y_true=y_test,y_pred=arbol.predict(X_test)))
print('Accuracy en entrenamiento: %f' % accuracy_score(y_train,arbol.predict(X_train)))
print('Accuracy en test: %f' % accuracy_score(y_test,arbol.predic... | _____no_output_____ | MIT | MachineLearning/5_KNNyArbolesDeDecision/KNN_Arboles.ipynb | guillelencina/cursos-python |
This notebook trains a N2V network in the first step and then finetunes it for segmentation. | # We import all our dependencies.
import warnings
warnings.filterwarnings('ignore')
import sys
sys.path.append('../../')
from voidseg.models import Seg, SegConfig
from n2v.models import N2VConfig, N2V
import numpy as np
from csbdeep.utils import plot_history
from voidseg.utils.misc_utils import combine_train_test_data,... | Using TensorFlow backend.
| BSD-3-Clause | examples/DSB2018/U-Net_Finetune.ipynb | psteinb/VoidSeg |
Download DSB2018 data.From the Kaggle 2018 Data Science Bowl challenge, we take the same subset of data as has been used [here](https://github.com/mpicbg-csbd/stardist), showing a diverse collection of cell nuclei imaged by various fluorescence microscopes. We extracted 4870 image patches of size 128×128 from the trai... | # create a folder for our data
if not os.path.isdir('./data'):
os.mkdir('data')
# check if data has been downloaded already
zipPath="data/DSB.zip"
if not os.path.exists(zipPath):
#download and unzip data
data = urllib.request.urlretrieve('https://owncloud.mpi-cbg.de/index.php/s/LIN4L4R9b2gebDX/download', z... | _____no_output_____ | BSD-3-Clause | examples/DSB2018/U-Net_Finetune.ipynb | psteinb/VoidSeg |
The downloaded data is in `npz` format and the cell below extracts the training, validation and test data as numpy arrays | trainval_data = np.load('data/DSB/train_data/dsb2018_TrainVal40.npz')
test_data = np.load('data/DSB/test_data/dsb2018_Test40.npz', allow_pickle=True)
train_images = trainval_data['X_train']
val_images = trainval_data['X_val']
test_images = test_data['X_test']
train_masks = trainval_data['Y_train']
val_masks = trainv... | Shape of train_images: (3800, 128, 128) , Shape of train_masks: (3800, 128, 128)
Shape of val_images: (670, 128, 128) , Shape of val_masks: (670, 128, 128)
Shape of test_images: (50,) , Shape of test_masks: (50,)
| BSD-3-Clause | examples/DSB2018/U-Net_Finetune.ipynb | psteinb/VoidSeg |
Data preparation for training a N2V networkSince, we can use all the noisy data for training N2V network, we combine the noisy train_images and test_images and use them as input to the N2V network. | X, Y = combine_train_test_data(X_train=train_images,Y_train=train_masks,X_test=test_images,Y_test=test_masks)
print("Combined Dataset Shape", X.shape)
X_val = val_images
Y_val = val_masks | _____no_output_____ | BSD-3-Clause | examples/DSB2018/U-Net_Finetune.ipynb | psteinb/VoidSeg |
Next, we shuffle the training pairs and augment the training and validation data. | random_seed = 1 # Seed to shuffle training data (annotated GT and raw image pairs)
X, Y = shuffle_train_data(X, Y, random_seed = random_seed)
print("Training Data \n..................")
X, Y = augment_data(X, Y)
print("\n")
print("Validation Data \n..................")
X_val, Y_val = augment_data(X_val, Y_val)
# Addin... | (34400, 128, 128, 1)
(5360, 128, 128, 1)
| BSD-3-Clause | examples/DSB2018/U-Net_Finetune.ipynb | psteinb/VoidSeg |
Let's look at one of our training and validation patches. | sl=0
plt.figure(figsize=(14,7))
plt.subplot(1,2,1)
plt.imshow(X[sl,...,0], cmap='gray')
plt.title('Training Patch');
plt.subplot(1,2,2)
plt.imshow(X_val[sl,...,0], cmap='gray')
plt.title('Validation Patch'); | _____no_output_____ | BSD-3-Clause | examples/DSB2018/U-Net_Finetune.ipynb | psteinb/VoidSeg |
Configure N2V Network The data preparation for training a denoising N2V network is now done. Next, we configure N2V network by specifying `N2VConfig` parameters. | config = N2VConfig(X, unet_kern_size=3, n_channel_out=1,train_steps_per_epoch=400, train_epochs=200,
train_loss='mse', batch_norm=True,
train_batch_size=128, n2v_perc_pix=0.784, n2v_patch_shape=(64, 64),
unet_n_first = 32,
unet_residual = Fal... | _____no_output_____ | BSD-3-Clause | examples/DSB2018/U-Net_Finetune.ipynb | psteinb/VoidSeg |
Now, we begin training the denoising N2V model. In case, a trained model is available, that model is loaded else a new model is trained. | # We are ready to start training now.
query_weightpath = os.getcwd()+"/models/"+model_name
weights_present = False
for file in os.listdir(query_weightpath):
if(file == "weights_best.h5"):
print("Found weights of a trained N2V network, loading it for prediction!")
weights_present = True
brea... | Found weights of a trained N2V network, loading it for prediction!
| BSD-3-Clause | examples/DSB2018/U-Net_Finetune.ipynb | psteinb/VoidSeg |
Data preparation for segmentation stepNext, we normalize all raw data with the mean and std (standard deviation) of the raw `train_images`. Then, we shuffle the raw training images and the correponding Ground Truth (GT). Lastly, we fractionate the training pairs of raw images and corresponding GT to realize the case w... | fraction = 2 # Fraction of annotated GT and raw image pairs to use during training.
random_seed = 1 # Seed to shuffle training data (annotated GT and raw image pairs).
assert 0 <fraction<= 100, "Fraction should be between 0 and 100"
mean, std = np.mean(train_images), np.std(train_images)
X_normalized = normalize(tr... | Training Data
..................
Raw image size after augmentation (608, 128, 128)
Mask size after augmentation (608, 128, 128)
Validation Data
..................
Raw image size after augmentation (5360, 128, 128)
Mask size after augmentation (5360, 128, 128)
| BSD-3-Clause | examples/DSB2018/U-Net_Finetune.ipynb | psteinb/VoidSeg |
Next, we do a one-hot encoding of training and validation labels for training a 3-class U-Net. One-hot encoding will extract three channels from each labelled image, where the channels correspond to background, foreground and border. | X = X[...,np.newaxis]
Y = convert_to_oneHot(Y_train_masks)
X_val = X_val[...,np.newaxis]
Y_val = convert_to_oneHot(Y_val_masks)
print(X.shape, Y.shape)
print(X_val.shape, Y_val.shape) | (608, 128, 128, 1) (608, 128, 128, 3)
(5360, 128, 128, 1) (5360, 128, 128, 3)
| BSD-3-Clause | examples/DSB2018/U-Net_Finetune.ipynb | psteinb/VoidSeg |
Let's look at one of our validation patches. | sl=0
plt.figure(figsize=(20,5))
plt.subplot(1,4,1)
plt.imshow(X_val[sl,...,0])
plt.title('Raw validation image')
plt.subplot(1,4,2)
plt.imshow(Y_val[sl,...,0])
plt.title('1-hot encoded background')
plt.subplot(1,4,3)
plt.imshow(Y_val[sl,...,1])
plt.title('1-hot encoded foreground')
plt.subplot(1,4,4)
plt.imshow(Y_val[s... | _____no_output_____ | BSD-3-Clause | examples/DSB2018/U-Net_Finetune.ipynb | psteinb/VoidSeg |
Configure Segmentation NetworkThe data preparation for segmentation is now done. Next, we configure a segmentation network by specifying `SegConfig` parameters. For example, one can increase `train_epochs` to get even better results at the expense of a longer computation. (This holds usually true for a large `fraction... | relative_weights = [1.0,1.0,5.0] # Relative weight of background, foreground and border class for training
config = SegConfig(X, unet_kern_size=3, relative_weights = relative_weights,
train_steps_per_epoch=400, train_epochs=3, batch_norm=True,
train_batch_size=128, unet_n_first =... | _____no_output_____ | BSD-3-Clause | examples/DSB2018/U-Net_Finetune.ipynb | psteinb/VoidSeg |
For finetuning, we initialize segmentation network with the best weights of the denoising N2V network trained above. | ft_layers = seg_model.keras_model.layers
n2v_layers = model.keras_model.layers
for i in range(0, len(n2v_layers)-2):
ft_layers[i].set_weights(n2v_layers[i].get_weights())
for l in seg_model.keras_model.layers:
l.trainable=True | _____no_output_____ | BSD-3-Clause | examples/DSB2018/U-Net_Finetune.ipynb | psteinb/VoidSeg |
Now, we begin training the model for segmentation. | seg_model.train(X, Y, (X_val, Y_val)) | Epoch 1/3
400/400 [==============================] - 152s 380ms/step - loss: 0.3040 - seg_crossentropy: 0.3040 - val_loss: 0.2867 - val_seg_crossentropy: 0.2867
Epoch 2/3
400/400 [==============================] - 143s 358ms/step - loss: 0.1202 - seg_crossentropy: 0.1202 - val_loss: 0.3895 - val_seg_crossentropy: 0.389... | BSD-3-Clause | examples/DSB2018/U-Net_Finetune.ipynb | psteinb/VoidSeg |
Computing the best threshold on validation images (to maximize Average Precision score). The threshold so obtained will be used to get hard masks from probability images to be predicted on test images. | threshold=seg_model.optimize_thresholds(X_val_normalized.astype(np.float32), val_masks) | Computing best threshold:
| BSD-3-Clause | examples/DSB2018/U-Net_Finetune.ipynb | psteinb/VoidSeg |
Prediction on test images to get segmentation result | predicted_images, precision_result=seg_model.predict_label_masks(X_test_normalized, test_masks, threshold)
print("Average precision over all test images at IOU = 0.5: ", precision_result)
plt.figure(figsize=(10,10))
plt.subplot(1,2,1)
plt.imshow(predicted_images[22])
plt.title('Prediction')
plt.subplot(1,2,2)
plt.imsho... | _____no_output_____ | BSD-3-Clause | examples/DSB2018/U-Net_Finetune.ipynb | psteinb/VoidSeg |
3 Maneras de Programar a una Red Neuronal - DOTCSV Código inicial | import numpy as np
import scipy as sc
import matplotlib.pyplot as plt
from sklearn.datasets import make_circles
# Creamos nuestros datos artificiales, donde buscaremos clasificar
# dos anillos concéntricos de datos.
X, Y = make_circles(n_samples=500, factor=0.5, noise=0.05)
# Resolución del mapa de predicción.
res... | _____no_output_____ | MIT | 2.3.1_3_Maneras_de_Programar_a_una_Red_Neuronal.ipynb | txusser/Master_IA_Sanidad |
Tensorflow | import tensorflow as tf
from matplotlib import animation
from IPython.core.display import display, HTML
# Definimos los puntos de entrada de la red, para la matriz X e Y.
iX = tf.placeholder('float', shape=[None, X.shape[1]])
iY = tf.placeholder('float', shape=[None])
lr = 0.01 # learning rate
nn = [2, 16,... | Step 0 / 1000 - Loss = 0.29063216 - Acc = 0.562
Step 25 / 1000 - Loss = 0.18204297 - Acc = 0.632
Step 50 / 1000 - Loss = 0.1471082 - Acc = 0.79
Step 75 / 1000 - Loss = 0.13354021 - Acc = 0.854
Step 100 / 1000 - Loss = 0.122594796 - Acc = 0.902
Step 125 / 1000 - Loss = 0.111153014 - Acc = 0.942
Step 150 / 1000 - L... | MIT | 2.3.1_3_Maneras_de_Programar_a_una_Red_Neuronal.ipynb | txusser/Master_IA_Sanidad |
Keras | import tensorflow as tf
import tensorflow.keras as kr
from IPython.core.display import display, HTML
lr = 0.01 # learning rate
nn = [2, 16, 8, 1] # número de neuronas por capa.
# Creamos el objeto que contendrá a nuestra red neuronal, como
# secuencia de capas.
model = kr.Sequential()
# Añadimos la cap... | Epoch 1/100
500/500 [==============================] - 0s 111us/sample - loss: 0.2468 - acc: 0.5040
Epoch 2/100
500/500 [==============================] - 0s 37us/sample - loss: 0.2457 - acc: 0.5100
Epoch 3/100
500/500 [==============================] - 0s 40us/sample - loss: 0.2446 - acc: 0.5040
Epoch 4/100
500/500 [=... | MIT | 2.3.1_3_Maneras_de_Programar_a_una_Red_Neuronal.ipynb | txusser/Master_IA_Sanidad |
Sklearn | import sklearn as sk
import sklearn.neural_network
from IPython.core.display import display, HTML
lr = 0.01 # learning rate
nn = [2, 16, 8, 1] # número de neuronas por capa.
# Creamos el objeto del modelo de red neuronal multicapa.
clf = sk.neural_network.MLPRegressor(solver='sgd',
... | Iteration 1, loss = 0.66391606
Iteration 2, loss = 0.29448667
Iteration 3, loss = 0.13429471
Iteration 4, loss = 0.13165037
Iteration 5, loss = 0.13430276
Iteration 6, loss = 0.12556423
Iteration 7, loss = 0.12292571
Iteration 8, loss = 0.12204933
Iteration 9, loss = 0.12175702
Iteration 10, loss = 0.12129750
Iteration... | MIT | 2.3.1_3_Maneras_de_Programar_a_una_Red_Neuronal.ipynb | txusser/Master_IA_Sanidad |
Arctic Project in Linear Regression: K-fold + Y:Area Import libraries | library(MASS)
library(tidyverse) | ── [1mAttaching packages[22m ──────────────────────────────────────────────────── tidyverse 1.3.0 ──
[32m✔[39m [34mggplot2[39m 3.3.2 [32m✔[39m [34mpurrr [39m 0.3.4
[32m✔[39m [34mtibble [39m 3.0.4 [32m✔[39m [34mdplyr [39m 1.0.2
[32m✔[39m [34mtidyr [39m 1.1.2 [32m✔[39m [34mstringr... | MIT | .ipynb_checkpoints/1-linear_regression_K-fold_area-checkpoint.ipynb | UCL-BENV0091-Antarctic/antarctic |
Load data | arctic <- read.csv("arctic_data.csv",stringsAsFactors = F) | _____no_output_____ | MIT | .ipynb_checkpoints/1-linear_regression_K-fold_area-checkpoint.ipynb | UCL-BENV0091-Antarctic/antarctic |
Data segmentation | folds <- cut(seq(1,nrow(arctic)), breaks = 10, labels = FALSE) | _____no_output_____ | MIT | .ipynb_checkpoints/1-linear_regression_K-fold_area-checkpoint.ipynb | UCL-BENV0091-Antarctic/antarctic |
Prediction | prediction <- as.data.frame(
sapply(1:10, FUN = function(i) # loop 1:K
{
testID <- which(folds == i, arr.ind = TRUE)
test <- arctic[testID, ]
train <- arctic[-testID, ] # set K-fold
# print(test) # if needed
# linear regression
model <- lm(area~rainfall+daylight+population+CO2+ozone+ocean_temp+land_... | _____no_output_____ | MIT | .ipynb_checkpoints/1-linear_regression_K-fold_area-checkpoint.ipynb | UCL-BENV0091-Antarctic/antarctic |
Table gathering and merging | pred_gather <- gather(data=prediction, key="fold",value="prediction",1:10)
result <- as.data.frame(cbind(arctic[,c(1,6)],pred_gather)) | _____no_output_____ | MIT | .ipynb_checkpoints/1-linear_regression_K-fold_area-checkpoint.ipynb | UCL-BENV0091-Antarctic/antarctic |
Calculate value of R^2 | result["R^2"] <- ((result$area-result$prediction)^2)
R_square <- sum(result$`R^2`)/490 | _____no_output_____ | MIT | .ipynb_checkpoints/1-linear_regression_K-fold_area-checkpoint.ipynb | UCL-BENV0091-Antarctic/antarctic |
Plot line chart (Prediction vs True) with title, legend, and specific size of figure | {plot(result$observation,result$area,type ='l',ylim = c(0,1.5),lwd = '2',xlab = "Date", ylab = "Value",xaxt='n')
lines(result$observation,result$prediction,lty=1,col='red',lwd = '2')
axis(1,at=c(1,61,121,181,241,301,361,421,481),
labels=c("Jan 1980","Jan 1985","Jan 1990","Jan 1995","Jan 2000","Jan 2005","Jan 201... | _____no_output_____ | MIT | .ipynb_checkpoints/1-linear_regression_K-fold_area-checkpoint.ipynb | UCL-BENV0091-Antarctic/antarctic |
Data extraction and Pairing of Insulin Inputs to Glucose Measurements in the ICU Interactive notebook: Part IIAuthors: [Aldo Robles Arévalo](mailto:aldo.arevalo@tecnico.ulisboa.pt); Jason Maley; Lawrence Baker; Susana M. da Silva Vieira; João M. da Costa Sousa; Stan Finkelstein; Jesse D. Raffa; Roselyn Cristelle; Leo... | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib.colors as colors
from scipy import stats
from datetime import datetime
import time
import warnings
# Below imports are used to print out pretty pandas dataframes
from IPython.display import display, HTML
# I... | _____no_output_____ | MIT | notebooks/ICUglycemia/Notebooks/2_0_ara_pairing_II.ipynb | aldo-arevalo/mimic-code |
Adjusted datasets* **Note 1**: Substitute `your_dataset` with the name of your dataset ID (Line 850) where you hosted/stored the tables created in the `1.0-ara-pairing-I.ipynb` notebook. * **Note 2**: The table `glucose_insulin_ICU` was created in `1.0-ara-pairing-I.ipynb` notebook. It is equivalent to `glucose_insuli... | # Import dataset adjusted or aligned
projectid = "YOUR_PROJECT_ID" # <-- Add your project ID
query ="""
WITH pg AS(
SELECT p1.*
-- Column GLC_AL that would gather paired glucose values according to the proposed rules
,(CASE
-- 1ST CLAUSE
-- When previous and following rows are glucose read... | _____no_output_____ | MIT | notebooks/ICUglycemia/Notebooks/2_0_ara_pairing_II.ipynb | aldo-arevalo/mimic-code |
Boluses of short-acting insulin | # Filtering for only short insulin boluses and all sources of glucose
short_BOL_adjusted = ICUinputs_adjusted[
(ICUinputs_adjusted['INSULINTYPE']=="Short") &
(ICUinputs_adjusted['EVENT'].str.contains('BOLUS'))].copy()
# Get statistics
display(HTML('<h5>Contains the following information</h5>'))
print(... | _____no_output_____ | MIT | notebooks/ICUglycemia/Notebooks/2_0_ara_pairing_II.ipynb | aldo-arevalo/mimic-code |
Infusions of short-acting insulin | warnings.simplefilter('default')
# Filtering for only short insulin infusions and all sources of glucose
short_INF_adjusted = ICUinputs_adjusted[
(ICUinputs_adjusted['INSULINTYPE']=="Short") &
(ICUinputs_adjusted['EVENT'].str.contains('INFUSION'))].copy()
# Get statistics
display(HTML('<h5>Counts</h5... | _____no_output_____ | MIT | notebooks/ICUglycemia/Notebooks/2_0_ara_pairing_II.ipynb | aldo-arevalo/mimic-code |
Boluses of intermediate-acting insulin | warnings.simplefilter('default')
# Filtering for only short insulin infusions and all sources of glucose
inter_BOL_adjusted = ICUinputs_adjusted[
(ICUinputs_adjusted['INSULINTYPE']=="Intermediate") &
(ICUinputs_adjusted['EVENT'].str.contains('BOLUS'))].copy()
# Get statistics
display(HTML('<h5>Contai... | _____no_output_____ | MIT | notebooks/ICUglycemia/Notebooks/2_0_ara_pairing_II.ipynb | aldo-arevalo/mimic-code |
Boluses of long-acting insulin | warnings.simplefilter('default')
# Filtering for only short insulin infusions and all sources of glucose
long_BOL_adjusted = ICUinputs_adjusted[
(ICUinputs_adjusted['INSULINTYPE']=="Long") &
(ICUinputs_adjusted['EVENT'].str.contains('BOLUS'))].copy()
# Get statistics
display(HTML('<h5>Contains the fo... | _____no_output_____ | MIT | notebooks/ICUglycemia/Notebooks/2_0_ara_pairing_II.ipynb | aldo-arevalo/mimic-code |
Non-adjusted datasetsTo complement this analysis, and to show the difference between implementing and not implementing the proposed rules, three cohorts were created: a) no pairing rules applied, b) paired a glucose reading recorded within 60 minutes of the insulin event instead of 90 minutes, and c) pairing a glucose... | # GLUCOSE READINGS CURATED AND INSULIN INPUTS CURATED but no RULES
query = """
SELECT pg.*
, (CASE
WHEN pg.GLCSOURCE_AL IS null
AND (LEAD(pg.GLCTIMER_AL,1) OVER(PARTITION BY pg.ICUSTAY_ID ORDER BY pg.TIMER) = pg.GLCTIMER)
THEN 1
WHEN pg.GLCSOURC... | /usr/lib/python3.6/json/decoder.py:355: ResourceWarning: unclosed <ssl.SSLSocket fd=63, family=AddressFamily.AF_INET, type=2049, proto=6, laddr=('172.28.0.2', 52706), raddr=('74.125.142.95', 443)>
obj, end = self.scan_once(s, idx)
/usr/lib/python3.6/json/decoder.py:355: ResourceWarning: unclosed <ssl.SSLSocket fd=64,... | MIT | notebooks/ICUglycemia/Notebooks/2_0_ara_pairing_II.ipynb | aldo-arevalo/mimic-code |
Scenario BGlucose reading CURATED and inulin inputs CURATED paired with rules (60 min)* **Note 1**: Substitute `your_dataset` with the name of your dataset ID (Line 849) where you hosted/stored the tables created in the `1.0-ara-pairing-I.ipynb` notebook. * **Note 2**: The table `glucose_insulin_ICU` was created in `1... | # Import dataset adjusted or aligned with 60 min
query ="""
WITH pg AS(
SELECT p1.*
-- Column GLC_AL that would gather paired glucose values according to the proposed rules
,(CASE
-- 1ST CLAUSE
-- When previous and following rows are glucose readings, select the glucose value that
... | /usr/lib/python3.6/json/decoder.py:355: ResourceWarning: unclosed <ssl.SSLSocket fd=80, family=AddressFamily.AF_INET, type=2049, proto=6, laddr=('172.28.0.2', 52770), raddr=('74.125.20.95', 443)>
obj, end = self.scan_once(s, idx)
/usr/lib/python3.6/json/decoder.py:355: ResourceWarning: unclosed <ssl.SSLSocket fd=79, ... | MIT | notebooks/ICUglycemia/Notebooks/2_0_ara_pairing_II.ipynb | aldo-arevalo/mimic-code |
Boluses of short-acting insulin | # Filtering for only short insulin boluses and all sources of glucose
short_BOL_60 = ICU60min_adjusted[(ICU60min_adjusted['INSULINTYPE']=="Short") &
(ICU60min_adjusted['EVENT'].str.contains('BOLUS'))].copy()
# Get statistics
display(HTML('<h5>Contains the following information</h5>'))... | _____no_output_____ | MIT | notebooks/ICUglycemia/Notebooks/2_0_ara_pairing_II.ipynb | aldo-arevalo/mimic-code |
Loops and Conditions loops provides the methods of iteration while condition allows or blocks the code execution when specified conditionis meet. For Loop and while Loop | L = ['apple', 'banana','kite','cellphone']
for item in L:
print(item)
range(5), range(5,100), sum(range(100))
L=[]
for k in range(10):
L.append(10*k)
L
D = {}
for i in range(5):
for j in range(5):
if i == j :
D.update({(i,j) : 10*i+j})
elif i!=j :
D.update({(i,j): 100... | _____no_output_____ | MIT | loop.ipynb | dineshyadav2020/P_W_Files |
Copyright 2019 The TensorFlow Authors. | #@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under... | _____no_output_____ | Apache-2.0 | community/en/transformer_chatbot.ipynb | xuekun90/examples |
Transformer Chatbot Run in Google Colab View source on GitHub This tutorial trains a Transformer model to be a chatbot. This is an advanced example that assumes knowledge of [text generation](https://tensorflow.org/alpha/tutorials/text/text_generation), [attention](https://www.tensorflow.org/alpha/tutor... | from __future__ import absolute_import, division, print_function, unicode_literals
try:
# The %tensorflow_version magic only works in colab.
%tensorflow_version 2.x
except Exception:
pass
import tensorflow as tf
tf.random.set_seed(1234)
!pip install tfds-nightly
import tensorflow_datasets as tfds
import os
imp... | Collecting tf-nightly-gpu-2.0-preview==2.0.0.dev20190520
[?25l Downloading https://files.pythonhosted.org/packages/c9/c1/fcaf4f6873777da2cd3a7a8ac3c9648cef7c7413f13b8135521eb9b9804a/tf_nightly_gpu_2.0_preview-2.0.0.dev20190520-cp36-cp36m-manylinux1_x86_64.whl (349.0MB)
[K |████████████████████████████████| 349.0... | Apache-2.0 | community/en/transformer_chatbot.ipynb | xuekun90/examples |
Prepare Dataset We will use the conversations in movies and TV shows provided by [Cornell Movie-Dialogs Corpus](https://www.cs.cornell.edu/~cristian/Cornell_Movie-Dialogs_Corpus.html), which contains more than 220 thousands conversational exchanges between more than 10k pairs of movie characters, as our dataset.`movie_... | path_to_zip = tf.keras.utils.get_file(
'cornell_movie_dialogs.zip',
origin=
'http://www.cs.cornell.edu/~cristian/data/cornell_movie_dialogs_corpus.zip',
extract=True)
path_to_dataset = os.path.join(
os.path.dirname(path_to_zip), "cornell movie-dialogs corpus")
path_to_movie_lines = os.path.join(pa... | Downloading data from http://www.cs.cornell.edu/~cristian/data/cornell_movie_dialogs_corpus.zip
9920512/9916637 [==============================] - 1s 0us/step
| Apache-2.0 | community/en/transformer_chatbot.ipynb | xuekun90/examples |
Load and preprocess dataTo keep this example simple and fast, we are limiting the maximum number of training samples to`MAX_SAMPLES=25000` and the maximum length of the sentence to be `MAX_LENGTH=40`.We preprocess our dataset in the following order:* Extract `MAX_SAMPLES` conversation pairs into list of `questions` an... | # Maximum number of samples to preprocess
MAX_SAMPLES = 50000
def preprocess_sentence(sentence):
sentence = sentence.lower().strip()
# creating a space between a word and the punctuation following it
# eg: "he is a boy." => "he is a boy ."
sentence = re.sub(r"([?.!,])", r" \1 ", sentence)
sentence = re.sub(r... | Vocab size: 8333
Number of samples: 44095
| Apache-2.0 | community/en/transformer_chatbot.ipynb | xuekun90/examples |
Create `tf.data.Dataset`We are going to use the [tf.data.Dataset API](https://www.tensorflow.org/api_docs/python/tf/data) to contruct our input pipline in order to utilize features like caching and prefetching to speed up the training process.The transformer is an auto-regressive model: it makes predictions one part a... | BATCH_SIZE = 64
BUFFER_SIZE = 20000
# decoder inputs use the previous target as input
# remove START_TOKEN from targets
dataset = tf.data.Dataset.from_tensor_slices((
{
'inputs': questions,
'dec_inputs': answers[:, :-1]
},
{
'outputs': answers[:, 1:]
},
))
dataset = dataset.cac... | <PrefetchDataset shapes: ({inputs: (None, 40), dec_inputs: (None, 39)}, {outputs: (None, 39)}), types: ({inputs: tf.int32, dec_inputs: tf.int32}, {outputs: tf.int32})>
| Apache-2.0 | community/en/transformer_chatbot.ipynb | xuekun90/examples |
Attention Scaled dot product AttentionThe scaled dot-product attention function used by the transformer takes three inputs: Q (query), K (key), V (value). The equation used to calculate the attention weights is:$$\Large{Attention(Q, K, V) = softmax_k(\frac{QK^T}{\sqrt{d_k}}) V} $$As the softmax normalization is done ... | def scaled_dot_product_attention(query, key, value, mask):
"""Calculate the attention weights. """
matmul_qk = tf.matmul(query, key, transpose_b=True)
# scale matmul_qk
depth = tf.cast(tf.shape(key)[-1], tf.float32)
logits = matmul_qk / tf.math.sqrt(depth)
# add the mask to zero out padding tokens
if ma... | _____no_output_____ | Apache-2.0 | community/en/transformer_chatbot.ipynb | xuekun90/examples |
Multi-head attentionMulti-head attention consists of four parts:* Linear layers and split into heads.* Scaled dot-product attention.* Concatenation of heads.* Final linear layer.Each multi-head attention block gets three inputs; Q (query), K (key), V (value). These are put through linear (Dense) layers and split up in... | class MultiHeadAttention(tf.keras.layers.Layer):
def __init__(self, d_model, num_heads, name="multi_head_attention"):
super(MultiHeadAttention, self).__init__(name=name)
self.num_heads = num_heads
self.d_model = d_model
assert d_model % self.num_heads == 0
self.depth = d_model // self.num_heads... | _____no_output_____ | Apache-2.0 | community/en/transformer_chatbot.ipynb | xuekun90/examples |
Transformer Masking `create_padding_mask` and `create_look_ahead` are helper functions to creating masks to mask out padded tokens, we are going to use these helper functions as `tf.keras.layers.Lambda` layers.Mask all the pad tokens (value `0`) in the batch to ensure the model does not treat padding as input. | def create_padding_mask(x):
mask = tf.cast(tf.math.equal(x, 0), tf.float32)
# (batch_size, 1, 1, sequence length)
return mask[:, tf.newaxis, tf.newaxis, :]
print(create_padding_mask(tf.constant([[1, 2, 0, 3, 0], [0, 0, 0, 4, 5]]))) | tf.Tensor(
[[[[0. 0. 1. 0. 1.]]]
[[[1. 1. 1. 0. 0.]]]], shape=(2, 1, 1, 5), dtype=float32)
| Apache-2.0 | community/en/transformer_chatbot.ipynb | xuekun90/examples |
Look-ahead mask to mask the future tokens in a sequence.We also mask out pad tokens.i.e. To predict the third word, only the first and second word will be used | def create_look_ahead_mask(x):
seq_len = tf.shape(x)[1]
look_ahead_mask = 1 - tf.linalg.band_part(tf.ones((seq_len, seq_len)), -1, 0)
padding_mask = create_padding_mask(x)
return tf.maximum(look_ahead_mask, padding_mask)
print(create_look_ahead_mask(tf.constant([[1, 2, 0, 4, 5]]))) | tf.Tensor(
[[[[0. 1. 1. 1. 1.]
[0. 0. 1. 1. 1.]
[0. 0. 1. 1. 1.]
[0. 0. 1. 0. 1.]
[0. 0. 1. 0. 0.]]]], shape=(1, 1, 5, 5), dtype=float32)
| Apache-2.0 | community/en/transformer_chatbot.ipynb | xuekun90/examples |
Positional encodingSince this model doesn't contain any recurrence or convolution, positional encoding is added to give the model some information about the relative position of the words in the sentence. The positional encoding vector is added to the embedding vector. Embeddings represent a token in a d-dimensional s... | class PositionalEncoding(tf.keras.layers.Layer):
def __init__(self, position, d_model):
super(PositionalEncoding, self).__init__()
self.pos_encoding = self.positional_encoding(position, d_model)
def get_angles(self, position, i, d_model):
angles = 1 / tf.pow(10000, (2 * (i // 2)) / tf.cast(d_model, tf... | _____no_output_____ | Apache-2.0 | community/en/transformer_chatbot.ipynb | xuekun90/examples |
Encoder LayerEach encoder layer consists of sublayers:1. Multi-head attention (with padding mask) 2. 2 dense layers followed by dropoutEach of these sublayers has a residual connection around it followed by a layer normalization. Residual connections help in avoiding the vanishing gradient problem in deep networks.The... | def encoder_layer(units, d_model, num_heads, dropout, name="encoder_layer"):
inputs = tf.keras.Input(shape=(None, d_model), name="inputs")
padding_mask = tf.keras.Input(shape=(1, 1, None), name="padding_mask")
attention = MultiHeadAttention(
d_model, num_heads, name="attention")({
'query': inputs... | _____no_output_____ | Apache-2.0 | community/en/transformer_chatbot.ipynb | xuekun90/examples |
EncoderThe Encoder consists of:1. Input Embedding2. Positional Encoding3. `num_layers` encoder layersThe input is put through an embedding which is summed with the positional encoding. The output of this summation is the input to the encoder layers. The output of the encoder is the input to the decoder. | def encoder(vocab_size,
num_layers,
units,
d_model,
num_heads,
dropout,
name="encoder"):
inputs = tf.keras.Input(shape=(None,), name="inputs")
padding_mask = tf.keras.Input(shape=(1, 1, None), name="padding_mask")
embeddings = tf.keras.layer... | _____no_output_____ | Apache-2.0 | community/en/transformer_chatbot.ipynb | xuekun90/examples |
Decoder LayerEach decoder layer consists of sublayers:1. Masked multi-head attention (with look ahead mask and padding mask)2. Multi-head attention (with padding mask). `value` and `key` receive the *encoder output* as inputs. `query` receives the *output from the masked multi-head attention sublayer.*3. 2 dense... | def decoder_layer(units, d_model, num_heads, dropout, name="decoder_layer"):
inputs = tf.keras.Input(shape=(None, d_model), name="inputs")
enc_outputs = tf.keras.Input(shape=(None, d_model), name="encoder_outputs")
look_ahead_mask = tf.keras.Input(
shape=(1, None, None), name="look_ahead_mask")
padding_ma... | _____no_output_____ | Apache-2.0 | community/en/transformer_chatbot.ipynb | xuekun90/examples |
DecoderThe Decoder consists of:1. Output Embedding2. Positional Encoding3. N decoder layersThe target is put through an embedding which is summed with the positional encoding. The output of this summation is the input to the decoder layers. The output of the decoder is the input to the final linear layer. | def decoder(vocab_size,
num_layers,
units,
d_model,
num_heads,
dropout,
name='decoder'):
inputs = tf.keras.Input(shape=(None,), name='inputs')
enc_outputs = tf.keras.Input(shape=(None, d_model), name='encoder_outputs')
look_ahead_mask = tf.ke... | _____no_output_____ | Apache-2.0 | community/en/transformer_chatbot.ipynb | xuekun90/examples |
TransformerTransformer consists of the encoder, decoder and a final linear layer. The output of the decoder is the input to the linear layer and its output is returned. | def transformer(vocab_size,
num_layers,
units,
d_model,
num_heads,
dropout,
name="transformer"):
inputs = tf.keras.Input(shape=(None,), name="inputs")
dec_inputs = tf.keras.Input(shape=(None,), name="dec_inputs")
enc_... | _____no_output_____ | Apache-2.0 | community/en/transformer_chatbot.ipynb | xuekun90/examples |
Train model Initialize modelTo keep this example small and relatively fast, the values for *num_layers, d_model, and units* have been reduced. See the [paper](https://arxiv.org/abs/1706.03762) for all the other versions of the transformer. | tf.keras.backend.clear_session()
# Hyper-parameters
NUM_LAYERS = 2
D_MODEL = 256
NUM_HEADS = 8
UNITS = 512
DROPOUT = 0.1
model = transformer(
vocab_size=VOCAB_SIZE,
num_layers=NUM_LAYERS,
units=UNITS,
d_model=D_MODEL,
num_heads=NUM_HEADS,
dropout=DROPOUT) | _____no_output_____ | Apache-2.0 | community/en/transformer_chatbot.ipynb | xuekun90/examples |
Loss functionSince the target sequences are padded, it is important to apply a padding mask when calculating the loss. | def loss_function(y_true, y_pred):
y_true = tf.reshape(y_true, shape=(-1, MAX_LENGTH - 1))
loss = tf.keras.losses.SparseCategoricalCrossentropy(
from_logits=True, reduction='none')(y_true, y_pred)
mask = tf.cast(tf.not_equal(y_true, 0), tf.float32)
loss = tf.multiply(loss, mask)
return tf.reduce_me... | _____no_output_____ | Apache-2.0 | community/en/transformer_chatbot.ipynb | xuekun90/examples |
Custom learning rateUse the Adam optimizer with a custom learning rate scheduler according to the formula in the [paper](https://arxiv.org/abs/1706.03762).$$\Large{lrate = d_{model}^{-0.5} * min(step{\_}num^{-0.5}, step{\_}num * warmup{\_}steps^{-1.5})}$$ | class CustomSchedule(tf.keras.optimizers.schedules.LearningRateSchedule):
def __init__(self, d_model, warmup_steps=4000):
super(CustomSchedule, self).__init__()
self.d_model = d_model
self.d_model = tf.cast(self.d_model, tf.float32)
self.warmup_steps = warmup_steps
def __call__(self, step):
... | _____no_output_____ | Apache-2.0 | community/en/transformer_chatbot.ipynb | xuekun90/examples |
Compile Model | learning_rate = CustomSchedule(D_MODEL)
optimizer = tf.keras.optimizers.Adam(
learning_rate, beta_1=0.9, beta_2=0.98, epsilon=1e-9)
def accuracy(y_true, y_pred):
# ensure labels have shape (batch_size, MAX_LENGTH - 1)
y_true = tf.reshape(y_true, shape=(-1, MAX_LENGTH - 1))
accuracy = tf.metrics.SparseCatego... | _____no_output_____ | Apache-2.0 | community/en/transformer_chatbot.ipynb | xuekun90/examples |
Fit modelTrain our transformer by simply calling `model.fit()` | EPOCHS = 20
model.fit(dataset, epochs=EPOCHS) | Epoch 1/20
689/689 [==============================] - 97s 141ms/step - loss: 2.1146 - accuracy: 0.0249
Epoch 2/20
689/689 [==============================] - 81s 118ms/step - loss: 1.5008 - accuracy: 0.0530
Epoch 3/20
689/689 [==============================] - 82s 119ms/step - loss: 1.3940 - accuracy: 0.0653
Epoch 4/20
... | Apache-2.0 | community/en/transformer_chatbot.ipynb | xuekun90/examples |
Evaluate and predictThe following steps are used for evaluation:* Apply the same preprocessing method we used to create our dataset for the input sentence.* Tokenize the input sentence and add `START_TOKEN` and `END_TOKEN`. * Calculate the padding masks and the look ahead masks.* The decoder then outputs the predictio... | def evaluate(sentence):
sentence = preprocess_sentence(sentence)
sentence = tf.expand_dims(
START_TOKEN + tokenizer.encode(sentence) + END_TOKEN, axis=0)
output = tf.expand_dims(START_TOKEN, 0)
for i in range(MAX_LENGTH):
predictions = model(inputs=[sentence, output], training=False)
# select ... | _____no_output_____ | Apache-2.0 | community/en/transformer_chatbot.ipynb | xuekun90/examples |
Let's test our model! | output = predict('Where have you been?')
output = predict("It's a trap")
# feed the model with its previous output
sentence = 'I am not crazy, my mother had me tested.'
for _ in range(5):
sentence = predict(sentence)
print('') | Input: I am not crazy, my mother had me tested.
Output: you re a good man , roy . that s a good man , roy , you re a little girl , that s a good man . you re a little girl .
Input: you re a good man , roy . that s a good man , roy , you re a little girl , that s a good man . you re a little girl .
Output: i m glad you... | Apache-2.0 | community/en/transformer_chatbot.ipynb | xuekun90/examples |
Copyright 2020 The TensorFlow Authors. | #@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under... | _____no_output_____ | Apache-2.0 | docs/tutorials/gradients.ipynb | HectorIGH/quantum |
Calculate gradients View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook This tutorial explores gradient calculation algorithms for the expectation values of quantum circuits.Calculating the gradient of the expectation value of a certain observable in a quantu... | !pip install tensorflow==2.3.1 | _____no_output_____ | Apache-2.0 | docs/tutorials/gradients.ipynb | HectorIGH/quantum |
Install TensorFlow Quantum: | !pip install tensorflow-quantum | _____no_output_____ | Apache-2.0 | docs/tutorials/gradients.ipynb | HectorIGH/quantum |
Now import TensorFlow and the module dependencies: | import tensorflow as tf
import tensorflow_quantum as tfq
import cirq
import sympy
import numpy as np
# visualization tools
%matplotlib inline
import matplotlib.pyplot as plt
from cirq.contrib.svg import SVGCircuit | _____no_output_____ | Apache-2.0 | docs/tutorials/gradients.ipynb | HectorIGH/quantum |
1. PreliminaryLet's make the notion of gradient calculation for quantum circuits a little more concrete. Suppose you have a parameterized circuit like this one: | qubit = cirq.GridQubit(0, 0)
my_circuit = cirq.Circuit(cirq.Y(qubit)**sympy.Symbol('alpha'))
SVGCircuit(my_circuit) | _____no_output_____ | Apache-2.0 | docs/tutorials/gradients.ipynb | HectorIGH/quantum |
Along with an observable: | pauli_x = cirq.X(qubit)
pauli_x | _____no_output_____ | Apache-2.0 | docs/tutorials/gradients.ipynb | HectorIGH/quantum |
Looking at this operator you know that $⟨Y(\alpha)| X | Y(\alpha)⟩ = \sin(\pi \alpha)$ | def my_expectation(op, alpha):
"""Compute ⟨Y(alpha)| `op` | Y(alpha)⟩"""
params = {'alpha': alpha}
sim = cirq.Simulator()
final_state_vector = sim.simulate(my_circuit, params).final_state_vector
return op.expectation_from_state_vector(final_state_vector, {qubit: 0}).real
my_alpha = 0.3
print("Expe... | _____no_output_____ | Apache-2.0 | docs/tutorials/gradients.ipynb | HectorIGH/quantum |
and if you define $f_{1}(\alpha) = ⟨Y(\alpha)| X | Y(\alpha)⟩$ then $f_{1}^{'}(\alpha) = \pi \cos(\pi \alpha)$. Let's check this: | def my_grad(obs, alpha, eps=0.01):
grad = 0
f_x = my_expectation(obs, alpha)
f_x_prime = my_expectation(obs, alpha + eps)
return ((f_x_prime - f_x) / eps).real
print('Finite difference:', my_grad(pauli_x, my_alpha))
print('Cosine formula: ', np.pi * np.cos(np.pi * my_alpha)) | _____no_output_____ | Apache-2.0 | docs/tutorials/gradients.ipynb | HectorIGH/quantum |
2. The need for a differentiatorWith larger circuits, you won't always be so lucky to have a formula that precisely calculates the gradients of a given quantum circuit. In the event that a simple formula isn't enough to calculate the gradient, the `tfq.differentiators.Differentiator` class allows you to define algorit... | expectation_calculation = tfq.layers.Expectation(
differentiator=tfq.differentiators.ForwardDifference(grid_spacing=0.01))
expectation_calculation(my_circuit,
operators=pauli_x,
symbol_names=['alpha'],
symbol_values=[[my_alpha]]) | _____no_output_____ | Apache-2.0 | docs/tutorials/gradients.ipynb | HectorIGH/quantum |
However, if you switch to estimating expectation based on sampling (what would happen on a true device) the values can change a little bit. This means you now have an imperfect estimate: | sampled_expectation_calculation = tfq.layers.SampledExpectation(
differentiator=tfq.differentiators.ForwardDifference(grid_spacing=0.01))
sampled_expectation_calculation(my_circuit,
operators=pauli_x,
repetitions=500,
s... | _____no_output_____ | Apache-2.0 | docs/tutorials/gradients.ipynb | HectorIGH/quantum |
This can quickly compound into a serious accuracy problem when it comes to gradients: | # Make input_points = [batch_size, 1] array.
input_points = np.linspace(0, 5, 200)[:, np.newaxis].astype(np.float32)
exact_outputs = expectation_calculation(my_circuit,
operators=pauli_x,
symbol_names=['alpha'],
... | _____no_output_____ | Apache-2.0 | docs/tutorials/gradients.ipynb | HectorIGH/quantum |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.