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 |
|---|---|---|---|---|---|
1.0 Connect to workspace and datastore | from azureml.core import Workspace
# set up workspace
ws = Workspace.from_config()
# set up datastores
dstore = ws.get_default_datastore()
print('Workspace Name: ' + ws.name,
'Azure Region: ' + ws.location,
'Subscription Id: ' + ws.subscription_id,
'Resource Group: ' + ws.resource_group,
... | _____no_output_____ | MIT | Custom_Script/02_CustomScript_Training_Pipeline.ipynb | ben-chin-unify/solution-accelerator-many-models |
2.0 Create an experiment | from azureml.core import Experiment
experiment = Experiment(ws, 'oj_training_pipeline')
print('Experiment name: ' + experiment.name) | _____no_output_____ | MIT | Custom_Script/02_CustomScript_Training_Pipeline.ipynb | ben-chin-unify/solution-accelerator-many-models |
3.0 Get the training DatasetNext, we get the training Dataset using the [Dataset.get_by_name()](https://docs.microsoft.com/python/api/azureml-core/azureml.core.dataset.datasetget-by-name-workspace--name--version--latest--) method.This is the training dataset we created and registered in the [data preparation notebook]... | dataset_name = 'oj_data_small_train'
from azureml.core.dataset import Dataset
dataset = Dataset.get_by_name(ws, name=dataset_name)
dataset_input = dataset.as_named_input(dataset_name) | _____no_output_____ | MIT | Custom_Script/02_CustomScript_Training_Pipeline.ipynb | ben-chin-unify/solution-accelerator-many-models |
4.0 Create the training pipelineNow that the workspace, experiment, and dataset are set up, we can put together a pipeline for training. 4.1 Configure environment for ParallelRunStepAn [environment](https://docs.microsoft.com/en-us/azure/machine-learning/concept-environments) defines a collection of resources that we ... | from azureml.core import Environment
from azureml.core.conda_dependencies import CondaDependencies
train_env = Environment(name="many_models_environment")
train_conda_deps = CondaDependencies.create(pip_packages=['sklearn', 'pandas', 'joblib', 'azureml-defaults', 'azureml-core', 'azureml-dataprep[fuse]'])
train_env.py... | _____no_output_____ | MIT | Custom_Script/02_CustomScript_Training_Pipeline.ipynb | ben-chin-unify/solution-accelerator-many-models |
4.2 Choose a compute target Currently ParallelRunConfig only supports AMLCompute. This is the compute cluster you created in the [setup notebook](../00_Setup_AML_Workspace.ipynb3.0-Create-compute-cluster). | cpu_cluster_name = "cpucluster"
from azureml.core.compute import AmlCompute
compute = AmlCompute(ws, cpu_cluster_name) | _____no_output_____ | MIT | Custom_Script/02_CustomScript_Training_Pipeline.ipynb | ben-chin-unify/solution-accelerator-many-models |
4.3 Set up ParallelRunConfig[ParallelRunConfig](https://docs.microsoft.com/en-us/python/api/azureml-pipeline-steps/azureml.pipeline.steps.parallel_run_config.parallelrunconfig?view=azure-ml-py) provides the configuration for the ParallelRunStep we'll be creating next. Here we specify the environment and compute target... | from azureml.pipeline.steps import ParallelRunConfig
processes_per_node = 8
node_count = 1
timeout = 180
parallel_run_config = ParallelRunConfig(
source_directory='./scripts',
entry_script='train.py',
mini_batch_size="1",
run_invocation_timeout=timeout,
error_threshold=-1,
output_action="appen... | _____no_output_____ | MIT | Custom_Script/02_CustomScript_Training_Pipeline.ipynb | ben-chin-unify/solution-accelerator-many-models |
4.4 Set up ParallelRunStepThis [ParallelRunStep](https://docs.microsoft.com/en-us/python/api/azureml-pipeline-steps/azureml.pipeline.steps.parallel_run_step.parallelrunstep?view=azure-ml-py) is the main step in our training pipeline. First, we set up the output directory and define the pipeline's output name. The data... | from azureml.pipeline.core import PipelineData
output_dir = PipelineData(name="training_output", datastore=dstore) | _____no_output_____ | MIT | Custom_Script/02_CustomScript_Training_Pipeline.ipynb | ben-chin-unify/solution-accelerator-many-models |
We provide our ParallelRunStep with a name, the ParallelRunConfig created above and several other parameters:- **inputs**: A list of input datasets. Here we'll use the dataset created in the previous notebook. The number of files in that path determines the number of models will be trained in the ParallelRunStep.- **ou... | from azureml.pipeline.steps import ParallelRunStep
parallel_run_step = ParallelRunStep(
name="many-models-training",
parallel_run_config=parallel_run_config,
inputs=[dataset_input],
output=output_dir,
allow_reuse=False,
arguments=['--target_column', 'Quantity',
'--timestamp_colu... | _____no_output_____ | MIT | Custom_Script/02_CustomScript_Training_Pipeline.ipynb | ben-chin-unify/solution-accelerator-many-models |
5.0 Run the pipelineNext, we submit our pipeline to run. The run will train models for each dataset using a train set, compute accuracy metrics for the fits using a test set, and finally re-train models with all the data available. With 10 files, this should only take a few minutes but with the full dataset this can t... | from azureml.pipeline.core import Pipeline
pipeline = Pipeline(workspace=ws, steps=[parallel_run_step])
run = experiment.submit(pipeline)
#Wait for the run to complete
run.wait_for_completion(show_output=False, raise_on_error=True) | _____no_output_____ | MIT | Custom_Script/02_CustomScript_Training_Pipeline.ipynb | ben-chin-unify/solution-accelerator-many-models |
6.0 View results of training pipelineThe dataframe we return in the run method of train.py is outputted to *parallel_run_step.txt*. To see the results of our training pipeline, we'll download that file, read in the data to a DataFrame, and then visualize the results, including the in-sample metrics.The run submitted t... | import os
def download_results(run, target_dir=None, step_name='many-models-training', output_name='training_output'):
stitch_run = run.find_step_run(step_name)[0]
port_data = stitch_run.get_output_data(output_name)
port_data.download(target_dir, show_progress=True)
return os.path.join(target_dir, 'azu... | _____no_output_____ | MIT | Custom_Script/02_CustomScript_Training_Pipeline.ipynb | ben-chin-unify/solution-accelerator-many-models |
6.2 Convert the file to a dataframe | import pandas as pd
df = pd.read_csv(file_path + '/parallel_run_step.txt', sep=" ", header=None)
df.columns = ['Store', 'Brand', 'Model', 'File Name', 'ModelName', 'StartTime', 'EndTime', 'Duration',
'MSE', 'RMSE', 'MAE', 'MAPE', 'Index', 'Number of Models', 'Status']
df['StartTime'] = pd.to_datetime(df... | _____no_output_____ | MIT | Custom_Script/02_CustomScript_Training_Pipeline.ipynb | ben-chin-unify/solution-accelerator-many-models |
6.3 Review Results | total = df['EndTime'].max() - df['StartTime'].min()
print('Number of Models: ' + str(len(df)))
print('Total Duration: ' + str(total)[6:])
print('Average MAPE: ' + str(round(df['MAPE'].mean(), 5)))
print('Average MSE: ' + str(round(df['MSE'].mean(), 5)))
print('Average RMSE: ' + str(round(df['RMSE'].mean(), 5)))
print... | _____no_output_____ | MIT | Custom_Script/02_CustomScript_Training_Pipeline.ipynb | ben-chin-unify/solution-accelerator-many-models |
6.4 Visualize Performance across modelsHere, we produce some charts from the errors metrics calculated during the run using a subset put aside for testing.First, we examine the distribution of mean absolute percentage error (MAPE) over all the models: | import seaborn as sns
import matplotlib.pyplot as plt
fig = sns.boxplot(y='MAPE', data=df)
fig.set_title('MAPE across all models') | _____no_output_____ | MIT | Custom_Script/02_CustomScript_Training_Pipeline.ipynb | ben-chin-unify/solution-accelerator-many-models |
Next, we can break that down by Brand or Store to see variations in error across our models | fig = sns.boxplot(x='Brand', y='MAPE', data=df)
fig.set_title('MAPE by Brand') | _____no_output_____ | MIT | Custom_Script/02_CustomScript_Training_Pipeline.ipynb | ben-chin-unify/solution-accelerator-many-models |
We can also look at how long models for different brands took to train | brand = df.groupby('Brand')
brand = brand['Duration'].sum()
brand = pd.DataFrame(brand)
brand['time_in_seconds'] = [time.total_seconds() for time in brand['Duration']]
brand.drop(columns=['Duration']).plot(kind='bar')
plt.xlabel('Brand')
plt.ylabel('Seconds')
plt.title('Total Training Time by Brand')
plt.show() | _____no_output_____ | MIT | Custom_Script/02_CustomScript_Training_Pipeline.ipynb | ben-chin-unify/solution-accelerator-many-models |
7.0 Publish and schedule the pipeline (Optional) 7.1 Publish the pipelineOnce you have a pipeline you're happy with, you can publish a pipeline so you can call it programatically later on. See this [tutorial](https://docs.microsoft.com/en-us/azure/machine-learning/how-to-create-your-first-pipelinepublish-a-pipeline) f... | # published_pipeline = pipeline.publish(name = 'train_many_models',
# description = 'train many models',
# version = '1',
# continue_on_step_failure = False) | _____no_output_____ | MIT | Custom_Script/02_CustomScript_Training_Pipeline.ipynb | ben-chin-unify/solution-accelerator-many-models |
7.2 Schedule the pipelineYou can also [schedule the pipeline](https://docs.microsoft.com/en-us/azure/machine-learning/how-to-schedule-pipelines) to run on a time-based or change-based schedule. This could be used to automatically retrain models every month or based on another trigger such as data drift. | # from azureml.pipeline.core import Schedule, ScheduleRecurrence
# training_pipeline_id = published_pipeline.id
# recurrence = ScheduleRecurrence(frequency="Month", interval=1, start_time="2020-01-01T09:00:00")
# recurring_schedule = Schedule.create(ws, name="training_pipeline_recurring_schedule",
# ... | _____no_output_____ | MIT | Custom_Script/02_CustomScript_Training_Pipeline.ipynb | ben-chin-unify/solution-accelerator-many-models |
Let's turn the mapping features into a function | def get_ticks(bounds, dirs, otherbounds):
dirs = dirs.lower()
l0 = np.float(bounds[0])
l1 = np.float(bounds[1])
r = np.max([l1 - l0, np.float(otherbounds[1]) - np.float(otherbounds[0])])
if r <= 1.5:
# <1.5 degrees: 15' major ticks, 5' minor ticks
minor_int = 1.0 / 12.0
major... | _____no_output_____ | MIT | examples/notebooks/plot_quiver_curly.ipynb | teresaupdyke/codar_processing |
Let's change the arrows | # velocity_min = np.int32(np.nanmin(speed)) # Get the minimum speed from the data
# velocity_max =np.int32(np.nanmax(speed)) # Get the maximum speed from the data
# velocity_min = 0 # Get the minimum speed from the data
# velocity_max = 40 # Get the maximum speed from the data
# Setup a keyword argument, kwargs, dict... | _____no_output_____ | MIT | examples/notebooks/plot_quiver_curly.ipynb | teresaupdyke/codar_processing |
Amazon SageMaker Object Detection for Bird Species1. [Introduction](Introduction)2. [Setup](Setup)3. [Data Preparation](Data-Preparation) 1. [Download and unpack the dataset](Download-and-unpack-the-dataset) 2. [Understand the dataset](Understand-the-dataset) 3. [Generate RecordIO files](Generate-RecordIO-files)4. ... | import sys
!{sys.executable} -m pip install opencv-python
!{sys.executable} -m pip install mxnet | _____no_output_____ | Apache-2.0 | introduction_to_amazon_algorithms/object_detection_birds/object_detection_birds.ipynb | Amirosimani/amazon-sagemaker-examples |
We need to identify the S3 bucket that you want to use for providing training and validation datasets. It will also be used to store the tranied model artifacts. In this notebook, we use a custom bucket. You could alternatively use a default bucket for the session. We use an object prefix to help organize the bucket ... | bucket = "<your_s3_bucket_name_here>" # custom bucket name.
prefix = "DEMO-ObjectDetection-birds" | _____no_output_____ | Apache-2.0 | introduction_to_amazon_algorithms/object_detection_birds/object_detection_birds.ipynb | Amirosimani/amazon-sagemaker-examples |
To train the Object Detection algorithm on Amazon SageMaker, we need to setup and authenticate the use of AWS services. To begin with, we need an AWS account role with SageMaker access. Here we will use the execution role the current notebook instance was given when it was created. This role has necessary permissions,... | import sagemaker
from sagemaker import get_execution_role
role = get_execution_role()
print(role)
sess = sagemaker.Session() | _____no_output_____ | Apache-2.0 | introduction_to_amazon_algorithms/object_detection_birds/object_detection_birds.ipynb | Amirosimani/amazon-sagemaker-examples |
Data PreparationThe [Caltech Birds (CUB 200 2011)](http://www.vision.caltech.edu/visipedia/CUB-200-2011.html) dataset contains 11,788 images across 200 bird species (the original technical report can be found [here](http://www.vision.caltech.edu/visipedia/papers/CUB_200_2011.pdf)). Each species comes with around 60 i... | import os
import urllib.request
def download(url):
filename = url.split("/")[-1]
if not os.path.exists(filename):
urllib.request.urlretrieve(url, filename)
%%time
# download('http://www.vision.caltech.edu/visipedia-data/CUB-200-2011/CUB_200_2011.tgz')
# CalTech's download is (at least temporarily) una... | _____no_output_____ | Apache-2.0 | introduction_to_amazon_algorithms/object_detection_birds/object_detection_birds.ipynb | Amirosimani/amazon-sagemaker-examples |
Now we unpack the dataset into its own directory structure. | %%time
# Clean up prior version of the downloaded dataset if you are running this again
!rm -rf CUB_200_2011
# Unpack and then remove the downloaded compressed tar file
!gunzip -c ./CUB_200_2011.tgz | tar xopf -
!rm CUB_200_2011.tgz | _____no_output_____ | Apache-2.0 | introduction_to_amazon_algorithms/object_detection_birds/object_detection_birds.ipynb | Amirosimani/amazon-sagemaker-examples |
Understand the dataset Set some parameters for the rest of the notebook to use Here we define a few parameters that help drive the rest of the notebook. For example, `SAMPLE_ONLY` is defaulted to `True`. This will force the notebook to train on only a handful of species. Setting to false will make the notebook work... | import pandas as pd
import cv2
import boto3
import json
runtime = boto3.client(service_name="runtime.sagemaker")
import matplotlib.pyplot as plt
%matplotlib inline
RANDOM_SPLIT = False
SAMPLE_ONLY = True
FLIP = False
# To speed up training and experimenting, you can use a small handful of species.
# To see the ful... | _____no_output_____ | Apache-2.0 | introduction_to_amazon_algorithms/object_detection_birds/object_detection_birds.ipynb | Amirosimani/amazon-sagemaker-examples |
Explore the dataset imagesFor each species, there are dozens of images of various shapes and sizes. By dividing the entire dataset into individual named (numbered) folders, the images are in effect labelled for supervised learning using image classification and object detection algorithms. The following function displ... | def show_species(species_id):
_im_list = !ls $IMAGES_DIR/$species_id
NUM_COLS = 6
IM_COUNT = len(_im_list)
print('Species ' + species_id + ' has ' + str(IM_COUNT) + ' images.')
NUM_ROWS = int(IM_COUNT / NUM_COLS)
if ((IM_COUNT % NUM_COLS) > 0):
NUM_ROWS += 1
fig, axarr = plt.... | _____no_output_____ | Apache-2.0 | introduction_to_amazon_algorithms/object_detection_birds/object_detection_birds.ipynb | Amirosimani/amazon-sagemaker-examples |
Show the list of bird species or dataset classes. | classes_df = pd.read_csv(CLASSES_FILE, sep=" ", names=CLASS_COLS, header=None)
criteria = classes_df["class_number"].isin(CLASSES)
classes_df = classes_df[criteria]
print(classes_df.to_csv(columns=["class_id"], sep="\t", index=False, header=False)) | _____no_output_____ | Apache-2.0 | introduction_to_amazon_algorithms/object_detection_birds/object_detection_birds.ipynb | Amirosimani/amazon-sagemaker-examples |
Now for any given species, display thumbnail images of each of the images provided for training and testing. | show_species("017.Cardinal") | _____no_output_____ | Apache-2.0 | introduction_to_amazon_algorithms/object_detection_birds/object_detection_birds.ipynb | Amirosimani/amazon-sagemaker-examples |
Generate RecordIO files Step 1. Gather image sizesFor this particular dataset, bounding box annotations are specified in absolute terms. RecordIO format requires them to be defined in terms relative to the image size. The following code visits each image, extracts the height and width, and saves this information in... | %%time
SIZE_COLS = ["idx", "width", "height"]
def gen_image_size_file():
print("Generating a file containing image sizes...")
images_df = pd.read_csv(
IMAGE_FILE, sep=" ", names=["image_pretty_name", "image_file_name"], header=None
)
rows_list = []
idx = 0
for i in images_df["image_fil... | _____no_output_____ | Apache-2.0 | introduction_to_amazon_algorithms/object_detection_birds/object_detection_birds.ipynb | Amirosimani/amazon-sagemaker-examples |
Step 2. Generate list files for producing RecordIO files [RecordIO](https://mxnet.incubator.apache.org/architecture/note_data_loading.html) files can be created using the [im2rec tool](https://mxnet.incubator.apache.org/faq/recordio.html) (images to RecordIO), which takes as input a pair of list files, one for trainin... | def split_to_train_test(df, label_column, train_frac=0.8):
train_df, test_df = pd.DataFrame(), pd.DataFrame()
labels = df[label_column].unique()
for lbl in labels:
lbl_df = df[df[label_column] == lbl]
lbl_train_df = lbl_df.sample(frac=train_frac)
lbl_test_df = lbl_df.drop(lbl_train_d... | _____no_output_____ | Apache-2.0 | introduction_to_amazon_algorithms/object_detection_birds/object_detection_birds.ipynb | Amirosimani/amazon-sagemaker-examples |
Here we take a look at a few records from the training list file to understand better what is being fed to the RecordIO files.The first column is the image number or index. The second column indicates that the label is made up of 2 columns (column 2 and column 3). The third column specifies the label width of a singl... | !tail -3 $TRAIN_LST_FILE | _____no_output_____ | Apache-2.0 | introduction_to_amazon_algorithms/object_detection_birds/object_detection_birds.ipynb | Amirosimani/amazon-sagemaker-examples |
Step 2. Convert data into RecordIO formatNow we create im2rec databases (.rec files) for training and validation based on the list files created earlier. | !python tools/im2rec.py --resize $RESIZE_SIZE --pack-label birds_ssd_sample $BASE_DIR/images/ | _____no_output_____ | Apache-2.0 | introduction_to_amazon_algorithms/object_detection_birds/object_detection_birds.ipynb | Amirosimani/amazon-sagemaker-examples |
Step 3. Upload RecordIO files to S3Upload the training and validation data to the S3 bucket. We do this in multiple channels. Channels are simply directories in the bucket that differentiate the types of data provided to the algorithm. For the object detection algorithm, we call these directories `train` and `validati... | # Upload the RecordIO files to train and validation channels
train_channel = prefix + "/train"
validation_channel = prefix + "/validation"
sess.upload_data(path="birds_ssd_sample_train.rec", bucket=bucket, key_prefix=train_channel)
sess.upload_data(path="birds_ssd_sample_val.rec", bucket=bucket, key_prefix=validation_... | _____no_output_____ | Apache-2.0 | introduction_to_amazon_algorithms/object_detection_birds/object_detection_birds.ipynb | Amirosimani/amazon-sagemaker-examples |
Train the model Next we define an output location in S3, where the model artifacts will be placed on completion of the training. These artifacts are the output of the algorithm's traning job. We also get the URI to the Amazon SageMaker Object Detection docker image. This ensures the estimator uses the correct algori... | from sagemaker.amazon.amazon_estimator import get_image_uri
training_image = get_image_uri(sess.boto_region_name, "object-detection", repo_version="latest")
print(training_image)
s3_output_location = "s3://{}/{}/output".format(bucket, prefix)
od_model = sagemaker.estimator.Estimator(
training_image,
role,
... | _____no_output_____ | Apache-2.0 | introduction_to_amazon_algorithms/object_detection_birds/object_detection_birds.ipynb | Amirosimani/amazon-sagemaker-examples |
Define hyperparameters The object detection algorithm at its core is the [Single-Shot Multi-Box detection algorithm (SSD)](https://arxiv.org/abs/1512.02325). This algorithm uses a `base_network`, which is typically a [VGG](https://arxiv.org/abs/1409.1556) or a [ResNet](https://arxiv.org/abs/1512.03385). The Amazon Sag... | def set_hyperparameters(num_epochs, lr_steps):
num_classes = classes_df.shape[0]
num_training_samples = train_df.shape[0]
print("num classes: {}, num training images: {}".format(num_classes, num_training_samples))
od_model.set_hyperparameters(
base_network="resnet-50",
use_pretrained_mo... | _____no_output_____ | Apache-2.0 | introduction_to_amazon_algorithms/object_detection_birds/object_detection_birds.ipynb | Amirosimani/amazon-sagemaker-examples |
Now that the hyperparameters are setup, we define the data channels to be passed to the algorithm. To do this, we need to create the `sagemaker.session.s3_input` objects from our data channels. These objects are then put in a simple dictionary, which the algorithm consumes. Note that you could add a third channel name... | train_data = sagemaker.session.s3_input(
s3_train_data,
distribution="FullyReplicated",
content_type="application/x-recordio",
s3_data_type="S3Prefix",
)
validation_data = sagemaker.session.s3_input(
s3_validation_data,
distribution="FullyReplicated",
content_type="application/x-recordio",
... | _____no_output_____ | Apache-2.0 | introduction_to_amazon_algorithms/object_detection_birds/object_detection_birds.ipynb | Amirosimani/amazon-sagemaker-examples |
Submit training job We have our `Estimator` object, we have set the hyperparameters for this object, and we have our data channels linked with the algorithm. The only remaining thing to do is to train the algorithm using the `fit` method. This will take more than 10 minutes in our example.The training process involves... | %%time
od_model.fit(inputs=data_channels, logs=True) | _____no_output_____ | Apache-2.0 | introduction_to_amazon_algorithms/object_detection_birds/object_detection_birds.ipynb | Amirosimani/amazon-sagemaker-examples |
Now that the training job is complete, you can also see the job listed in the `Training jobs` section of your SageMaker console. Note that the job name is uniquely identified by the name of the algorithm concatenated with the date and time stamp. You can click on the job to see the details including the hyperparamete... | import boto3
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
%matplotlib inline
client = boto3.client("logs")
BASE_LOG_NAME = "/aws/sagemaker/TrainingJobs"
def plot_object_detection_log(model, title):
logs = client.describe_log_streams(
logGroupName=BASE_LOG_NAME, l... | _____no_output_____ | Apache-2.0 | introduction_to_amazon_algorithms/object_detection_birds/object_detection_birds.ipynb | Amirosimani/amazon-sagemaker-examples |
Host the model Once the training is done, we can deploy the trained model as an Amazon SageMaker real-time hosted endpoint. This lets us make predictions (or inferences) from the model. Note that we don't have to host using the same type of instance that we used to train. Training is a prolonged and compute heavy job ... | %%time
object_detector = od_model.deploy(initial_instance_count=1, instance_type="ml.m4.xlarge") | _____no_output_____ | Apache-2.0 | introduction_to_amazon_algorithms/object_detection_birds/object_detection_birds.ipynb | Amirosimani/amazon-sagemaker-examples |
Test the model Now that the trained model is deployed at an endpoint that is up-and-running, we can use this endpoint for inference. The results of a call to the inference endpoint are in a format that is similar to the .lst format, with the addition of a confidence score for each detected object. The format of the o... | def visualize_detection(img_file, dets, classes=[], thresh=0.6):
"""
visualize detections in one image
Parameters:
----------
img : numpy.array
image, in bgr format
dets : numpy.array
ssd detections, numpy.array([[id, score, x1, y1, x2, y2]...])
each row is one object
... | _____no_output_____ | Apache-2.0 | introduction_to_amazon_algorithms/object_detection_birds/object_detection_birds.ipynb | Amirosimani/amazon-sagemaker-examples |
Now we use our endpoint to try to detect objects within an image. Since the image is a jpeg, we use the appropriate content_type to run the prediction. The endpoint returns a JSON object that we can simply load and peek into. We have packaged the prediction code into a function to make it easier to test other images. ... | OBJECT_CATEGORIES = classes_df["class_id"].values.tolist()
def show_bird_prediction(filename, ep, thresh=0.40):
b = ""
with open(filename, "rb") as image:
f = image.read()
b = bytearray(f)
endpoint_response = runtime.invoke_endpoint(EndpointName=ep, ContentType="image/jpeg", Body=b)
re... | _____no_output_____ | Apache-2.0 | introduction_to_amazon_algorithms/object_detection_birds/object_detection_birds.ipynb | Amirosimani/amazon-sagemaker-examples |
Here we download images that the algorithm has not yet seen. | !wget -q -O multi-goldfinch-1.jpg https://t3.ftcdn.net/jpg/01/44/64/36/500_F_144643697_GJRUBtGc55KYSMpyg1Kucb9yJzvMQooW.jpg
!wget -q -O northern-flicker-1.jpg https://upload.wikimedia.org/wikipedia/commons/5/5c/Northern_Flicker_%28Red-shafted%29.jpg
!wget -q -O northern-cardinal-1.jpg https://cdn.pixabay.com/photo/2013... | _____no_output_____ | Apache-2.0 | introduction_to_amazon_algorithms/object_detection_birds/object_detection_birds.ipynb | Amirosimani/amazon-sagemaker-examples |
Clean upHere we delete the SageMaker endpoint, as we will no longer be performing any inferences. This is an important step, as your account is billed for the amount of time an endpoint is running, even when it is idle. | sagemaker.Session().delete_endpoint(object_detector.endpoint) | _____no_output_____ | Apache-2.0 | introduction_to_amazon_algorithms/object_detection_birds/object_detection_birds.ipynb | Amirosimani/amazon-sagemaker-examples |
Improve the model Define Function to Flip the Images Horizontally (on the X Axis) | from PIL import Image
def flip_images():
print("Flipping images...")
SIZE_COLS = ["idx", "width", "height"]
IMAGE_COLS = ["image_pretty_name", "image_file_name"]
LABEL_COLS = ["image_pretty_name", "class_id"]
BBOX_COLS = ["image_pretty_name", "x_abs", "y_abs", "bbox_width", "bbox_height"]
SPL... | _____no_output_____ | Apache-2.0 | introduction_to_amazon_algorithms/object_detection_birds/object_detection_birds.ipynb | Amirosimani/amazon-sagemaker-examples |
Re-train the model with the expanded dataset | %%time
BBOX_FILE = BASE_DIR + "bounding_boxes_with_flip.txt"
IMAGE_FILE = BASE_DIR + "images_with_flip.txt"
LABEL_FILE = BASE_DIR + "image_class_labels_with_flip.txt"
SIZE_FILE = BASE_DIR + "sizes_with_flip.txt"
SPLIT_FILE = BASE_DIR + "train_test_split_with_flip.txt"
# add a set of flipped images
flip_images()
# sh... | _____no_output_____ | Apache-2.0 | introduction_to_amazon_algorithms/object_detection_birds/object_detection_birds.ipynb | Amirosimani/amazon-sagemaker-examples |
Re-deploy and test | # host the updated model
object_detector = od_model.deploy(initial_instance_count=1, instance_type="ml.m4.xlarge")
# test the new model
test_model() | _____no_output_____ | Apache-2.0 | introduction_to_amazon_algorithms/object_detection_birds/object_detection_birds.ipynb | Amirosimani/amazon-sagemaker-examples |
Final cleanupHere we delete the SageMaker endpoint, as we will no longer be performing any inferences. This is an important step, as your account is billed for the amount of time an endpoint is running, even when it is idle. | # delete the new endpoint
sagemaker.Session().delete_endpoint(object_detector.endpoint) | _____no_output_____ | Apache-2.0 | introduction_to_amazon_algorithms/object_detection_birds/object_detection_birds.ipynb | Amirosimani/amazon-sagemaker-examples |
Test | import fastai.train
import pandas as pd
import torch
import torch.nn as nn
from captum.attr import LayerIntegratedGradients
# --- Model Setup ---
# Load a fast.ai `Learner` trained to predict IMDB review category `[negative, positive]`
awd = fastai.train.load_learner(".", "imdb_fastai_trained_lm_clf.pth")
awd.model[0... | _____no_output_____ | Apache-2.0 | Interactive.ipynb | MichaMucha/awdlstm-integrated-gradients |
데이터 불러오기 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import datetime as dt
import warnings
warnings.filterwarnings('ignore')
%matplotlib inline
import matplotlib as mat
import matplotlib.font_manager as fonm
font_list = [font.name for font in fonm.fontManager.ttflist]
# for f in... | _____no_output_____ | BSD-Source-Code | 2. data_check.ipynb | DUYONGBEAK/Insurance-fraud-detection-model |
데이터 복사 | copy_insurance = insurance.copy() | _____no_output_____ | BSD-Source-Code | 2. data_check.ipynb | DUYONGBEAK/Insurance-fraud-detection-model |
비식별화 및 고유값이 많은 컬럼 삭제 - unique한 값이 많으면 인코딩이 어려움으로 해당하는 컬럼들 삭제 - 실제로 컬럼삭제를 진행하지 않은 결과 인코딩 시 차원이 60000여개로 늘어나는 문제 발생 | col_1, col_2 = unique_check(copy_insurance)
col_2.remove('RESI_TYPE_CODE')
col_2.remove('OCCP_GRP_1')
col_2.remove('MINCRDT')
col_2.remove('MAXCRDT')
col_2.remove('DMND_RESN_CODE')
col_2.remove('CUST_ROLE')
# index를 CUST_ID로 변경
copy_insurance.set_index('CUST_ID', inplace=True)
copy_insurance.drop(col_2, axis=1, inpla... | _____no_output_____ | BSD-Source-Code | 2. data_check.ipynb | DUYONGBEAK/Insurance-fraud-detection-model |
데이터 파악하기 변수간 상관관계 확인 | ### 필요한 모듈 불러오기
#%matplotlib inline # 시각화 결과를 Jupyter Notebook에서 바로 보기
# import matplotlib.pyplot as plt # 모듈 불러오기
### 상관계수 테이블
corr = copy_insurance.corr() # 'df'라는 데이터셋을 'corr'라는 이름의 상관계수 테이블로 저장
### 상관계수 히트맵 그리기
# 히트맵 사이즈 설정
plt.figure(figsize = (20, 15))
# 히트맵 형태 정의. 여기서는 삼각형 형태(위 쪽 삼각형에 True, 아래 삼각형에 F... | _____no_output_____ | BSD-Source-Code | 2. data_check.ipynb | DUYONGBEAK/Insurance-fraud-detection-model |
연관성이 높은 컬럼 제거 | copy_insurance = copy_insurance[copy_insurance.columns.difference(['LTBN_CHLD_AGE','JPBASE_HSHD_INCM'])] | _____no_output_____ | BSD-Source-Code | 2. data_check.ipynb | DUYONGBEAK/Insurance-fraud-detection-model |
데이터가 정규분포를 이루는지 확인하기 - 최소 최대 정규화: 모든 feature들의 스케일이 동일하지만, 이상치(outlier)를 잘 처리하지 못한다. (X - MIN) / (MAX-MIN) - Z-점수 정규화(표준화) : 이상치(outlier)를 잘 처리하지만, 정확히 동일한 척도로 정규화 된 데이터를 생성하지는 않는다. (X - 평균) / 표준편차 | plot_target = int_col(copy_insurance)
import scipy.stats as stats
for i in plot_target:
print(i,"의 가우시안 분포 확인")
fig = plt.figure(figsize=(15,3))
ax1 = fig.add_subplot(1,2,1)
ax2 = fig.add_subplot(1,2,2)
stats.probplot(copy_insurance[i], dist=stats.norm,plot=ax1)
mu = copy_insurance[i].mean()
... | AGE 의 가우시안 분포 확인
| BSD-Source-Code | 2. data_check.ipynb | DUYONGBEAK/Insurance-fraud-detection-model |
stats.kstest으로 가설검증하기 - 귀무가설은 '정규분포를 따른다' 이다. | for i in plot_target:
print(i,"귀무가설의 기각 여부 확인")
test_state, p_val = stats.kstest(copy_insurance[i],'norm',args=(copy_insurance[i].mean(), copy_insurance[i].var()**0.5) )
print("Test-statistics : {:.5f}, p-value : {:.5f}".format(test_state, p_val))
print() | AGE 귀무가설의 기각 여부 확인
Test-statistics : 0.05453, p-value : 0.00000
CHLD_CNT 귀무가설의 기각 여부 확인
Test-statistics : 0.36416, p-value : 0.00000
CLAIM_NUM 귀무가설의 기각 여부 확인
Test-statistics : 0.25656, p-value : 0.00000
CUST_INCM 귀무가설의 기각 여부 확인
Test-statistics : 0.29274, p-value : 0.00000
CUST_RGST 귀무가설의 기각 여부 확인
Test-statistics : ... | BSD-Source-Code | 2. data_check.ipynb | DUYONGBEAK/Insurance-fraud-detection-model |
AGE를 제외한 모든 컬럼이 정규분포를 따르지 않으므로 MinMaxScaler를 이용해 정규화 적용 | from sklearn.preprocessing import MinMaxScaler
int_data = copy_insurance[plot_target]
# 인덱스 빼두기
index = int_data.index
# MinMaxcaler 객체 생성
scaler = MinMaxScaler()
# MinMaxcaler로 데이터 셋 변환 .fit( ) 과 .transform( ) 호출
scaler.fit(int_data)
data_scaled = scaler.transform(int_data)
# int_data.loc[:,:] = data_scaled
# ... | feature 들의 정규화 최소 값
AGE 0.0
CHLD_CNT 0.0
CLAIM_NUM 0.0
CUST_INCM 0.0
CUST_RGST 0.0
DISTANCE 0.0
HOUSE_HOSP_DIST 0.0
PAYM_AMT 0.0
RCBASE_HSHD_INCM 0.0
RESI_COST 0.0
RESN_DATE_NUM 0.0
SUM_ORIG_PREM 0.0
TOTALPREM ... | BSD-Source-Code | 2. data_check.ipynb | DUYONGBEAK/Insurance-fraud-detection-model |
label컬럼을 제외한 나머지 카테고리 데이터들은 원핫 인코딩을 진행 | onehot_target = str_col(copy_insurance)
onehot_target.remove('SIU_CUST_YN')
str_data = copy_insurance[onehot_target]
onehot_data = pd.get_dummies(str_data) | ['ACCI_DVSN', 'CUST_ROLE', 'DMND_RESN_CODE', 'FP_CAREER', 'HEED_HOSP_YN', 'MAXCRDT', 'MINCRDT', 'OCCP_GRP_1', 'RESI_TYPE_CODE', 'SEX', 'SIU_CUST_YN', 'WEDD_YN']
| BSD-Source-Code | 2. data_check.ipynb | DUYONGBEAK/Insurance-fraud-detection-model |
인코딩과 스케일링 데이터, 라벨을 합쳐서 저장 | concat_data = pd.concat([data_scaled, onehot_data, copy_insurance['SIU_CUST_YN']], axis=1)
concat_data.to_csv('./temp_data/save_scaled_insurance.csv',index = True) | _____no_output_____ | BSD-Source-Code | 2. data_check.ipynb | DUYONGBEAK/Insurance-fraud-detection-model |
Repertoire classification subsamplingWhen training a classifier to assign repertoires to the subject from which they were obtained, we need a set of subsampled sequences. The sequences have been condensed to just the V- and J-gene assignments and the CDR3 length (VJ-CDR3len). Subsample sizes range from 10 to 10,000 se... | from __future__ import print_function, division
from collections import Counter
import os
import subprocess as sp
import sys
import tempfile
from abutils.utils.pipeline import make_dir | _____no_output_____ | MIT | data_processing/05_repertoire-classification-subsampling.ipynb | Linda-Lan/grp_paper |
Subjects, subsample sizes, and directoriesThe `input_dir` should contain deduplicated clonotype sequences. The datafiles are too large to be included in the Github repository, but may be downloaded [**here**](http://burtonlab.s3.amazonaws.com/GRP_github_data/techrep-merged_vj-cdr3len_no-header.tar.gz). If downloading ... | with open('./data/subjects.txt') as f:
subjects = sorted(f.read().split())
subsample_sizes = list(range(10, 100, 10)) + list(range(100, 1000, 100)) + list(range(1000, 11000, 1000))
input_dir = './data/techrep-merged_vj-cdr3len_no-header/'
subsample_dir = './data/repertoire_classification/user-created_subsamples_v... | _____no_output_____ | MIT | data_processing/05_repertoire-classification-subsampling.ipynb | Linda-Lan/grp_paper |
Subsampling | def subsample(infile, outfile, n_seqs, iterations):
with open(outfile, 'w') as f:
f.write('')
shuf_cmd = 'shuf -n {} {}'.format(n_seqs, infile)
p = sp.Popen(shuf_cmd, stdout=sp.PIPE, stderr=sp.PIPE, shell=True)
stdout, stderr = p.communicate()
with open(outfile, 'a') as f:
for iterat... | _____no_output_____ | MIT | data_processing/05_repertoire-classification-subsampling.ipynb | Linda-Lan/grp_paper |
Strata objects: Legend and ColumnStrata is stratigraphic data.The main object of `strata` submodule is `mplStrater.strata.Column` which represents the single stratigraphic column.This example shows the structure of the class and how to use it.First, import all required packages and load the example dataset. | %load_ext autoreload
%autoreload 2
from mplStrater.data import StrataFrame
from mplStrater.strata import Column,Legend
import pandas as pd
import matplotlib.pyplot as plt
df=pd.read_csv("../../../data/example.csv")
df.head() | _____no_output_____ | MIT | docs/examples/strata.ipynb | giocaizzi/mplStrater |
Then, initiate a `mpl.StrataFrame` providing a `pandas.DataFrame` and specifying its `epsg` code. | sf=StrataFrame(
df=df,
epsg=32633) | _____no_output_____ | MIT | docs/examples/strata.ipynb | giocaizzi/mplStrater |
Define a `Legend`.This is done providing a dictionary containing pairs of (value-specification) the `fill_dict` parameter and for the `hatch_fill` parameter.The dictionary matches dataframe `fill` and `hatch` column values to either a *matplotlib encoded color* or *encoded hatch* string.The example uses the following ... | fill_dict={
'Terreno conforme': 'lightgreen',
'Riporto conforme': 'darkgreen',
'Riporto non conforme': 'orange',
'Rifiuto': 'red',
'Assenza campione': 'white'
}
hatch_dict={
'Non pericoloso': '',
'Pericoloso': 'xxxxxxxxx',
'_': ''
}
l=Legend(
fill_dict=fill_dict,
hatch_d... | _____no_output_____ | MIT | docs/examples/strata.ipynb | giocaizzi/mplStrater |
Plot stand-alone `Column` objectsImagine we would need to inspect closely a column. It's not sure that we would be able to clearly do it on the map with all other elements (labels, basemap...). Unless exporting the map in pdf with a high resolution, open the local file... would take sooo long! Therefore `Column` objec... | sf.strataframe[:3] | _____no_output_____ | MIT | docs/examples/strata.ipynb | giocaizzi/mplStrater |
Plot the first three columns contained in the `StrataFrame`. | #create figure
f,axes=plt.subplots(1,4,figsize=(5,3),dpi=200,frameon=False)
for ax,i in zip(axes,range(4)):
ax.axis('off')
#instantiate class
c=Column(
#figure
ax,l,
#id
sf.strataframe.loc[i,"ID"],
#coords
(0.9,0.9),
#scale
sf.strataframe.loc[i... | _____no_output_____ | MIT | docs/examples/strata.ipynb | giocaizzi/mplStrater |
Sometimes it is useful to take a random choice between two or more options.Numpy has a function for that, called `random.choice`: | import numpy as np | _____no_output_____ | CC-BY-4.0 | notebooks/10/random_choice.ipynb | matthew-brett/cfd-uob |
Say we want to choose randomly between 0 and 1. We want an equal probability of getting 0 and getting 1. We could do it like this: | np.random.randint(0, 2) | _____no_output_____ | CC-BY-4.0 | notebooks/10/random_choice.ipynb | matthew-brett/cfd-uob |
If we do that lots of times, we see that we have a roughly 50% chance of getting 0 (and therefore, a roughly 50% chance of getting 1). | # Make 10000 random numbers that can be 0 or 1, with equal probability.
lots_of_0_1 = np.random.randint(0, 2, size=10000)
# Count the proportion that are 1.
np.count_nonzero(lots_of_0_1) / 10000 | _____no_output_____ | CC-BY-4.0 | notebooks/10/random_choice.ipynb | matthew-brett/cfd-uob |
Run the cell above a few times to confirm you get numbers very close to 0.5. Another way of doing this is to use `np.random.choice`.As usual, check the arguments that the function expects with `np.random.choice?` in a notebook cell.The first argument is a sequence, like a list, with the options that Numpy should chose ... | np.random.choice([0, 1]) | _____no_output_____ | CC-BY-4.0 | notebooks/10/random_choice.ipynb | matthew-brett/cfd-uob |
A second `size` argument to the function says how many items to choose: | # Ten numbers, where each has a 50% chance of 0 and 50% chance of 1.
np.random.choice([0, 1], size=10) | _____no_output_____ | CC-BY-4.0 | notebooks/10/random_choice.ipynb | matthew-brett/cfd-uob |
By default, Numpy will chose each item in the sequence with equal probability, In this case, Numpy will chose 0 with 50% probability, and 1 with 50% probability: | # Use choice to make another 10000 random numbers that can be 0 or 1,
# with equal probability.
more_0_1 = np.random.choice([0, 1], size=10000)
# Count the proportion that are 1.
np.count_nonzero(more_0_1) / 10000 | _____no_output_____ | CC-BY-4.0 | notebooks/10/random_choice.ipynb | matthew-brett/cfd-uob |
If you want, you can change these proportions with the `p` argument: | # Use choice to make another 10000 random numbers that can be 0 or 1,
# where 0 has probability 0.25, and 1 has probability 0.75.
weighted_0_1 = np.random.choice([0, 1], size=10000, p=[0.25, 0.75])
# Count the proportion that are 1.
np.count_nonzero(weighted_0_1) / 10000 | _____no_output_____ | CC-BY-4.0 | notebooks/10/random_choice.ipynb | matthew-brett/cfd-uob |
There can be more than two choices: | # Use choice to make another 10000 random numbers that can be 0 or 10 or 20, or
# 30, where each has probability 0.25.
multi_nos = np.random.choice([0, 10, 20, 30], size=10000)
multi_nos[:10]
np.count_nonzero(multi_nos == 30) / 10000 | _____no_output_____ | CC-BY-4.0 | notebooks/10/random_choice.ipynb | matthew-brett/cfd-uob |
The choices don't have to be numbers: | np.random.choice(['Heads', 'Tails'], size=10) | _____no_output_____ | CC-BY-4.0 | notebooks/10/random_choice.ipynb | matthew-brett/cfd-uob |
You can also do choices *without replacement*, so once you have chosen an element, all subsequent choices cannot chose that element again. For example, this *must* return all the elements from the choices, but in random order: | np.random.choice([0, 10, 20, 30], size=4, replace=False) | _____no_output_____ | CC-BY-4.0 | notebooks/10/random_choice.ipynb | matthew-brett/cfd-uob |
Capsule Network In this notebook i will try to explain and implement Capsule Network. MNIST images will be used as an input. To implement capsule Network, we need to understand what are capsules first and what advantages do they have compared to convolutional neural network. so what are capsules?* Briefly explaining i... | # import resources
import numpy as np
import torch
# random seed (for reproducibility)
seed = 1
# set random seed for numpy
np.random.seed(seed)
# set random seed for pytorch
torch.manual_seed(seed)
from torchvision import datasets
import torchvision.transforms as transforms
# number of subprocesses to use for data l... | _____no_output_____ | MIT | Capsule_ network.ipynb | noureldinalaa/Capsule-Networks |
The nexts step is to create the convolutional layer as we explained: | import torch.nn as nn
import torch.nn.functional as F
class ConvLayer(nn.Module):
def __init__(self, in_channels=1, out_channels=256):
'''Constructs the ConvLayer with a specified input and output size.
These sizes has initial values from the paper.
param input_channel: input dep... | _____no_output_____ | MIT | Capsule_ network.ipynb | noureldinalaa/Capsule-Networks |
B)Primary capsules This layer is tricky but i will try to simplify it as much as i can.We would like to convolute the first layer to a new layer with 8 primary capsules.To do so we will follow Hinton's paper steps: - First step is to convolute our first Convolutional layer which has a dimension of (20 ,20 ,256) wit... | class PrimaryCaps(nn.Module):
def __init__(self, num_capsules=8, in_channels=256, out_channels=32):
'''Constructs a list of convolutional layers to be used in
creating capsule output vectors.
param num_capsules: number of capsules to create
param in_channels: input dep... | _____no_output_____ | MIT | Capsule_ network.ipynb | noureldinalaa/Capsule-Networks |
c)Digit capsules As we have 10 digit classes from 0 to 9, this layer will have 10 capsules each capsule is for one digit.Each capsule takes an input of a batch of 1152 dimensional vector while the output is a ten 16 dimnsional vector. Dynamic Routing Dynamic routing is used to find the best matching between the best... | def softmax(input_tensor, dim=1): # to get transpose softmax function # for multiplication reason s_J
# transpose input
transposed_input = input_tensor.transpose(dim, len(input_tensor.size()) - 1)
# calculate softmax
softmaxed_output = F.softmax(transposed_input.contiguous().view(-1, transposed_input.si... | _____no_output_____ | MIT | Capsule_ network.ipynb | noureldinalaa/Capsule-Networks |
After implementing the dynamic routing we are ready to implement the Digitcaps class,which consisits of :- This layer is composed of 10 "digit" capsules, one for each of our digit classes 0-9.- Each capsule takes, as input, a batch of 1152-dimensional vectors produced by our 8 primary capsules, above.- Each of these 10... | # it will also be relevant, in this model, to see if I can train on gpu
TRAIN_ON_GPU = torch.cuda.is_available()
if(TRAIN_ON_GPU):
print('Training on GPU!')
else:
print('Only CPU available')
class DigitCaps(nn.Module):
def __init__(self, num_capsules=10, previous_layer_nodes=32*6*6,
... | _____no_output_____ | MIT | Capsule_ network.ipynb | noureldinalaa/Capsule-Networks |
2)Decoder As shown in the following figure from [Hinton's paper(capsule networks orignal paper)](https://arxiv.org/pdf/1710.09829.pdf), The decoder is made of three fully-connected, linear layers. The first layer sees the 10, 16-dimensional output vectors from the digit capsule layer and produces hidden_dim=512 number... | class Decoder(nn.Module):
def __init__(self, input_vector_length=16, input_capsules=10, hidden_dim=512):
'''Constructs an series of linear layers + activations.
param input_vector_length: dimension of input capsule vector, default value = 16
param input_capsules: number of capsule... | _____no_output_____ | MIT | Capsule_ network.ipynb | noureldinalaa/Capsule-Networks |
Now let us collect all these layers (classes that we have created i.e ConvLayer,PrimaryCaps,DigitCaps,Decoder) in one class called CapsuleNetwork. | class CapsuleNetwork(nn.Module):
def __init__(self):
'''Constructs a complete Capsule Network.'''
super(CapsuleNetwork, self).__init__()
self.conv_layer = ConvLayer()
self.primary_capsules = PrimaryCaps()
self.digit_capsules = DigitCaps()
self.decoder = Decoder()... | _____no_output_____ | MIT | Capsule_ network.ipynb | noureldinalaa/Capsule-Networks |
Let us now instantiate the model and print it. | # instantiate and print net
capsule_net = CapsuleNetwork()
print(capsule_net)
# move model to GPU, if available
if TRAIN_ON_GPU:
capsule_net = capsule_net.cuda() | CapsuleNetwork(
(conv_layer): ConvLayer(
(conv): Conv2d(1, 256, kernel_size=(9, 9), stride=(1, 1))
)
(primary_capsules): PrimaryCaps(
(capsules): ModuleList(
(0): Conv2d(256, 32, kernel_size=(9, 9), stride=(2, 2))
(1): Conv2d(256, 32, kernel_size=(9, 9), stride=(2, 2))
(2): Conv2d(256, 3... | MIT | Capsule_ network.ipynb | noureldinalaa/Capsule-Networks |
Loss The loss for a capsule network is a weighted combination of two losses:1. Reconstraction loss2. Margin loss Reconstraction Loss - It checks how the reconstracted image which we get from the decoder diferent from the original input image.- It is calculated using mean squared error which is nn.MSELoss in pytorch.-... | from IPython.display import Image
Image(filename='images/margin_loss.png') | _____no_output_____ | MIT | Capsule_ network.ipynb | noureldinalaa/Capsule-Networks |
Margin Loss is a classification loss (we can think of it as cross entropy) which is based on the length of the output vectors coming from the DigitCaps layer.so let us try to elaborate it more on our example.Let us say we have an output vector called (x) coming from the digitcap layer, this ouput vector represents a ce... | class CapsuleLoss(nn.Module):
def __init__(self):
'''Constructs a CapsuleLoss module.'''
super(CapsuleLoss, self).__init__()
self.reconstruction_loss = nn.MSELoss(reduction='sum') # cumulative loss, equiv to size_average=False
def forward(self, x, labels, images, reconstructions):
... | _____no_output_____ | MIT | Capsule_ network.ipynb | noureldinalaa/Capsule-Networks |
Now we have to call the custom loss class we have implemented and we will use Adam optimizer as in the paper. | import torch.optim as optim
# custom loss
criterion = CapsuleLoss()
# Adam optimizer with default params
optimizer = optim.Adam(capsule_net.parameters()) | _____no_output_____ | MIT | Capsule_ network.ipynb | noureldinalaa/Capsule-Networks |
Train the network So the normal steps to do the training from a batch of data:1. Clear the gradients of all optimized variables, by making them zero.2. Forward pass: compute predicted outputs by passing inputs to the model3. Calculate the loss .4. Backward pass: compute gradient of the loss with respect to model param... | def train(capsule_net, criterion, optimizer,
n_epochs, print_every=300):
'''Trains a capsule network and prints out training batch loss statistics.
Saves model parameters if *validation* loss has decreased.
param capsule_net: trained capsule network
param criterion: capsule loss func... | Epoch: 1 Training Loss: 0.25108408
Epoch: 1 Training Loss: 0.09796484
Epoch: 1 Training Loss: 0.07615296
Epoch: 1 Training Loss: 0.06122471
Epoch: 1 Training Loss: 0.05977095
Epoch: 1 Training Loss: 0.05478950
Epoch: 1 Training Loss: 0.05140611
Epoch: 1 Training Loss: 0.05044698
Epoch: 1 Training Loss: 0.04870... | MIT | Capsule_ network.ipynb | noureldinalaa/Capsule-Networks |
Now let us plot the training loss to get more feeling how does the loss look like: | import matplotlib.pyplot as plt
%matplotlib inline
plt.plot(losses)
plt.title("Training Loss")
plt.show() | _____no_output_____ | MIT | Capsule_ network.ipynb | noureldinalaa/Capsule-Networks |
Test the trained network Test the trained network on unseen data: | def test(capsule_net, test_loader):
'''Prints out test statistics for a given capsule net.
param capsule_net: trained capsule network
param test_loader: test dataloader
return: returns last batch of test image data and corresponding reconstructions
'''
class_correct = list(0. for i i... | Test Loss: 0.03073818
Test Accuracy of 0: 99% (975/980)
Test Accuracy of 1: 99% (1132/1135)
Test Accuracy of 2: 99% (1027/1032)
Test Accuracy of 3: 99% (1001/1010)
Test Accuracy of 4: 98% (971/982)
Test Accuracy of 5: 99% (886/892)
Test Accuracy of 6: 98% (947/958)
Test Accuracy of 7: 9... | MIT | Capsule_ network.ipynb | noureldinalaa/Capsule-Networks |
Now it is time to dispaly the reconstructions: | def display_images(images, reconstructions):
'''Plot one row of original MNIST images and another row (below)
of their reconstructions.'''
# convert to numpy images
images = images.data.cpu().numpy()
reconstructions = reconstructions.view(-1, 1, 28, 28)
reconstructions = reconstructions.data... | _____no_output_____ | MIT | Capsule_ network.ipynb | noureldinalaa/Capsule-Networks |
Monte Carlo ControlSo far, we assumed that we know the underlying model of the environment and that the agent has access to it. Now, we considere the case in which do not have access to the full MDP. That is, we do __model-free control__ now.To illustrate this, we implement the black jack example from the RL Lecture 5... | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import plotting
from operator import itemgetter
plotting.set_layout(drawing_size=15)
| _____no_output_____ | MIT | Lecture 5 Monte-Carlo Control.ipynb | oesst/rl_lecture_examples |
The EnvironmentFor this example we use the python package [gym](https://gym.openai.com/docs/) which provides a ready-to-use implementation of a BlackJack environment.The states are stored in this tuple format: \n(Agent's score , Dealer's visible score, and whether or not the agent has a usable ace)Here, we can look at... | import gym
env = gym.make('Blackjack-v0')
env.observation_space | _____no_output_____ | MIT | Lecture 5 Monte-Carlo Control.ipynb | oesst/rl_lecture_examples |
And the number of actions we can take: | env.action_space | _____no_output_____ | MIT | Lecture 5 Monte-Carlo Control.ipynb | oesst/rl_lecture_examples |
To start a game call `env.reset()` which will return the obersavtion space | env.reset() | _____no_output_____ | MIT | Lecture 5 Monte-Carlo Control.ipynb | oesst/rl_lecture_examples |
We can take two different actions: `hit` = 1 or `stay` = 0. The result of this function call shows the _obersavtion space_, the reward (winning=+1, loosing =-1) and if the game is over, | env.step(1) | _____no_output_____ | MIT | Lecture 5 Monte-Carlo Control.ipynb | oesst/rl_lecture_examples |
Define the Agent |
class agents():
""" This class defines the agent
"""
def __init__(self, state_space, action_space, ):
""" TODO """
# Store the discount factor
self.gamma = 0.7
# Store the epsilon parameters
self.epsilon = 1
n_player_states = state_s... | _____no_output_____ | MIT | Lecture 5 Monte-Carlo Control.ipynb | oesst/rl_lecture_examples |
Plotting | fig = plt.figure(figsize=(10,5))
axes = fig.subplots(1,2,squeeze=False)
ax = axes[0,0]
c = ax.pcolormesh(agent.q[13:22,1:,0,:].max(2),vmin=-1,vmax=1)
ax.set_yticklabels(range(13,22))
ax.set_xticklabels(range(1,11,2))
ax.set_xlabel('Dealer Showing')
ax.set_ylabel('Player Sum')
ax.set_title('No Usable Aces')
# plt.co... | <ipython-input-41-ea3605012f37>:9: UserWarning: FixedFormatter should only be used together with FixedLocator
ax.set_yticklabels(range(13,22))
<ipython-input-41-ea3605012f37>:10: UserWarning: FixedFormatter should only be used together with FixedLocator
ax.set_xticklabels(range(1,11,2))
<ipython-input-41-ea3605012f... | MIT | Lecture 5 Monte-Carlo Control.ipynb | oesst/rl_lecture_examples |
Azure Functions での展開用に Auto MLで作成したファイル群を Container 化する参考:Azure Functions に機械学習モデルをデプロイする (プレビュー)https://docs.microsoft.com/ja-jp/azure/machine-learning/how-to-deploy-functions | #!pip install azureml-contrib-functions | _____no_output_____ | MIT | 4.AML-Functions-notebook/AML-AzureFunctionsPackager.ipynb | dahatake/Azure-Machine-Learning-sample |
Azure Machine Learnig ワークスペースへの接続 | from azureml.core import Workspace, Dataset
subscription_id = '<your azure subscription id>'
resource_group = '<your resource group>'
workspace_name = '<your azure machine learning workspace name>'
ws = Workspace(subscription_id, resource_group, workspace_name)
modelfilespath = 'AutoML1bb3ebb0477' | _____no_output_____ | MIT | 4.AML-Functions-notebook/AML-AzureFunctionsPackager.ipynb | dahatake/Azure-Machine-Learning-sample |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.