arranp
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    --- tags: AWS Network Firewall, Networking, AWS, Workshop --- # Time series forecasting with AWS services This is our list of hints and tips for this workshop. **JOIN EVENT:** https://catalog.workshops.aws/join 1. Complete OTP to an email address (Any that you can access over public internet) 2. **Code will be on the TV** screen for you to type. 3. Read "Terms and Conditions", select "**I agree with the Terms and Conditions**" and click "**Join event**". 4. On the next page, click "**Open AWS Console**" URL link. ![](https://hackmd.io/_uploads/SycdQF8P3.png) 3. **Skip the entire sections**: "Introduction" & "Setup" *this is already done!* 4. Go straight to the first lab [**Overview of the Environment**](https://catalog.us-east-1.prod.workshops.aws/workshops/caef4710-3721-4957-a2ce-33799920ef72/en-US/20-environmentsetup/23-overviewoftheenvironment) :::info :warning: **For this workshop resources are deployed in us-west-2** ::: ## Forecast Messaging For those seeking a UI-centric forecasting experience, the Canvas UI, which comes integrated with the Canvas (Autopilot) APIs, is highly recommended. It streamlines data integration, model training, and prediction processes, establishing itself as an essential tool for data-driven decision-making. Building forecasting models with the Canvas APIs offer the following key advantages over the Amazon Forecast service APIs: 1. **Better Performance**: * On average, building ML models with the Autopilot API is up to 50% faster than with the Amazon Forecast API. * Inference on these models is up to 45% faster. 1. **Lower Cost**: * Deploying the AP-generated model on a SageMaker inference instance for predictions is more cost-effective. In fact, using SageMaker Inference can be over 90% cheaper than using Amazon Forecast. 1. **Enhanced Control**: * When building a model with AP APIs: **a/** You gain visibility into the algorithms selected in the ensemble. **b/** You have the option to deploy either the ensemble model or a model created by an individual algorithm. **c/** You can choose any desired inference instance configuration (recommended instances are detailed in the document) to suit your use case. 1. **Wider Availability**: * Compared to Amazon Forecast, AP APIs are available in 8 additional regions: Asia Pacific (Hong Kong); Canada (Central); Europe (London); Europe (Paris); Europe (Stockholm); Middle East (Bahrain); South America (Sao Paulo); and US West (N. California). The AP API will be accessible in all regions where Autopilot currently operates or will operate in the future. # Key Concepts There are 3 key services for time series forecasting. 1. **No-code approach with SageMaker Canvas** 1. **Programmatic approach with SageMaker Autopilot**: 1. **Build custom model with SageMaker** ## Workshop briefing In this workshop, the hands on labs will cover different ways of forecasting with AWS Services such as Amazon Forecast, Amazon Canvas, and Amazon sageMaker. The session provides prescriptive guidance around choosing the right AWS service for your use case. * 3 labs, one for each of the 3 approaches discussed. * All workshops goes through the ML lifecycle of processing, training and interference. * Model training is time consuming. So please switch to next lab after starting the training process as per workshop instructions. * SageMaker Studio Jupyter Notebook kernel may take couple of minutes to initialize. * It is suggested to execute SageMaker Studio Notebooks by each cell to understand the flow. # Time-Series Forecasting with Amazon SageMaker Autopilot Import the SageMaker Python library and start a session. ```python= import sagemaker # This is the client we will use to interact with SageMaker Autopilot sm = boto3.Session().client(service_name="sagemaker", region_name=region) ``` [**automl_problem_type_config**](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_TimeSeriesForecastingJobConfig.html) The collection of settings used by an AutoML job V2 for the time-series forecasting problem type. ```python= automl_problem_type_config ={ 'TimeSeriesForecastingJobConfig': { 'ForecastFrequency': 'M', 'ForecastHorizon': 2, 'ForecastQuantiles': ['p50','p60','p70','p80','p90'], 'Transformations': { 'Filling': { 'demand': { 'middlefill' : 'zero', 'backfill' : 'zero' }, 'price': { 'middlefill' : 'zero', 'backfill' : 'zero', 'futurefill' : 'zero' } } }, 'TimeSeriesConfig': { 'TargetAttributeName': 'demand', 'TimestampAttributeName': 'ts', 'ItemIdentifierAttributeName': 'item_id', 'GroupingAttributeNames': [ 'store_id' ] } } } ``` [**Creates an Autopilot job also referred to as Autopilot experiment or AutoML job V2**](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker/client/create_auto_ml_job_v2.html#) You can find the best-performing model after you run an AutoML job V2 by calling DescribeAutoMLJobV2. ```python= sm.create_auto_ml_job_v2( AutoMLJobName=auto_ml_job_name, AutoMLJobInputDataConfig=input_data_config, OutputDataConfig=output_data_config, AutoMLProblemTypeConfig = automl_problem_type_config, AutoMLJobObjective=optimizaton_metric_config, RoleArn=role ) ``` [**create_model**](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker/client/create_model.html#create-model) Creates a model in SageMaker. In the request, you name the model and describe a primary container. For the primary container, you specify the Docker image that contains inference code, artifacts (from prior training), and a custom environment map that the inference code uses when you deploy the model for predictions. Use this API to create a model if you want to use SageMaker hosting services or run a batch transform job. ```python= best_candidate = sm.describe_auto_ml_job_v2(AutoMLJobName=auto_ml_job_name)['BestCandidate'] best_candidate_containers = best_candidate['InferenceContainers'] best_candidate_name = best_candidate['CandidateName'] reponse = sm.create_model( ModelName = best_candidate_name, ExecutionRoleArn = role, Containers = best_candidate_containers ) print('BestCandidateName:',best_candidate_name) print('BestCandidateContainers:',best_candidate_containers) ``` [**create_transform_job**](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker/client/create_transform_job.html#create-transform-job) Starts a transform job. A transform job uses a trained model to get inferences on a dataset and saves these results to an Amazon S3 location that you specify. To perform batch transformations, you create a transform job and use the data that you have readily available. ```python= response = sm.create_transform_job( TransformJobName=transform_job_name, ModelName=best_candidate_name, MaxPayloadInMB=0, ModelClientConfig={ 'InvocationsTimeoutInSeconds': 3600 }, TransformInput={ 'DataSource': { 'S3DataSource': { 'S3DataType': 'S3Prefix', 'S3Uri': 's3://{}/{}/batch_transform/input/'.format(bucket, prefix) } }, 'ContentType': 'text/csv', 'SplitType': 'None' }, TransformOutput={ 'S3OutputPath': 's3://{}/{}/batch_transform/output/'.format(bucket, prefix), 'AssembleWith': 'Line', }, TransformResources={ 'InstanceType': 'ml.m5.4xlarge', 'InstanceCount': 1 } ) ``` # Custom SageMaker/DeepAR This notebook complements the [DeepAR introduction notebook](https://github.com/awslabs/amazon-sagemaker-examples/blob/master/introduction_to_amazon_algorithms/deepar_synthetic/deepar_synthetic.ipynb). Here, we will consider a real use case and show how to use DeepAR on SageMaker for predicting energy consumption of 370 customers over time, based on a [dataset](https://archive.ics.uci.edu/ml/datasets/ElectricityLoadDiagrams20112014) that was used in the academic papers [[1](https://media.nips.cc/nipsbooks/nipspapers/paper_files/nips29/reviews/526.html)] and [[2](https://arxiv.org/abs/1704.04110)]. In particular, we will see how to: * Prepare the dataset * Use the SageMaker Python SDK to train a DeepAR model and deploy it * Make requests to the deployed model to obtain forecasts interactively * Illustrate advanced features of DeepAR: missing values, additional time features, non-regular frequencies and category information ### Import electricity dataset and upload it to S3 to make it available for Sagemaker We load and parse the dataset and convert it to a collection of Pandas time series, which makes common time series operations such as indexing by time periods or resampling much easier. The data is originally recorded in 15min interval, which we could use directly. Here we want to forecast longer periods (one week) and resample the data to a granularity of 2 hours. ### Train and Test splits Often times one is interested in evaluating the model or tuning its hyperparameters by looking at error metrics on a hold-out test set. Here we split the available data into train and test sets for evaluating the trained model. For standard machine learning tasks such as classification and regression, one typically obtains this split by randomly separating examples into train and test sets. However, in forecasting it is important to do this train/test split based on time rather than by time series. In this example, we will reserve the last section of each of the time series for evalutation purpose and use only the first part as training data. ```python-= start_dataset = pd.Timestamp("2014-01-01 00:00:00", freq=freq) end_training = pd.Timestamp("2014-09-01 00:00:00", freq=freq) ``` Error! ``` --------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[15], line 1 ----> 1 start_dataset = pd.Timestamp("2014-01-01 00:00:00", freq=freq) 2 end_training = pd.Timestamp("2014-09-01 00:00:00", freq=freq) File timestamps.pyx:1755, in pandas._libs.tslibs.timestamps.Timestamp.__new__() TypeError: __new__() got an unexpected keyword argument 'freq' ``` Update ```python= start_dataset = pd.Timestamp("2014-01-01 00:00:00") end_training = pd.Timestamp("2014-09-01 00:00:00") # Now, when you create a date range, you can specify the frequency date_range = pd.date_range(start=start_dataset, periods=(end_training - start_dataset).days * 12, freq=freq) print(date_range) ``` ### Train a model Here we define and then will launch the training job. (estimate 21 minutes) ### Create endpoint and predictor We have a trained model, we can use it to perform predictions by deploying it to an endpoint. ## Links [Speed up your time series forecasting by up to 50 percent with Amazon SageMaker Canvas UI and AutoML APIs](https://aws.amazon.com/blogs/machine-learning/speed-up-your-time-series-forecasting-by-up-to-50-percent-with-amazon-sagemaker-canvas-ui-and-automl-apis/) [Time-Series Forecasting with Amazon SageMaker Autopilot](https://github.com/aws/amazon-sagemaker-examples/blob/main/autopilot/autopilot_time_series.ipynb) ![image](https://hackmd.io/_uploads/SkH11RBpT.png) ## Follow up ### Working with Quantiles Time-series quantile selection example https://github.com/aws/amazon-sagemaker-examples/tree/main/sagemaker-datawrangler/timeseries-quantile-selection-dataflow Beyond forecasting: The delicate balance of serving customers and growing your business https://aws.amazon.com/blogs/machine-learning/beyond-forecasting-the-delicate-balance-of-serving-customers-and-growing-your-business/

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully