hongbo-miao/hongbomiao.com

View on GitHub
cloud-platform/aws/amazon-sagemaker/pytorch-mnist/notebook.ipynb

Summary

Maintainability
Test Coverage
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-python-sdk/pytorch_mnist/pytorch_mnist.html\n",
    "\n",
    "import gzip\n",
    "import os\n",
    "import random\n",
    "import time\n",
    "\n",
    "import numpy as np\n",
    "import sagemaker\n",
    "import torchvision\n",
    "from sagemaker.pytorch import PyTorch\n",
    "\n",
    "experiment_name = \"amazon-sagemaker-pytorch-mnist\"\n",
    "sagemaker_session = sagemaker.Session()\n",
    "s3_bucket = sagemaker_session.default_bucket()\n",
    "iam_role_irn = sagemaker.get_execution_role()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Get the data\n",
    "torchvision.datasets.MNIST(\n",
    "    \"data/\",\n",
    "    download=True,\n",
    "    transform=torchvision.transforms.Compose(\n",
    "        [\n",
    "            torchvision.transforms.transforms.ToTensor(),\n",
    "            torchvision.transforms.transforms.Normalize((0.1307,), (0.3081,)),\n",
    "        ]\n",
    "    ),\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Upload the data to S3\n",
    "data_s3_uri = sagemaker_session.upload_data(\n",
    "    path=\"data/\", bucket=s3_bucket, key_prefix=f\"{experiment_name}-data\"\n",
    ")\n",
    "print(data_s3_uri)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Train\n",
    "estimator = PyTorch(\n",
    "    source_dir=\"src/\",\n",
    "    entry_point=\"main.py\",\n",
    "    role=iam_role_irn,\n",
    "    py_version=\"py310\",\n",
    "    framework_version=\"2.0.0\",\n",
    "    instance_count=2,\n",
    "    instance_type=\"ml.c5.2xlarge\",\n",
    "    hyperparameters={\"epochs\": 1, \"backend\": \"gloo\"},\n",
    ")\n",
    "estimator.fit(\n",
    "    inputs={\"training\": data_s3_uri},\n",
    "    job_name=f\"{experiment_name}-job-{int(time.time())}\",\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Deploy\n",
    "predictor = estimator.deploy(\n",
    "    initial_instance_count=1,\n",
    "    instance_type=\"ml.m5.xlarge\",\n",
    "    model_name=f\"{experiment_name}-model-{int(time.time())}\",\n",
    "    endpoint_name=f\"{experiment_name}-endpoint-{int(time.time())}\",\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Evaluate\n",
    "data_dir = \"data/MNIST/raw\"\n",
    "path = os.path.join(data_dir, \"t10k-images-idx3-ubyte.gz\")\n",
    "with gzip.open(path, \"rb\") as f:\n",
    "    images = (\n",
    "        np.frombuffer(f.read(), np.uint8, offset=16)\n",
    "        .reshape(-1, 28, 28)\n",
    "        .astype(np.float32)\n",
    "    )\n",
    "\n",
    "# Randomly select some of the test images\n",
    "mask = random.sample(range(len(images)), 16)\n",
    "mask = np.array(mask, dtype=np.int_)\n",
    "data = images[mask]\n",
    "\n",
    "response = predictor.predict(np.expand_dims(data, axis=1))\n",
    "print(\"Raw prediction result:\", response)\n",
    "\n",
    "labeled_predictions = list(zip(range(10), response[0]))\n",
    "print(\"Labeled predictions:\", labeled_predictions)\n",
    "\n",
    "labeled_predictions.sort(key=lambda label_and_prob: 1.0 - label_and_prob[1])\n",
    "print(\"Most likely answer:\", labeled_predictions[0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Clean up\n",
    "sagemaker_session.delete_endpoint(endpoint_name=predictor.endpoint_name)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (PyTorch 1.13 Python 3.9 CPU Optimized)",
   "language": "python",
   "name": "python3__SAGEMAKER_INTERNAL__arn:aws:sagemaker:us-west-2:236514542706:image/pytorch-1.13-cpu-py39"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2"
  },
  "notice": "Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.  Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the \"license\" file accompanying this file. This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License."
 },
 "nbformat": 4,
 "nbformat_minor": 4
}