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 |
|---|---|---|---|---|---|
Pytorch backend - Only the import changes | #Change gluon_prototype to pytorch_prototype
from monk.pytorch_prototype import prototype
gtf = prototype(verbose=1);
gtf.Prototype("sample-project-1", "sample-experiment-1");
network = [];
# Single line addition of blocks
network.append(gtf.resnet_v2_bottleneck_block(output_channels=64, downsample=False));
gtf.... | Pytorch Version: 1.2.0
Experiment Details
Project: sample-project-1
Experiment: sample-experiment-1
Dir: /home/abhi/Desktop/Work/tess_tool/gui/v0.3/finetune_models/Organization/development/v5.0_blocks/study_roadmap/blocks/workspace/sample-project-1/sample-experiment-1/
Model Details
Loading pretrained... | Apache-2.0 | study_roadmaps/3_image_processing_deep_learning_roadmap/3_deep_learning_advanced/1_Blocks in Deep Learning Networks/8) Resnet V2 Bottleneck Block (Type - 2).ipynb | take2rohit/monk_v1 |
Keras backend - Only the import changes | #Change gluon_prototype to keras_prototype
from monk.keras_prototype import prototype
gtf = prototype(verbose=1);
gtf.Prototype("sample-project-1", "sample-experiment-1");
network = [];
# Single line addition of blocks
network.append(gtf.resnet_v2_bottleneck_block(output_channels=64, downsample=False));
gtf.Comp... | Keras Version: 2.2.5
Tensorflow Version: 1.12.0
Experiment Details
Project: sample-project-1
Experiment: sample-experiment-1
Dir: /home/abhi/Desktop/Work/tess_tool/gui/v0.3/finetune_models/Organization/development/v5.0_blocks/study_roadmap/blocks/workspace/sample-project-1/sample-experiment-1/
Model Detai... | Apache-2.0 | study_roadmaps/3_image_processing_deep_learning_roadmap/3_deep_learning_advanced/1_Blocks in Deep Learning Networks/8) Resnet V2 Bottleneck Block (Type - 2).ipynb | take2rohit/monk_v1 |
Appendix Study links - https://towardsdatascience.com/residual-blocks-building-blocks-of-resnet-fd90ca15d6ec - https://medium.com/@MaheshNKhatri/resnet-block-explanation-with-a-terminology-deep-dive-989e15e3d691 - https://medium.com/analytics-vidhya/understanding-and-implementation-of-residual-networks-resnets-b80... | # Traditional-Mxnet-gluon
import mxnet as mx
from mxnet.gluon import nn
from mxnet.gluon.nn import HybridBlock, BatchNorm
from mxnet.gluon.contrib.nn import HybridConcurrent, Identity
from mxnet import gluon, init, nd
def _conv3x3(channels, stride, in_channels):
return nn.Conv2D(channels, kernel_size=3, strides=st... | (1, 64, 224, 224) (1, 64, 224, 224)
Serving 'final-symbol.json' at http://localhost:8082
| Apache-2.0 | study_roadmaps/3_image_processing_deep_learning_roadmap/3_deep_learning_advanced/1_Blocks in Deep Learning Networks/8) Resnet V2 Bottleneck Block (Type - 2).ipynb | take2rohit/monk_v1 |
Creating block using traditional Pytorch - Code credits - https://pytorch.org/ | # Traiditional-Pytorch
import torch
from torch import nn
from torch.jit.annotations import List
import torch.nn.functional as F
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
... | torch.Size([1, 64, 224, 224]) torch.Size([1, 64, 224, 224])
Serving 'model.onnx' at http://localhost:9998
| Apache-2.0 | study_roadmaps/3_image_processing_deep_learning_roadmap/3_deep_learning_advanced/1_Blocks in Deep Learning Networks/8) Resnet V2 Bottleneck Block (Type - 2).ipynb | take2rohit/monk_v1 |
Creating block using traditional Keras - Code credits: https://keras.io/ | # Traditional-Keras
import keras
import keras.layers as kla
import keras.models as kmo
import tensorflow as tf
from keras.models import Model
backend = 'channels_last'
from keras import layers
def resnet_conv_block(input_tensor,
kernel_size,
filters,
stage,
bl... | (1, 224, 224, 64) (1, 224, 224, 64)
Stopping http://localhost:8082
Serving 'final.h5' at http://localhost:8082
| Apache-2.0 | study_roadmaps/3_image_processing_deep_learning_roadmap/3_deep_learning_advanced/1_Blocks in Deep Learning Networks/8) Resnet V2 Bottleneck Block (Type - 2).ipynb | take2rohit/monk_v1 |
from google.colab import drive
drive.mount('/content/drive')
import tensorflow as tf
import numpy as np
from tensorflow import keras
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Dense
from tensorflow.keras.layers import Flatten, Dropout
from tensorflow.keras.applications.resnet import p... | _____no_output_____ | MIT | RocksResnetTrainer.ipynb | malcolmrite-dsi/RockVideoClassifier | |
Training | train_datagen = keras.preprocessing.image.ImageDataGenerator(validation_split=0.2, preprocessing_function=preprocess_input)
train_generator = train_datagen.flow_from_directory(
'/content/drive/My Drive/Module 2 shared folder/samples',
subset="training",
seed=3,
target_size=(64, 64),
... | _____no_output_____ | MIT | RocksResnetTrainer.ipynb | malcolmrite-dsi/RockVideoClassifier |
02 - AC SAF GOME-2 - Produce gridded dataset (L3)>> Optional: Introduction to Python and Project Jupyter Project Jupyter "Project Jupyter exists to develop open-source software, open-standards, and services for interactive computing across dozens of programming languages." Project Jupyter offers different tools ... | jupyter notebook | _____no_output_____ | MIT | 90_workshops/202012_EUM_short_course_gridded_dataset/01_introduction_to_python_and_jupyter.ipynb | trivedi-c/atm_Practical3 |
Installing Jupyter with pip Experienced Python users may want to install Jupyter using Python's package manager `pip`.With `Python3` you do: | python3 -m pip install --upgrade pip
python3 -m pip install jupyter | _____no_output_____ | MIT | 90_workshops/202012_EUM_short_course_gridded_dataset/01_introduction_to_python_and_jupyter.ipynb | trivedi-c/atm_Practical3 |
In order to run the notebook, you run the same command as with Anaconda at the Terminal : | jupyter notebook | _____no_output_____ | MIT | 90_workshops/202012_EUM_short_course_gridded_dataset/01_introduction_to_python_and_jupyter.ipynb | trivedi-c/atm_Practical3 |
Jupyter notebooks UI * Notebook dashboard * Create new notebook* Notebook editor (UI) * Menu * Toolbar * Notebook area and cells* Cell types * Code * Markdown* Edit (green) vs. Command mode (blue) Notebook editor User Interface (UI) Shortcuts Get an overview of the shortcuts by hitting `H` or go to `Help/Keyboard... | %lsmagic | _____no_output_____ | MIT | 90_workshops/202012_EUM_short_course_gridded_dataset/01_introduction_to_python_and_jupyter.ipynb | trivedi-c/atm_Practical3 |
**See and set environment variables** | %env | _____no_output_____ | MIT | 90_workshops/202012_EUM_short_course_gridded_dataset/01_introduction_to_python_and_jupyter.ipynb | trivedi-c/atm_Practical3 |
**Install and list libraries** | !pip install numpy
!pip list | grep pandas | _____no_output_____ | MIT | 90_workshops/202012_EUM_short_course_gridded_dataset/01_introduction_to_python_and_jupyter.ipynb | trivedi-c/atm_Practical3 |
**Write cell content to a Python file** | %%writefile hello_world.py
print('Hello World') | _____no_output_____ | MIT | 90_workshops/202012_EUM_short_course_gridded_dataset/01_introduction_to_python_and_jupyter.ipynb | trivedi-c/atm_Practical3 |
**Load a Python file** | %pycat hello_world.py | _____no_output_____ | MIT | 90_workshops/202012_EUM_short_course_gridded_dataset/01_introduction_to_python_and_jupyter.ipynb | trivedi-c/atm_Practical3 |
**Get the time of cell execution** | %%time
tmpList = []
for i in range(100):
tmpList.append(i+i)
print(tmpList) | _____no_output_____ | MIT | 90_workshops/202012_EUM_short_course_gridded_dataset/01_introduction_to_python_and_jupyter.ipynb | trivedi-c/atm_Practical3 |
**Show matplotlib plots inline** | %matplotlib inline | _____no_output_____ | MIT | 90_workshops/202012_EUM_short_course_gridded_dataset/01_introduction_to_python_and_jupyter.ipynb | trivedi-c/atm_Practical3 |
Adding functionality so we can create dataframe from string representation of dict | import ast
def str_to_dict(string):
return ast.literal_eval(string)
import pandas as pd
class MySubClass(pd.DataFrame):
def from_str(self, string):
df_obj = super().from_dict(str_to_dict(string))
df_obj.my_string_attribute = string
return df_obj
data = "{'col_1' : ['a','b'], 'col2': [1,... | _____no_output_____ | MIT | 6_a_extending_dataframe_capabilities.ipynb | mj111312/pandas_basics |
[Ateliers: Technologies des grosses données](https://github.com/wikistat/Ateliers-Big-Data) Recommandation de Films par Filtrage Collaboratif: [NMF](http://wikistat.fr/pdf/st-m-explo-nmf.pdf) de la librairie [SparkML](https://spark.apache.org/docs/latest/ml-guide.html) de 1. IntroductionCe calepin traite d'un pr... | sc
# Chargement des fichiers si ce n'est déjà fait
#Renseignez ici le dossier où vous souhaitez stocker le fichier téléchargé.
DATA_PATH=""
import urllib.request
# fichier réduit
f = urllib.request.urlretrieve("http://www.math.univ-toulouse.fr/~besse/Wikistat/data/ml-ratings100k.csv",DATA_PATH+"ml-ratings100k.csv") | _____no_output_____ | MIT | MovieLens/Atelier-pyspark-MovieLens.ipynb | duongtoan261196/AI_Framework |
Les données sont lues comme une seule ligne de texte avant d'être restructurées au bon format d'une *matrice creuse* à savoir une liste de triplets contenant les indices de ligne, de colonne et la note pour les seules valeurs renseignées. | # Importer les données au format texte dans un RDD
small_ratings_raw_data = sc.textFile(DATA_PATH+"ml-ratings100k.csv")
# Identifier et afficher la première ligne
small_ratings_raw_data_header = small_ratings_raw_data.take(1)[0]
print(small_ratings_raw_data_header)
# Create RDD without header
all_lines = small_ratin... | _____no_output_____ | MIT | MovieLens/Atelier-pyspark-MovieLens.ipynb | duongtoan261196/AI_Framework |
3. Optimisation du rang sur l'échantillon 10kLe fichier comporte 10 000 évaluations croisant les avis de mille utilisateurs sur les films qu'ils ont vus parmi 1700. 3.1 Constitution des échantillons Séparation aléatoire en trois échantillons apprentissage, validation et test. Le paramètre de rang est optimisé en mini... | tauxTrain=0.6
tauxVal=0.2
tauxTes=0.2
# Si le total est inférieur à 1, les données sont sous-échantillonnées.
(trainDF, validDF, testDF) = ratingsDF.randomSplit([tauxTrain, tauxVal, tauxTes])
# validation et test à prédire, sans les notes
validDF_P = validDF.select("user", "item")
testDF_P = testDF.select("user", "item... | _____no_output_____ | MIT | MovieLens/Atelier-pyspark-MovieLens.ipynb | duongtoan261196/AI_Framework |
3.2 Optimisation du rang de la NMF L'erreur d'imputation des données, donc de recommandation, est estimée sur l'échantillon de validation pour différentes valeurs (grille) du rang de la factorisation matricielle. Il faudrait en principe aussi optimiser la valeur du paramètre de pénalisation pris à 0.1 par défaut.*Poin... | from pyspark.ml.recommendation import ALS
import math
import collections
# Initialisation du générateur
seed = 5
# Nombre max d'itérations (ALS)
maxIter = 10
# Régularisation L1; à optimiser également
regularization_parameter = 0.1
# Choix d'une grille pour les valeurs du rang à optimiser
ranks = [4, 8, 12]
#Initialis... | _____no_output_____ | MIT | MovieLens/Atelier-pyspark-MovieLens.ipynb | duongtoan261196/AI_Framework |
3.3 Résultats et test | # Quelques prévisions
pred_without_naDF.take(3) | _____no_output_____ | MIT | MovieLens/Atelier-pyspark-MovieLens.ipynb | duongtoan261196/AI_Framework |
Prévision finale de l'échantillon test. | #On concatane la DataFrame Train et Validatin
trainValidDF = trainDF.union(validDF)
# On crée un model avec le nouveau Dataframe complété d'apprentissage et le rank fixé à la valeur optimal
als = ALS( rank=best_rank, seed=seed, maxIter=maxIter,
regParam=regularization_parameter)
model = als.fit(train... | _____no_output_____ | MIT | MovieLens/Atelier-pyspark-MovieLens.ipynb | duongtoan261196/AI_Framework |
3 Analyse du fichier complet MovieLens propose un plus gros fichier avec 20M de notes (138000 utilisateurs, 27000 films). Ce fichier est utilisé pour extraire un fichier test de deux millions de notes à reconstruire. Les paramètres précédemment optimisés, ils pourraient sans doute l'être mieux, sont appliqués pour une... | # Chargement des fichiers si ce n'est déjà fait
import urllib.request
# fichier complet mais compressé
f = urllib.request.urlretrieve("http://www.math.univ-toulouse.fr/~besse/Wikistat/data/ml-ratings20M.zip",DATA_PATH+"ml-ratings20M.zip")
#Unzip downloaded file
import zipfile
zip_ref = zipfile.ZipFile(DATA_PATH+"ml-rat... | _____no_output_____ | MIT | MovieLens/Atelier-pyspark-MovieLens.ipynb | duongtoan261196/AI_Framework |
3.2 Echantillonnage Extraction de l'échantillon test et éventuellement sous-échantillonnage de l'échantillon d'apprentissage. | tauxTest=0.1
# Si le total est inférieur à 1, les données sont sous-échantillonnées.
(trainTotDF, testDF) = ratingsDF.randomSplit([1-tauxTest, tauxTest])
# Sous-échantillonnage de l'apprentissage permettant de
# tester pour des tailles croissantes de cet échantillon
tauxEch=0.2
(trainDF, DropData) = trainTotDF.random... | _____no_output_____ | MIT | MovieLens/Atelier-pyspark-MovieLens.ipynb | duongtoan261196/AI_Framework |
3.3 Estimation du modèle Le modèle est estimé en utilisant les valeurs des paramètres obtenues dans l'étape précédente. | import time
time_start=time.time()
# Initialisation du générateur
seed = 5
# Nombre max d'itérations (ALS)
maxIter = 10
# Régularisation L1 (valeur par défaut)
regularization_parameter = 0.1
best_rank = 8
# Estimation pour chaque valeur de rang
als = ALS(rank=rank, seed=seed, maxIter=maxIter,
regP... | _____no_output_____ | MIT | MovieLens/Atelier-pyspark-MovieLens.ipynb | duongtoan261196/AI_Framework |
3.4 Prévision de l'échantillon test et erreur | # Prévision de l'échantillon de validation
predDF = model.transform(testDF).select("prediction","rating")
#Remove unpredicter row due to no-presence of user in the train dataset
pred_without_naDF = predDF.na.drop()
# Calcul du RMSE
evaluator = RegressionEvaluator(metricName="rmse", labelCol="rating",
... | _____no_output_____ | MIT | MovieLens/Atelier-pyspark-MovieLens.ipynb | duongtoan261196/AI_Framework |
Experiments comparing the performance of traditional pooling operations and entropy pooling within a shallow neural network and Lenet. The experiments use cifar10 and cifar100. | %matplotlib inline
import torch
import torchvision
import torchvision.transforms as transforms
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
trainset = torchvision.datasets.CIFAR100(root='./data', train=True,
... | _____no_output_____ | Apache-2.0 | pytorch/notebooks/shallow_NNs-Cifar.ipynb | ChristoferNal/pooling-operations-and-information-theory |
M.A.R.K. Detection model Training and InferenceIn this notebook we will use axelerate, Keras-based framework for AI on the edge, to quickly setup model training and then after training session is completed convert it to .tflite and .kmodel formats.First, let's take care of some administrative details. 1) Before we do... | %load_ext tensorboard
#we need imgaug 0.4 for image augmentations to work properly, see https://stackoverflow.com/questions/62580797/in-colab-doing-image-data-augmentation-with-imgaug-is-not-working-as-intended
!pip uninstall -y imgaug && pip uninstall -y albumentations && pip install imgaug==0.4
!git clone https://git... | _____no_output_____ | MIT | resources/aXeleRate_mark_detector.ipynb | joaopdss/aXelerate |
At this step you typically need to get the dataset. You can use !wget command to download it from somewhere on the Internet or !cp to copy from My Drive as in this example```!cp -r /content/drive/'My Drive'/pascal_20_segmentation.zip .!unzip --qq pascal_20_segmentation.zip```Dataset preparation and postprocessing are d... | %matplotlib inline
!gdown https://drive.google.com/uc?id=1s2h6DI_1tHpLoUWRc_SavvMF9jYG8XSi #dataset
!gdown https://drive.google.com/uc?id=1-bDRZ9Z2T81SfwhHEfZIMFG7FtMQ5ZiZ #pre-trained model
!unzip --qq mark_dataset.zip
from axelerate.networks.common_utils.augment import visualize_detection_dataset
visualize_detecti... | _____no_output_____ | MIT | resources/aXeleRate_mark_detector.ipynb | joaopdss/aXelerate |
Next step is defining a config dictionary. Most lines are self-explanatory.Type is model frontend - Classifier, Detector or SegnetArchitecture is model backend (feature extractor) - Full Yolo- Tiny Yolo- MobileNet1_0- MobileNet7_5 - MobileNet5_0 - MobileNet2_5 - SqueezeNet- NASNetMobile- DenseNet121- ResNet50For more i... | config = {
"model":{
"type": "Detector",
"architecture": "MobileNet5_0",
"input_size": 224,
"anchors": [0.57273, 0.677385, 1.87446, 2.06253, 3.33843, 5.47434, 7.88282, 3.52778, 9.77052, 9.16828],
"labels":... | _____no_output_____ | MIT | resources/aXeleRate_mark_detector.ipynb | joaopdss/aXelerate |
Let's check what GPU we have been assigned in this Colab session, if any. | from tensorflow.python.client import device_lib
device_lib.list_local_devices() | _____no_output_____ | MIT | resources/aXeleRate_mark_detector.ipynb | joaopdss/aXelerate |
Also, let's open Tensorboard, where we will be able to watch model training progress in real time. Training and validation logs also will be saved in project folder.Since there are no logs before we start the training, tensorboard will be empty. Refresh it after first epoch. | %tensorboard --logdir logs | _____no_output_____ | MIT | resources/aXeleRate_mark_detector.ipynb | joaopdss/aXelerate |
Finally we start the training by passing config dictionary we have defined earlier to setup_training function. The function will start the training with Checkpoint, Reduce Learning Rate on Plateau and Early Stopping callbacks. After the training has stopped, it will convert the best model into the format you have speci... | from keras import backend as K
K.clear_session()
model_path = setup_training(config_dict=config) | _____no_output_____ | MIT | resources/aXeleRate_mark_detector.ipynb | joaopdss/aXelerate |
After training it is good to check the actual perfomance of your model by doing inference on your validation dataset and visualizing results. This is exactly what next block does. Obviously since our model has only trained on a few images the results are far from stellar, but if you have a good dataset, you'll have bet... | from keras import backend as K
K.clear_session()
setup_inference(config, model_path) | _____no_output_____ | MIT | resources/aXeleRate_mark_detector.ipynb | joaopdss/aXelerate |
Table of Contents1. [Import Modules](import)2. [Read the History File](read)3. [Summary Table](table)4. [Histogram Fission Fragment Properties](ffHistograms)5. [Correlated Observables](correlations)6. [Neutron Properties](neutrons)7. [Gamma Properties](gammas)8. [Gamma-ray Timing Information](timing)9. [Angular Correl... | import numpy as np
import os
import matplotlib.pyplot as plt
from CGMFtk import histories as fh
# also define some plotting features
import matplotlib as mpl
mpl.rcParams['font.size'] = 12
mpl.rcParams['font.family'] = 'Helvetica','serif'
mpl.rcParams['font.weight'] = 'normal'
mpl.rcParams['axes.labelsize'] = 18.
mpl.r... | _____no_output_____ | MIT | analysis/example/CGMFtkHistoriesExample.ipynb | beykyle/omp-uq |
2. Read CGMF history file | # run Cf-252 sf with a single OM param file (#42)
directory = "/home/beykyle/db/projects/OM/KDOMPuq/KDUQSamples"
for filename in os.scandir(directory):
if filename.is_file() and "42" in filename.path:
#if filename.is_file():
print(filename.path)
os.system("mpirun -np 8 --use-hwthread-cpus cgmf.m... | Analyzing histories
WARNING
You asked for 1000000 events and there are only 800 in this history file
This file contains 800 events and 1600 fission fragments
| MIT | analysis/example/CGMFtkHistoriesExample.ipynb | beykyle/omp-uq |
With the option 'nevents', the number of fission events that are read can be specified: hist = fh.Histories('92235_1MeV.cgmf',nevents=5000) 3. Summary Table | # provide a summary table of the fission events
hist.summaryTable() | _____no_output_____ | MIT | analysis/example/CGMFtkHistoriesExample.ipynb | beykyle/omp-uq |
4. Fission Fragment Properties With the histogram function from matplotlib, we can easily plot distributions of the fission fragment characteristics | # plot the distributions of the fission fragments
A = hist.getA() # get A of all fragments
AL = hist.getALF() # get A of light fragments
AH = hist.getAHF() # get A of heavy fragments
fig = plt.figure(figsize=(8,6))
bins = np.arange(min(A),max(A))
h,b = np.histogram(A,bins=bins,density=True)
plt.plot(b[:-1],h,'-o')
plt.... | _____no_output_____ | MIT | analysis/example/CGMFtkHistoriesExample.ipynb | beykyle/omp-uq |
With the 2D histogram feature, we can see correlations between the calculated features from CGMF | TKEpre = hist.getTKEpre()
TXE = hist.getTXE()
bx = np.arange(min(TKEpre),max(TKEpre))
by = np.arange(min(TXE),max(TXE))
fig = plt.figure(figsize=(8,6))
plt.hist2d(TKEpre,TXE,bins=(bx,by),density=True)
plt.xlabel('Total Kinetic Energy (MeV)')
plt.ylabel('Total Excitation Energy (MeV)')
plt.colorbar()
plt.show() | _____no_output_____ | MIT | analysis/example/CGMFtkHistoriesExample.ipynb | beykyle/omp-uq |
5. Correlated Observables Many observables within fission are correlated with one another. Sometimes, these are best visualized as two-dimensional histograms as in the TKE-TXE plot directly above. Other times, it is helpful to plot certain observables as a function of mass or TKE. There are routines within CGMFtk t... | # nubar as a function of mass
## nubarg, excitation energy, kinetic energy (pre), and spin are available as a function of mass
nubarA = hist.nubarA()
TKEA = hist.TKEA()
fig = plt.figure(figsize=(16,6))
plt.subplot(121)
plt.plot(nubarA[0],nubarA[1],'ko')
plt.xlabel('Mass (u)')
plt.ylabel(r'$\overline{\nu}$')
plt.subplot... | _____no_output_____ | MIT | analysis/example/CGMFtkHistoriesExample.ipynb | beykyle/omp-uq |
6. Neutron properties | # construct and plot the neutron multiplicity distribution
nu,pnu = hist.Pnu()
fig = plt.figure(figsize=(8,6))
plt.plot(nu,pnu,'k*--',markersize=10)
plt.xlabel(r'$\nu$')
plt.ylabel(r'P($\nu$)')
plt.show()
# construct and plot the prompt neutron spectrum
fig = plt.figure(figsize=(16,6))
plt.subplot(121)
ebins,pfns = his... | Neutron energies in the lab:
Average energy of all neutrons = 2.0337924277648622
Average energy of neutrons from fragments = 2.0337924277648622
Average energy of neutrons from light fragment = 2.2622832643406268
Average energy of neutrons from heavy fragment = 1.7410818181818182
Neutron energies in the center of ... | MIT | analysis/example/CGMFtkHistoriesExample.ipynb | beykyle/omp-uq |
Note that the energies are not recorded for the pre-fission neutrons in the center of mass frame 7. Gamma properties | # construct and plot the gamma multiplicity distribution
nug,pnug = hist.Pnug()
fig = plt.figure(figsize=(8,6))
plt.plot(nug,pnug,'k*--',markersize=10)
plt.xlabel(r'$N_\gamma$')
plt.ylabel(r'P($N_\gamma$)')
plt.show()
# construct and plot the prompt neutron spectrum
fig = plt.figure(figsize=(16,6))
plt.subplot(121)
ebi... | Gamma energies in the lab:
Average energy of all gammas = 0.7157650070395495
Average energy of gammas from light fragment = 0.7317019104946348
Average energy of gammas from heavy fragment = 0.7005107715430862
| MIT | analysis/example/CGMFtkHistoriesExample.ipynb | beykyle/omp-uq |
Note that in the current version of CGMF, only the doppler shifted lab energies are recorded in the history file 8. Gamma-ray Timing Information We can also calculate quantities that are related to the time at which the 'late' prompt gamma rays are emitted. When the option -t -1 is included in the run time options fo... | histTime = fh.Histories(workdir + timeFile, nevents=nevents*2)
# gamma-ray times can be retrieved through
gammaAges = histTime.getGammaAges() | _____no_output_____ | MIT | analysis/example/CGMFtkHistoriesExample.ipynb | beykyle/omp-uq |
The nubargtot function can also be used to construct the average gamma-ray multiplicity per fission event as a function of time. In the call to nubarg() or nubargtot(), timeWindow=True should be included which uses the default timings provided in the function (otherwise, passing a numpy array or list of times to timeW... | times,nubargTime = histTime.nubarg(timeWindow=True) # include timeWindow as a boolean or list of times (in seconds) to activate this feature
fig = plt.figure(figsize=(8,6))
plt.plot(times,nubargTime,'o',label='Eth=0. MeV')
times,nubargTime = histTime.nubarg(timeWindow=True,Eth=0.1)
plt.plot(times,nubargTime,'o',label='... | _____no_output_____ | MIT | analysis/example/CGMFtkHistoriesExample.ipynb | beykyle/omp-uq |
The prompt fission gamma-ray spectrum function, pfgs(), can also be used to calculate this quantity within a certain time window since the fission event. The time window is defined using minTime and maxTime to set the lower and upper boundaries. | fig = plt.figure(figsize=(8,6))
bE,pfgsTest = histTime.pfgs(minTime=5e-8,maxTime=500e-8)
plt.step(bE,pfgsTest,label='Time window')
bE,pfgsTest = histTime.pfgs()
plt.step(bE,pfgsTest,label='All events')
plt.yscale('log')
plt.xlim(0,2)
plt.ylim(0.1,100)
plt.xlabel('Gamma-ray Energy (MeV)')
plt.ylabel('Prompt Fission Gamm... | 99Nb: 1.0
133Te: 0.14
| MIT | analysis/example/CGMFtkHistoriesExample.ipynb | beykyle/omp-uq |
9. Angular Correlations For the fission fragment angular distribution with respect to the beam axis/z-axis, there is one option: afterEmission=True/False. afterEmission=True uses these angles after neutron emission and afterEmission=False uses these angles before neutron emission. The default is True. | # calculate cos(theta) between the fragments and z-axis/beam axis
FFangles = hist.FFangles()
bins = np.linspace(-1,1,30)
h,b = np.histogram(FFangles,bins=bins,density=True)
# only light fragments
hLight,b = np.histogram(FFangles[::2],bins=bins,density=True)
# only heavy fragments
hHeavy,b = np.histogram(FFangles[1::2],... | _____no_output_____ | MIT | analysis/example/CGMFtkHistoriesExample.ipynb | beykyle/omp-uq |
There are several options when calculating the angles of the neutrons with respect to the beam axis/z-axis. The first is including a neutron threshold energy with keyword, Eth (given in MeV). We can also calculate these angles in the lab frame (lab=True, default) or in the center of mass frame of the compound system ... | # calculate the angles between the neutrons and the z-axis/beam axis
nAllLab,nLLab,nHLab = hist.nangles(lab=True) # all neutrons, from the light fragment, from the heavy fragment
nAllCM,nLCM,nHCM = hist.nangles(lab=False) # center of mass frame of the compound
bins = np.linspace(-1,1,30)
hAllLab,b = np.histogram(nAllLa... | _____no_output_____ | MIT | analysis/example/CGMFtkHistoriesExample.ipynb | beykyle/omp-uq |
There are again several options that we can use when calculating the angles between all pairs of neutrons (from all framgments) and the ligh fragments, all of which have been seen in the last two examples. These include, Eth (neutron threshold energy), afterEmission (fission fragment angles are post or pre neutron emi... | # calculate the angles between the neutrons and the light fragments
nFall,nFLight,nFHeavy = hist.nFangles()
bins = np.linspace(-1,1,30)
hall,b = np.histogram(nFall,bins=bins,density=True)
hlight,b = np.histogram(nFLight,bins=bins,density=True)
hheavy,b = np.histogram(nFHeavy,bins=bins,density=True)
x = 0.5*(b[:-1]+b[1:... | _____no_output_____ | MIT | analysis/example/CGMFtkHistoriesExample.ipynb | beykyle/omp-uq |
0. required packages for h5py | %run "..\..\Startup_py3.py"
sys.path.append(r"..\..\..\..\Documents")
import ImageAnalysis3 as ia
%matplotlib notebook
from ImageAnalysis3 import *
print(os.getpid())
import h5py
from ImageAnalysis3.classes import _allowed_kwds
import ast | 18112
| MIT | 5kb_DNA_analysis/single_fov/20210320_updated_single_fov_IgH_batch1_proB_dox+_2color.ipynb | shiwei23/Chromatin_Analysis_Scripts |
1. Create field-of-view class | reload(ia)
reload(classes)
reload(classes.batch_functions)
reload(classes.field_of_view)
reload(io_tools.load)
reload(visual_tools)
reload(ia.correction_tools)
reload(ia.correction_tools.alignment)
reload(ia.spot_tools.matching)
reload(ia.segmentation_tools.chromosome)
reload(ia.spot_tools.fitting)
fov_param = {'data... | Get Folder Names: (ia.get_img_info.get_folders)
- Number of folders: 78
- Number of field of views: 64
- Importing csv file: \\10.245.74.158\Chromatin_NAS_1\20210320-proB_Dox_IAA_STI_CTP-08_2color\Analysis\Color_Usage_clean.csv
- header: ['Hyb', '750', '647', '488', '405']
-- Hyb H0R0 exists in this data
-- DAPI exists... | MIT | 5kb_DNA_analysis/single_fov/20210320_updated_single_fov_IgH_batch1_proB_dox+_2color.ipynb | shiwei23/Chromatin_Analysis_Scripts |
2. Process image into candidate spots | reload(io_tools.load)
reload(spot_tools.fitting)
reload(correction_tools.chromatic)
reload(classes.batch_functions)
# process image into spots
id_list, spot_list = fov._process_image_to_spots('unique',
#_sel_ids=np.arange(41,47),
... | -- No folder selected, allow processing all 75 folders
+ load reference image from file:\\10.245.74.158\Chromatin_NAS_1\20210320-proB_Dox_IAA_STI_CTP-08_2color\H0R0\Conv_zscan_30.dax
- correct the whole fov for image: \\10.245.74.158\Chromatin_NAS_1\20210320-proB_Dox_IAA_STI_CTP-08_2color\H0R0\Conv_zscan_30.dax
-- load... | MIT | 5kb_DNA_analysis/single_fov/20210320_updated_single_fov_IgH_batch1_proB_dox+_2color.ipynb | shiwei23/Chromatin_Analysis_Scripts |
3. Find chromosomes 3.1 load chromosome image | overwrite_chrom = False
chrom_im = fov._load_chromosome_image(_type='reverse',
_overwrite=overwrite_chrom) | -- choose chrom images from folder: \.
- correct the whole fov for image: \\10.245.74.158\Chromatin_NAS_1\20210320-proB_Dox_IAA_STI_CTP-08_2color\H0R0\Conv_zscan_30.dax
-- loading illumination correction profile from file:
647 illumination_correction_647_2048x2048.npy
-- loading chromatic correction profile from file... | MIT | 5kb_DNA_analysis/single_fov/20210320_updated_single_fov_IgH_batch1_proB_dox+_2color.ipynb | shiwei23/Chromatin_Analysis_Scripts |
3.2 find candidate chromosomes | chrom_coords = fov._find_candidate_chromosomes_by_segmentation(_filt_size=4,
_binary_per_th=99.75,
_morphology_size=2,
_overwrite=... | + loading fov_info from file: \\10.245.74.212\Chromatin_NAS_2\IgH_analyzed_results\20210320_IgH_proB_iaa_dox+\Conv_zscan_30.hdf5
++ base attributes loaded:[] in 4.192s.
-- adjust seed image with filter size=4
-- binarize image with threshold: 99.75%
-- erosion and dialation with size=2.
-- find close objects.
-- random... | MIT | 5kb_DNA_analysis/single_fov/20210320_updated_single_fov_IgH_batch1_proB_dox+_2color.ipynb | shiwei23/Chromatin_Analysis_Scripts |
3.3 select among candidate chromosomes | chrom_coords = fov._select_chromosome_by_candidate_spots(_good_chr_loss_th=0.3,
_cand_spot_intensity_th=200,
_save=True,
_overwrite=overwrite_chrom) | + loading fov_info from file: \\10.245.74.212\Chromatin_NAS_2\IgH_analyzed_results\20210320_IgH_proB_iaa_dox+\Conv_zscan_30.hdf5
++ base attributes loaded:[] in 5.189s.
+ loading unique from file: \\10.245.74.212\Chromatin_NAS_2\IgH_analyzed_results\20210320_IgH_proB_iaa_dox+\Conv_zscan_30.hdf5
| MIT | 5kb_DNA_analysis/single_fov/20210320_updated_single_fov_IgH_batch1_proB_dox+_2color.ipynb | shiwei23/Chromatin_Analysis_Scripts |
visualize chromosomes selections | %matplotlib notebook
%matplotlib notebook
## visualize
coord_dict = {'coords':[np.flipud(_coord) for _coord in fov.chrom_coords],
'class_ids':list(np.zeros(len(fov.chrom_coords),dtype=np.int)),
}
visual_tools.imshow_mark_3d_v2([fov.chrom_im],
given_dic=coord_d... | _____no_output_____ | MIT | 5kb_DNA_analysis/single_fov/20210320_updated_single_fov_IgH_batch1_proB_dox+_2color.ipynb | shiwei23/Chromatin_Analysis_Scripts |
select spots based on chromosomes | fov._load_from_file('unique')
intensity_th = 200
from ImageAnalysis3.spot_tools.picking import assign_spots_to_chromosomes
kept_spots_list = []
for _spots in fov.unique_spots_list:
kept_spots_list.append(_spots[_spots[:,0] > intensity_th])
# finalize candidate spots
cand_chr_spots_list = [[] for _ct in fov.chrom_c... | kept chromosomes: 522
| MIT | 5kb_DNA_analysis/single_fov/20210320_updated_single_fov_IgH_batch1_proB_dox+_2color.ipynb | shiwei23/Chromatin_Analysis_Scripts |
EM pick spots | %matplotlib inline
reload(spot_tools.picking)
from ImageAnalysis3.spot_tools.picking import _maximize_score_spot_picking_of_chr, pick_spots_by_intensities,pick_spots_by_scores, generate_reference_from_population, evaluate_differences
niter= 10
num_threads = 24
ref_chr_cts = None
# initialize
init_dna_hzxys = pick_spot... | _____no_output_____ | MIT | 5kb_DNA_analysis/single_fov/20210320_updated_single_fov_IgH_batch1_proB_dox+_2color.ipynb | shiwei23/Chromatin_Analysis_Scripts |
visualize single example | %matplotlib inline
reload(figure_tools.image)
chrom_id = 3
import matplotlib
import copy
sc_cmap = copy.copy(matplotlib.cm.get_cmap('seismic_r'))
sc_cmap.set_bad(color=[0.5,0.5,0.5,1])
#valid_inds = np.where(np.isnan(final_dna_hzxys_list[chrom_id]).sum(1) == 0)[0]
valid_inds = np.ones(len(final_dna_hzxys_list[chr... | _____no_output_____ | MIT | 5kb_DNA_analysis/single_fov/20210320_updated_single_fov_IgH_batch1_proB_dox+_2color.ipynb | shiwei23/Chromatin_Analysis_Scripts |
visualize all fitted spots | with h5py.File(fov.save_filename, "r", libver='latest') as _f:
_grp = _f['unique']
raw_spots_list = [_spots[_spots[:,0] > 0] for _spots in _grp['raw_spots'][:]]
spots_list = [_spots[_spots[:,0] > 0] for _spots in _grp['spots'][:]]
from scipy.spatial.distance import cdist
picked_spot_inds_list = []
for _i, _... | _____no_output_____ | MIT | 5kb_DNA_analysis/single_fov/20210320_updated_single_fov_IgH_batch1_proB_dox+_2color.ipynb | shiwei23/Chromatin_Analysis_Scripts |
CIFAR10 是另外一個 dataset, 和 mnist 一樣,有十種類別(飛機、汽車、鳥、貓、鹿、狗、青蛙、馬、船、卡車)https://www.cs.toronto.edu/~kriz/cifar.html | import keras
from keras.models import Sequential
from PIL import Image
import numpy as np
import tarfile
# 讀取 dataset
# 只有 train 和 test 沒有 validation
import pickle
train_X=[]
train_y=[]
tar_gz = "../Week06/cifar-10-python.tar.gz"
with tarfile.open(tar_gz) as tarf:
for i in range(1, 6):
dataset = "cifar-10-... | _____no_output_____ | MIT | Week11/01-CIFAR10.ipynb | HowardNTUST/HackNTU_Data_2017 |
將之前的 cnn model 套用過來看看 | # %load ../Week06/q_cifar10_cnn.py
import keras
from keras.layers import Dense, Activation, Conv2D, MaxPool2D, Reshape
model = Sequential()
model.add(Reshape((3, 32, 32), input_shape=(3*32*32,) ))
model.add(Conv2D(filters=32, kernel_size=(3,3), padding='same', activation="relu", data_format='channels_first'))
model.add... | _____no_output_____ | MIT | Week11/01-CIFAR10.ipynb | HowardNTUST/HackNTU_Data_2017 |
不同的 activationhttps://keras.io/activations/ | # 先定義一個工具
def add_layers(model, *layers):
for l in layers:
model.add(l)
import keras
from keras.engine.topology import Layer
from keras.layers import Dense, Activation, Conv2D, MaxPool2D, Reshape, Dropout
def MyConv2D(filters, kernel_size, **kwargs):
return (Conv2D(filters=filters, kernel_size=kernel_s... | Train on 50000 samples, validate on 1000 samples
Epoch 1/10
50000/50000 [==============================] - 59s - loss: 4.1387 - acc: 0.2103 - val_loss: 1.9535 - val_acc: 0.2730
Epoch 2/10
50000/50000 [==============================] - 58s - loss: 1.6590 - acc: 0.3671 - val_loss: 1.3423 - val_acc: 0.5450
Epoch 3/10
5000... | MIT | Week11/01-CIFAR10.ipynb | HowardNTUST/HackNTU_Data_2017 |
使用動態資料處理```python fits the model on batches with real-time data augmentation:train_generator = datagen.flow(train_X, train_Y, batch_size=100, shuffle=False)test_generator = datagen.flow(*test_data, batch_size=100, shuffle=False)model.fit_generator(train_generator, steps_per_epoch=len(train_X), ... | import keras
from keras.layers import Dense, Activation, Conv2D, MaxPool2D, Reshape, Dropout, BatchNormalization
# 輸入改成 tensor4
train_X = train_X.reshape(-1, 3, 32, 32)
test_X = test_X.reshape(-1, 3, 32, 32)
def MyConv2D(filters, kernel_size, **kwargs):
return (Conv2D(filters=filters, kernel_size=kernel_size,
... | _____no_output_____ | MIT | Week11/01-CIFAR10.ipynb | HowardNTUST/HackNTU_Data_2017 |
lasagne 中相同的```python_ = InputLayer(shape=(None, 3*32*32), input_var=input_var)_ = DropoutLayer(_, 0.2)_ = ReshapeLayer(_, ([0], 3, 32, 32))_ = conv(_, 96, 3)_ = conv(_, 96, 3)_ = MaxPool2DDNNLayer(_, 3, 2)_ = DropoutLayer(_, 0.5)_ = conv(_, 192, 3)_ = conv(_, 192, 3)_ = MaxPool2DDNNLayer(_, 3, 2)_ = DropoutLayer(_, 0.... | import keras
from keras.layers import Dense, Activation, Conv2D, MaxPool2D, Reshape, Dropout, BatchNormalization, GlobalAveragePooling2D
# 輸入改成 tensor4
train_X = train_X.reshape(-1, 3, 32, 32)
test_X = test_X.reshape(-1, 3, 32, 32)
def MyConv2D(filters, kernel_size, **kwargs):
return (Conv2D(filters=filters, kerne... | _____no_output_____ | MIT | Week11/01-CIFAR10.ipynb | HowardNTUST/HackNTU_Data_2017 |
Preprocess the data and dump to a new file | DATA_PATH = '/fast/ankitesh/data/'
TRAINFILE = 'CI_SP_M4K_train_shuffle.nc'
VALIDFILE = 'CI_SP_M4K_valid.nc'
NORMFILE = 'CI_SP_M4K_NORM_norm.nc'
percentile_path='/export/nfs0home/ankitesg/data/percentile_data.pkl'
data_name='M4K'
bin_size = 1000
scale_dict = load_pickle('/export/nfs0home/ankitesg/CBrain_project/CBRAIN-... | saving this batch
saving this batch
saving this batch
saving this batch
saving this batch
saving this batch
saving this batch
saving this batch
saving this batch
saving this batch
| MIT | notebooks/ankitesh-devlog/08_Preprocess_to_onehot.ipynb | ankitesh97/CBRAIN-CAM |
Slicing | df.recency
df['recency']
df[['recency']]
df.loc[:,'recency']
df.loc[:,['recency']]
df.iloc[:,0]
df.iloc[:,[0]] | _____no_output_____ | MIT | Module2/Manipulating_Data.ipynb | akielbowicz/DAT210x |
Boolean Indexing | df.recency < 7
df[ df.recency < 7 ]
df[ (df.recency < 7) & (df.newbie == 0) ]
df[df.recency < 7] = -100
ordered_satisfaction = ['Very Unhappy', 'Unhappy', 'Neutral', 'Happy', 'Very Happy']
df = pd.DataFrame({'satisfaction':['Mad', 'Happy', 'Unhappy', 'Neutral']})
df.satisfaction = df.satisfaction.astype("category",
... | _____no_output_____ | MIT | Module2/Manipulating_Data.ipynb | akielbowicz/DAT210x |
Feature Representation Pure Textual Features | from sklearn.feature_extraction.text import CountVectorizer
corpus = [
"Authman ran faster than Harry because he is an athlete.",
"Authman and Harry ran faster and faster.",
]
bow = CountVectorizer()
X = bow.fit_transform(corpus) # Sparse Matrix
bow.get_feature_names()
X.toarray() | _____no_output_____ | MIT | Module2/Manipulating_Data.ipynb | akielbowicz/DAT210x |
Graphical Features | %matplotlib inline
import matplotlib.pyplot as plt
from imageio import imread
# Load the image up
img = imread('imageio:chelsea.png')
# Is the image too big? Resample it down by an order of magnitude
img = img[::2, ::2]
# Scale colors from (0-255) to (0-1), then reshape to 1D array per pixel, e.g. grayscale
# If ... | _____no_output_____ | MIT | Module2/Manipulating_Data.ipynb | akielbowicz/DAT210x |
Audio Features | import scipy.io.wavfile as wavfile
sample_rate, audio_data = wavfile.read('sound.wav')
print(audio_data) | _____no_output_____ | MIT | Module2/Manipulating_Data.ipynb | akielbowicz/DAT210x |
Let's try parameters from an actual simulation: REF_RL/RUN0 | """
[tud67309@login2 RUN0]$ cat LIG_res.itp
;LIG_res.itp
[ position_restraints ]
;i funct fcx fcy fcz
6 1 800 800 800
35 1 800 800 800
23 1 800 800 800
"""
# From LIG_h.pdb:
"""
ATOM 6 C28 LIG A 1 11.765 -16.536 ... | L0 1.1840481475428983 nm
self.d 0.8326849284092993
self.c 1.0486785581066906
self.e 0.720168877255378
self.d 0.8326849284092993
self.c 1.0486785581066906
self.e 0.720168877255378
self.L 1.1840481475428983
kc_coeff 1.7480098038626308
kp1_coeff 3.334083521100217
theory_dG_in_kT [-2.88375874 -0.80431719 1.27512435 4.023... | MIT | scripts/triple-harmonic-restraint.ipynb | yabmtm/position-restraints |
REF_RL/RUN1 | """
$ cat LIG_res.itp
;LIG_res.itp
[ position_restraints ]
;i funct fcx fcy fcz
11 1 800 800 800
25 1 800 800 800
2 1 800 800 800
"""
# From LIG_h.pdb:
"""
ATOM 2 C12 LIG A 1 6.050 0.774 17.871 1.00 0.00 ... | L0 1.1840481475428983 nm
self.d 0.4836264053998706
self.c 0.834018605392616
ee_REF1.d 0.4836264053998706
ee_REF1.c 0.834018605392616
ee_REF1.L 1.1840481475428983
k_prime_coeff 5.999999999996005
theory_dG_in_kT [-5.57122688 -3.49178533 -1.41234379 1.3365284 3.41596994 4.63236527
5.49541149 8.24428368 10.32372522 ... | MIT | scripts/triple-harmonic-restraint.ipynb | yabmtm/position-restraints |
REF_RL/RUN2 | """;LIG_res.itp
[ position_restraints ]
;i funct fcx fcy fcz
13 1 800 800 800
19 1 800 800 800
9 1 800 800 800
"""
# From LIG_h.pdb:
"""
ATOM 9 C2 LIG A 1 12.189 0.731 23.852 1.00 0.00 C
ATOM ... | ee.d 0.5844506200868992
ee.c 0.40967777340459033
ee.L 1.1840481475428983
k_prime_coeff 3.965391840602323
theory_dG_in_kT [-6.1104699 -4.03102836 -1.95158682 0.79728538 2.87672692 4.09312225
4.95616846 7.70504066 9.7844822 11.86392374 13.94336528 16.02280683]
ee.g [ 0. 5. 5. 20. 35. 70. 75. 95... | MIT | scripts/triple-harmonic-restraint.ipynb | yabmtm/position-restraints |
Creating a Sentiment Analysis Web App Using PyTorch and SageMaker_Deep Learning Nanodegree Program | Deployment_---Now that we have a basic understanding of how SageMaker works we will try to use it to construct a complete project from end to end. Our goal will be to have a simple web page which a user can use to ente... | %mkdir ../data
!wget -O ../data/aclImdb_v1.tar.gz http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz
!tar -zxf ../data/aclImdb_v1.tar.gz -C ../data | mkdir: cannot create directory ‘../data’: File exists
--2020-10-07 18:13:58-- http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz
Resolving ai.stanford.edu (ai.stanford.edu)... 171.64.68.10
Connecting to ai.stanford.edu (ai.stanford.edu)|171.64.68.10|:80... connected.
HTTP request sent, awaiting response...... | MIT | Project/SageMaker Project.ipynb | csuquanyanfei/ML_Sagemaker_Studies_Project1 |
Step 2: Preparing and Processing the dataAlso, as in the XGBoost notebook, we will be doing some initial data processing. The first few steps are the same as in the XGBoost example. To begin with, we will read in each of the reviews and combine them into a single input structure. Then, we will split the dataset into a... | import os
import glob
def read_imdb_data(data_dir='../data/aclImdb'):
data = {}
labels = {}
for data_type in ['train', 'test']:
data[data_type] = {}
labels[data_type] = {}
for sentiment in ['pos', 'neg']:
data[data_type][sentiment] = []
labels[d... | IMDB reviews: train = 12500 pos / 12500 neg, test = 12500 pos / 12500 neg
| MIT | Project/SageMaker Project.ipynb | csuquanyanfei/ML_Sagemaker_Studies_Project1 |
Now that we've read the raw training and testing data from the downloaded dataset, we will combine the positive and negative reviews and shuffle the resulting records. | from sklearn.utils import shuffle
def prepare_imdb_data(data, labels):
"""Prepare training and test sets from IMDb movie reviews."""
#Combine positive and negative reviews and labels
data_train = data['train']['pos'] + data['train']['neg']
data_test = data['test']['pos'] + data['test']['neg']
... | IMDb reviews (combined): train = 25000, test = 25000
| MIT | Project/SageMaker Project.ipynb | csuquanyanfei/ML_Sagemaker_Studies_Project1 |
Now that we have our training and testing sets unified and prepared, we should do a quick check and see an example of the data our model will be trained on. This is generally a good idea as it allows you to see how each of the further processing steps affects the reviews and it also ensures that the data has been loade... | print(train_X[100])
print(train_y[100]) | "The Straight Story" is a truly beautiful movie about an elderly man named Alvin Straight, who rides his lawnmower across the country to visit his estranged, dying brother. But that's just the basic synapsis...this movie is about so much more than that. This was Richard's Farnworth's last role before he died, and it's ... | MIT | Project/SageMaker Project.ipynb | csuquanyanfei/ML_Sagemaker_Studies_Project1 |
The first step in processing the reviews is to make sure that any html tags that appear should be removed. In addition we wish to tokenize our input, that way words such as *entertained* and *entertaining* are considered the same with regard to sentiment analysis. | import nltk
from nltk.corpus import stopwords
from nltk.stem.porter import *
import re
from bs4 import BeautifulSoup
def review_to_words(review):
nltk.download("stopwords", quiet=True)
stemmer = PorterStemmer()
text = BeautifulSoup(review, "html.parser").get_text() # Remove HTML tags
text = re.su... | _____no_output_____ | MIT | Project/SageMaker Project.ipynb | csuquanyanfei/ML_Sagemaker_Studies_Project1 |
The `review_to_words` method defined above uses `BeautifulSoup` to remove any html tags that appear and uses the `nltk` package to tokenize the reviews. As a check to ensure we know how everything is working, try applying `review_to_words` to one of the reviews in the training set. | # TODO: Apply review_to_words to a review (train_X[100] or any other review)
review_to_words(train_X[100]) | _____no_output_____ | MIT | Project/SageMaker Project.ipynb | csuquanyanfei/ML_Sagemaker_Studies_Project1 |
**Question:** Above we mentioned that `review_to_words` method removes html formatting and allows us to tokenize the words found in a review, for example, converting *entertained* and *entertaining* into *entertain* so that they are treated as though they are the same word. What else, if anything, does this method do t... | import pickle
cache_dir = os.path.join("../cache", "sentiment_analysis") # where to store cache files
os.makedirs(cache_dir, exist_ok=True) # ensure cache directory exists
def preprocess_data(data_train, data_test, labels_train, labels_test,
cache_dir=cache_dir, cache_file="preprocessed_data.pkl... | Read preprocessed data from cache file: preprocessed_data.pkl
| MIT | Project/SageMaker Project.ipynb | csuquanyanfei/ML_Sagemaker_Studies_Project1 |
Transform the dataIn the XGBoost notebook we transformed the data from its word representation to a bag-of-words feature representation. For the model we are going to construct in this notebook we will construct a feature representation which is very similar. To start, we will represent each word as an integer. Of cou... | import numpy as np
from collections import Counter
def build_dict(data, vocab_size = 5000):
"""Construct and return a dictionary mapping each of the most frequently appearing words to a unique integer."""
# TODO: Determine how often each word appears in `data`. Note that `data` is a list of sentences and t... | _____no_output_____ | MIT | Project/SageMaker Project.ipynb | csuquanyanfei/ML_Sagemaker_Studies_Project1 |
**Question:** What are the five most frequently appearing (tokenized) words in the training set? Does it makes sense that these words appear frequently in the training set? **Answer:**['one', 'come', 'cartoon', 'long', 'minut'], yes, it make sense to see it in the movie review. | # TODO: Use this space to determine the five most frequently appearing words in the training set.
list(word_dict.keys())[0:5] | _____no_output_____ | MIT | Project/SageMaker Project.ipynb | csuquanyanfei/ML_Sagemaker_Studies_Project1 |
Save `word_dict`Later on when we construct an endpoint which processes a submitted review we will need to make use of the `word_dict` which we have created. As such, we will save it to a file now for future use. | data_dir = '../data/pytorch' # The folder we will use for storing data
if not os.path.exists(data_dir): # Make sure that the folder exists
os.makedirs(data_dir)
with open(os.path.join(data_dir, 'word_dict.pkl'), "wb") as f:
pickle.dump(word_dict, f) | _____no_output_____ | MIT | Project/SageMaker Project.ipynb | csuquanyanfei/ML_Sagemaker_Studies_Project1 |
Transform the reviewsNow that we have our word dictionary which allows us to transform the words appearing in the reviews into integers, it is time to make use of it and convert our reviews to their integer sequence representation, making sure to pad or truncate to a fixed length, which in our case is `500`. | def convert_and_pad(word_dict, sentence, pad=500):
NOWORD = 0 # We will use 0 to represent the 'no word' category
INFREQ = 1 # and we use 1 to represent the infrequent words, i.e., words not appearing in word_dict
working_sentence = [NOWORD] * pad
for word_index, word in enumerate(sentence[:pa... | _____no_output_____ | MIT | Project/SageMaker Project.ipynb | csuquanyanfei/ML_Sagemaker_Studies_Project1 |
As a quick check to make sure that things are working as intended, check to see what one of the reviews in the training set looks like after having been processeed. Does this look reasonable? What is the length of a review in the training set? | # Use this cell to examine one of the processed reviews to make sure everything is working as intended.
print(len(train_X))
print(len(train_X_len))
print(len(test_X))
print(len(test_X_len))
print(len(train_X[100]))
print(train_X[100]) | 25000
25000
25000
25000
500
[ 421 1135 141 12 4 169 866 1219 1180 119 71 114 248 262
51 16 227 84 570 729 1067 3953 1 1 62 569 267 945
747 225 1020 629 3519 2255 386 4562 1695 506 4407 702 144 4
402 900 296 32 131 196 92 8 151 154 2694 729 1161 5
50 ... | MIT | Project/SageMaker Project.ipynb | csuquanyanfei/ML_Sagemaker_Studies_Project1 |
**Question:** In the cells above we use the `preprocess_data` and `convert_and_pad_data` methods to process both the training and testing set. Why or why not might this be a problem? **Answer:** it can be a problem. we should only have access to the training set so our transformer can only use the training set to const... | import pandas as pd
pd.concat([pd.DataFrame(train_y), pd.DataFrame(train_X_len), pd.DataFrame(train_X)], axis=1) \
.to_csv(os.path.join(data_dir, 'train.csv'), header=False, index=False) | _____no_output_____ | MIT | Project/SageMaker Project.ipynb | csuquanyanfei/ML_Sagemaker_Studies_Project1 |
Uploading the training dataNext, we need to upload the training data to the SageMaker default S3 bucket so that we can provide access to it while training our model. | import sagemaker
sagemaker_session = sagemaker.Session()
bucket = sagemaker_session.default_bucket()
prefix = 'sagemaker/sentiment_rnn'
role = sagemaker.get_execution_role()
input_data = sagemaker_session.upload_data(path=data_dir, bucket=bucket, key_prefix=prefix) | _____no_output_____ | MIT | Project/SageMaker Project.ipynb | csuquanyanfei/ML_Sagemaker_Studies_Project1 |
**NOTE:** The cell above uploads the entire contents of our data directory. This includes the `word_dict.pkl` file. This is fortunate as we will need this later on when we create an endpoint that accepts an arbitrary review. For now, we will just take note of the fact that it resides in the data directory (and so also ... | !pygmentize train/model.py | [34mimport[39;49;00m [04m[36mtorch[39;49;00m[04m[36m.[39;49;00m[04m[36mnn[39;49;00m [34mas[39;49;00m [04m[36mnn[39;49;00m
[34mclass[39;49;00m [04m[32mLSTMClassifier[39;49;00m(nn.Module):
[33m"""[39;49;00m
[33m This is the simple RNN model we will be using to perform Sentiment Analysi... | MIT | Project/SageMaker Project.ipynb | csuquanyanfei/ML_Sagemaker_Studies_Project1 |
The important takeaway from the implementation provided is that there are three parameters that we may wish to tweak to improve the performance of our model. These are the embedding dimension, the hidden dimension and the size of the vocabulary. We will likely want to make these parameters configurable in the training ... | import torch
import torch.utils.data
# Read in only the first 250 rows
train_sample = pd.read_csv(os.path.join(data_dir, 'train.csv'), header=None, names=None, nrows=250)
# Turn the input pandas dataframe into tensors
train_sample_y = torch.from_numpy(train_sample[[0]].values).float().squeeze()
train_sample_X = torch... | _____no_output_____ | MIT | Project/SageMaker Project.ipynb | csuquanyanfei/ML_Sagemaker_Studies_Project1 |
(TODO) Writing the training methodNext we need to write the training code itself. This should be very similar to training methods that you have written before to train PyTorch models. We will leave any difficult aspects such as model saving / loading and parameter loading until a little later. | def train(model, train_loader, epochs, optimizer, loss_fn, device):
for epoch in range(1, epochs + 1):
model.train()
total_loss = 0
for batch in train_loader:
batch_X, batch_y = batch
batch_X = batch_X.to(device)
batch_y = batch_y.to(... | _____no_output_____ | MIT | Project/SageMaker Project.ipynb | csuquanyanfei/ML_Sagemaker_Studies_Project1 |
Supposing we have the training method above, we will test that it is working by writing a bit of code in the notebook that executes our training method on the small sample training set that we loaded earlier. The reason for doing this in the notebook is so that we have an opportunity to fix any errors that arise early ... | import torch.optim as optim
from train.model import LSTMClassifier
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = LSTMClassifier(32, 100, 5000).to(device)
optimizer = optim.Adam(model.parameters())
loss_fn = torch.nn.BCELoss()
train(model, train_sample_dl, 5, optimizer, loss_fn, device) | Epoch: 1, BCELoss: 0.6912282586097718
Epoch: 2, BCELoss: 0.6808721899986268
Epoch: 3, BCELoss: 0.6719786524772644
Epoch: 4, BCELoss: 0.6623488545417786
Epoch: 5, BCELoss: 0.65109281539917
| MIT | Project/SageMaker Project.ipynb | csuquanyanfei/ML_Sagemaker_Studies_Project1 |
In order to construct a PyTorch model using SageMaker we must provide SageMaker with a training script. We may optionally include a directory which will be copied to the container and from which our training code will be run. When the training container is executed it will check the uploaded directory (if there is one)... | from sagemaker.pytorch import PyTorch
estimator = PyTorch(entry_point="train.py",
source_dir="train",
role=role,
framework_version='0.4.0',
train_instance_count=1,
train_instance_type='ml.p2.xlarge', #original: train_in... | 'create_image_uri' will be deprecated in favor of 'ImageURIProvider' class in SageMaker Python SDK v2.
's3_input' class will be renamed to 'TrainingInput' in SageMaker Python SDK v2.
'create_image_uri' will be deprecated in favor of 'ImageURIProvider' class in SageMaker Python SDK v2.
| MIT | Project/SageMaker Project.ipynb | csuquanyanfei/ML_Sagemaker_Studies_Project1 |
Step 5: Testing the modelAs mentioned at the top of this notebook, we will be testing this model by first deploying it and then sending the testing data to the deployed endpoint. We will do this so that we can make sure that the deployed model is working correctly. Step 6: Deploy the model for testingNow that we have ... | estimator.model_data
training_job_name=estimator.latest_training_job.name
# TODO: Deploy the trained model
predictor = estimator.deploy(initial_instance_count = 1, instance_type = 'ml.m4.xlarge')
#original: train_instance_type='ml.p2.xlarge', the support center haven't processed my ticket
model_predict = PyTorchModel(m... | Parameter image will be renamed to image_uri in SageMaker Python SDK v2.
'create_image_uri' will be deprecated in favor of 'ImageURIProvider' class in SageMaker Python SDK v2.
| MIT | Project/SageMaker Project.ipynb | csuquanyanfei/ML_Sagemaker_Studies_Project1 |
Step 7 - Use the model for testingOnce deployed, we can read in the test data and send it off to our deployed model to get some results. Once we collect all of the results we can determine how accurate our model is. | test_X = pd.concat([pd.DataFrame(test_X_len), pd.DataFrame(test_X)], axis=1)
# We split the data into chunks and send each chunk seperately, accumulating the results.
def predict(data, rows=512):
split_array = np.array_split(data, int(data.shape[0] / float(rows) + 1))
predictions = np.array([])
for array i... | _____no_output_____ | MIT | Project/SageMaker Project.ipynb | csuquanyanfei/ML_Sagemaker_Studies_Project1 |
**Question:** How does this model compare to the XGBoost model you created earlier? Why might these two models perform differently on this dataset? Which do *you* think is better for sentiment analysis? **Answer:**XGBoost has a better accuray score than this model and run much faster. The trainning job for XGBoost take... | test_review = 'The simplest pleasures in life are the best, and this film is one of them. Combining a rather basic storyline of love and adventure this movie transcends the usual weekend fair with wit and unmitigated charm.' | _____no_output_____ | MIT | Project/SageMaker Project.ipynb | csuquanyanfei/ML_Sagemaker_Studies_Project1 |
The question we now need to answer is, how do we send this review to our model?Recall in the first section of this notebook we did a bunch of data processing to the IMDb dataset. In particular, we did two specific things to the provided reviews. - Removed any html tags and stemmed the input - Encoded the review as a se... | # TODO: Convert test_review into a form usable by the model and save the results in test_data
test_data = None
test_words = review_to_words(test_review)
test_data, test_data_len = convert_and_pad(word_dict, test_words) | _____no_output_____ | MIT | Project/SageMaker Project.ipynb | csuquanyanfei/ML_Sagemaker_Studies_Project1 |
Now that we have processed the review, we can send the resulting array to our model to predict the sentiment of the review. | predictor.predict(test_data) | _____no_output_____ | MIT | Project/SageMaker Project.ipynb | csuquanyanfei/ML_Sagemaker_Studies_Project1 |
Since the return value of our model is close to `1`, we can be certain that the review we submitted is positive. Delete the endpointOf course, just like in the XGBoost notebook, once we've deployed an endpoint it continues to run until we tell it to shut down. Since we are done using our endpoint for now, we can delet... | estimator.delete_endpoint() | _____no_output_____ | MIT | Project/SageMaker Project.ipynb | csuquanyanfei/ML_Sagemaker_Studies_Project1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.