Skip to content

アプリケーション内で をクリックすると、お使いのDataRobotバージョンに関する全プラットフォームドキュメントにアクセスできます。

DataRobot予測API

このセクションでは、DataRobotの予測APIを使用して、専用予測サーバーで予測を作成する方法について説明します。 予測APIリファレンスドキュメントが必要な場合は、こちらから入手できます。

DataRobotの予測APIは(デプロイIDを指定することによって)モデルデプロイ上で予測を作成する場合に使用できます。 This provides access to advanced model management features like target or data drift detection. DataRobotのモデルマネジメント機能は予測APIから安全に分離されているので、予測の速度や信頼性を損なうことなくメリットを活用できます。 See the deployment section for details on creating a model deployment.

予測APIで予測を生成する前に、予測を最も高速に実行するために推奨されるベストプラクティスを参照してください。

予測を作成する

予測APIを使用して新しいデータで予測を作成するには、次のものが必要です。

  • モデルのデプロイID。 IDは、デプロイ > 予測 > 予測APIタブのサンプルコード出力にあります(インターフェイスは「APIクライアント」に設定されています)。
  • APIキー

注意

モデルがオープンソースのRスクリプトの場合、実行速度は著しく遅くなります。

予測リクエストがPOSTリクエストとしてリソースに対して送信されます。次に例を示します。

curl -i -X POST "https://example.datarobot.com/predApi/v1.0/deployments/<deploymentId>/predictions" \
    -H "Authorization: Bearer <API key>" -F \
    file=@~/.home/path/to/dataset.csv 

本機能の提供について

マネージドAIプラットフォームユーザーの場合は、datarobot-keyをCurlヘッダーに含める必要があります(curl -H "Content-Type: application/json", -H "datarobot-key: xxxx"など)。 予測 > 予測APIタブでシークレットを表示するか、DataRobotの担当者に連絡してキーを見つけます。

予測応答行の順序は、送信されたデータの順序と同じです。

この応答は次のようになります。

HTTP/1.1 200 OK
Content-Type: application/json
X-DataRobot-Execution-Time: 38
X-DataRobot-Model-Cache-Hit: true

{"data":[...]} 

備考

上記の例では、予測API URLとして便宜的なホスト名(example.datarobot.com)が使用されています。実際に使用する場合は、専用予測サーバーの正しいホスト名を使用してください。 デプロイ > 予測 > 予測APIタブの同じコードに設定済みの(予測)URLが表示されます。 不明な点がある場合は、システム管理者に問い合わせてください。

永続的HTTP接続の使用

すべての予測リクエストは安全な接続(SSL/TLS)を介して行われるので、接続のセットアップ時間が長くなることがあります。 この時間は、予測インスタンスへのネットワークレイテンシーに応じて 30msから100~150msです。

この問題への対処として、予測APIでHTTP Keep-Aliveがサポートされていて、最後の予測リクエストの後、最大1分間システムで接続を開いたままにしておくことができます。

Pythonのrequestsモジュールを使用して、requests.Sessionから予測リクエストを実行します。

import json
import requests

data = [
    json.dumps({'Feature1': 42, 'Feature2': 'text value 1'}),
    json.dumps({'Feature1': 60, 'Feature2': 'text value 2'}),
]

api_key = '...'
api_endpoint = '...'

session = requests.Session()
session.headers = {
    'Authorization': 'Bearer {}'.format(api_key),
    'Content-Type': 'text/json',
}

for row in data:
    print(session.post(api_endpoint, data=row).json()) 

現在の統合で持続的接続(パーシステントコネクション)を使用する方法については、使用するHTTPライブラリのドキュメントを参照してください。

予測入力

APIは、JSONとCSVの両方の形式の入力データをサポートします(高品質のJSONパーサーで作成されている場合はJSONの使用が推奨されます)。 データは、リクエストボディまたはファイルアップロード(マルチパートフォーム)を介してポストすることができます。

備考

予測APIを使用する場合、CSVファイルとリクエスト本文でサポートされる列区切りはコンマ(,)だけです

JSON入力

JSON入力は、キーが特徴量名で、値がデータセット内の値となるオブジェクト配列としてフォーマットされています。

たとえば、CSVファイルで以下のように表示されている場合:

a,b,c
1,2,3
7,8,9 

JSONの場合は以下のように表示されます。

[
  {
    "a": 1,
    "b": 2,
    "c": 3
  },
  {
    "a": 7,
    "b": 8,
    "c": 9
  }
] 

データを/predApi/v1.0/deployments/<deploymentId>/predictionsエンドポイントに送信して、JSON配列を予測APIにサブミットします。 例:

curl -H "Content-Type: application/json" -X POST --data '[{"a": 4, "b": 5, "c": 6}\]' \
    -H "Authorization: Bearer <API key>" \
    https://example.datarobot.com/predApi/v1.0/deployments/<deploymentId>/predictions 

ファイル入力

この例では、ヘッダーと予測を行うデータの行を含むCSVファイルdataset.csvを使用します。 コンテンツタイプはURLによって自動的に設定されます。

curl -i -X POST "https://example.datarobot.com/predApi/v1.0/deployments/<deploymentId>/predictions" \
    -H "Authorization: Bearer <API key>" -F \
    file=@~/.home/path/to/dataset.csv

HTTP/1.1 200 OK
Date: Fri, 08 Feb 2019 10:00:00 GMT
Content-Type: application/json
Content-Length: 60624
Connection: keep-alive
Server: nginx/1.12.2
X-DataRobot-Execution-Time: 39
X-DataRobot-Model-Cache-Hit: true
Access-Control-Allow-Methods: OPTIONS, POST
Access-Control-Allow-Credentials: true
Access-Control-Expose-Headers: Content-Type,Content-Length,X-DataRobot-Execution-Time,X-DataRobot-Model-Cache-Hit,X-DataRobot-Model-Id,X-DataRobot-Request-Id
Access-Control-Allow-Headers: Content-Type,Authorization,datarobot-key
X-DataRobot-Request-ID: 9e61f97bf07903b8c526f4eb47830a86

{
  "data": [
    {
      "predictionValues": [
        {
          "value": 0.2570950924,
          "label": 1
        },
        {
          "value": 0.7429049076,
          "label": 0
        }
      ],
      "predictionThreshold": 0.5,
      "prediction": 0,
      "rowId": 0
    },
    {
      "predictionValues": [
        {
          "value": 0.7631880558,
          "label": 1
        },
        {
          "value": 0.2368119442,
          "label": 0
        }
      ],
      "predictionThreshold": 0.5,
      "prediction": 1,
      "rowId": 1
    }
  ]
} 

インボディテキスト入力

この例には、リクエストボディ内にCSVファイルが含まれます。 この形式では、フォームデータのContent-Typeをtext/plainに設定する必要があります。

curl  -i -X POST "https://example.datarobot.com/predApi/v1.0/deployments/<deploymentId>/predictions"  --data-binary $'a,b,c\n1,2,3\n7,8,9\n'
    -H "content-type: text/plain" \
    -H "Authorization: Bearer <API key>" \ 

予測出力

コンテンツタイプのヘッダー値は、送信されるデータのタイプ(text/csvまたはapplication/json)に合わせて適切に設定する必要があります。元のAPIリクエストは常にJSONで応答します。 リアルタイム予測でJSONの代わりにCSVを返すには、-H "Accept: text/csv"を使用します。

予測オブジェクト

以下のセクションでは、さまざまな予測オブジェクトのコンテンツについて説明します。

リクエストスキーマ

リクエストスキーマは、すべての種類の予測の標準です。 使用可能なヘッダーを以下に示します。

名前
Content-Type text/csv;charset=utf8
  application/json
  multipart/form-data
Content-Encoding gzip
  bz2
Authorization ベアラー

以下の点に注意してください。

  • データの元のストリームとして予測を送信する場合、;charset=<encoding>Content-Typeヘッダーに追加してエンコーディングを指定できます。 有効な値の一覧については、Pythonの標準エンコーディングを参照してください。 DataRobotでは、デフォルトでutf8が使用されます。

  • データのエンコード済みストリームを送信する場合は、 Content-Encodingヘッダーを指定する必要があります。

  • Authorizationフィールドは、ベアラートークンと呼ばれるセキュリティトークンに関連するBearer認証HTTP ユーザー名 + APIトークン(基本認証)またはAPIトークンのみでも認証できますが、これらの認証方法は廃止されているので推奨されません。

URIクエリーパラメーターを使用してリクエストをパラメーター化することができます。

パラメーター名 タイプ 備考
passthroughColumns 文字列 予測応答でスコアリングデータセットから返す列のリスト。
passthroughColumnsSet 文字列 passthroughColumnsSet=allが渡された場合、スコアリングデータセットのすべての列が予測応答で返されます。

以下の点に注意してください。

  • passthroughColumnsおよびpassthroughColumnsSetパラメーターの両方を同じリクエストで渡すことはできません。
  • passthroughColumnsクエリーパラメーターで渡すことのできる列名の数に制限はありませんが、HTTPリクエストラインの制限があります(現在の制限は8192バイト)。

次の例は、複数のパススルー列の使用を示しています。

curl -i -X POST "https://example.datarobot.com/predApi/v1.0/deployments/<deploymentId>/predictions?passthroughColumns=Latitude&passthroughColumns=Longitude" \
    -H "Authorization: Bearer <API key>" \
    -H "datarobot-key: <DataRobot key>" -F \
    file=@~/.home/path/to/dataset.csv 

応答スキーム

The following is a sample prediction response body (also see the additional example of a time series response body):

{
  "data": [
    {
      "predictionValues": [
        {
          "value": 0.6856798909,
          "label": 1
        },
        {
          "value": 0.3143201091,
          "label": 0
        }
      ],
      "predictionThreshold": 0.5,
      "prediction": 1,
      "rowId": 0,
      "passthroughValues": {
        "Latitude": -25.433508,
        "Longitude": 22.759397
      }
    },
    {
      "predictionValues": [
        {
          "value": 0.765656753,
          "label": 1
        },
        {
          "value": 0.234343247,
          "label": 0
        }
      ],
      "predictionThreshold": 0.5,
      "prediction": 1,
      "rowId": 1,
      "passthroughValues": {
        "Latitude": 41.051128,
        "Longitude": 14.49598
      }
    }
  ]
} 

次の表にDataRobotのカスタムヘッダーの一覧を示します。

名前 備考
X-DataRobot-Execution-Time 数値 予測の計算時間(ミリ秒)。
X-DataRobot-Model-Cache-Hit trueまたはfalse モデルのインメモリーの有無(ブール型)。
X-DataRobot-Model-Id ObjectId 予測リクエストに使用するモデルのID(モデル展開で行われた予測に対してのみ返されます)。
X-DataRobot-Request-Id uuid 予測リクエストの一意の識別子。

以下の表にJSON配列の応答予測行を示します。

名前 タイプ 備考
predictionValues array An array of predictionValues (schema described below).
predictionThreshold 浮動小数 予測に対して使用されるしきい値(二値分類プロジェクトのみ)。
prediction 浮動小数 この行のモデルの出力。
rowId 整数 説明された行。
passthroughValues object JSONオブジェクト(キーが列名で、はスコアリングデータセットから予測された行の対応する値)。 このJSON項目はpassthroughColumnsまたはpassthroughColumnsSetのいずれかが渡された場合にのみ返されます。
adjustedPrediction 浮動小数 エクスポージャーがモデル構築で使用された場合、この行に対するこのモデルのエクスポージャーを調整した出力。 リクエストパラメーターexcludeAdjustedPredictionsがFalseの場合、adjustedPredictionは応答に含まれます。
adjustedPredictionValues array エクスポージャー調整されたPredictionValueの配列(スキーマについては以下を参照)。 リクエストパラメーターexcludeAdjustedPredictionsがfalseの場合、adjustedPredictionValuesは応答に含まれます。
predictionExplanations array PredictionExplanationsの配列(スキーマについては以下を参照)。 このJSON項目は、予測の説明と共にのみ返されます。

Prediction values schema

The following table describes the predictionValues schema in the JSON Response array:

名前 タイプ 備考
ラベル - モデル出力に対応するものを示します。 連続値プロジェクトの場合、これはターゲット特徴量の名前です。 分類プロジェクトの場合、これはターゲット特徴量のラベルです。
value 浮動小数 予測の出力。 連続値プロジェクトの場合、これはターゲットの予測値です。 分類プロジェクトの場合、最も確率が高いと予測されるのはラベルに関連付けられた確率です(二値分類問題において0.5のしきい値となります)。

Extra custom model output schema

本機能の提供について

カスタムモデルの予測レスポンスの追加出力は、デフォルトではオフになっています。 この機能を有効にする方法については、DataRobotの担当者または管理者にお問い合わせください。

機能フラグ:予測応答で追加のカスタムモデル出力を有効にする

In some cases, the prediction response from your model may contain extra model output. This is possible for custom models with additional output columns defined in the score() hook and for Generative AI (GenAI) models. score()フックは、stringintfloatbool、またはdatetime型のデータを含む追加の列を数に制限なく返すことができます。 追加の列がscore()メソッドによって返される場合、予測応答は次のようになります。

  • 表形式の応答(CSV)の場合、追加の列は応答テーブルまたはデータフレームの一部として返されます。
  • JSON応答の場合extraModelOutputキーが各行と一緒に返されます。 このキーは、行内の各追加列の値を含むディクショナリです。

As custom models, deployed GenAI models can return extra columns through the extraModelOutput key to provide information about the text generation model (citations, latency, confidence, LLM blueprint ID, token counts, etc.), as shown in the example below:

Citations in prediction response

For citations to be included in a Gen AI model's prediction response, the LLM deployed from the playground must have a vector database (VDB) associated with it.

JSON response for GenAI model predictions
{
    "data": [
        {
            "rowId": 0,
            "prediction": "In the field of biology, there have been some exciting new discoveries made through research conducted on the International Space Station (ISS). Here are three examples:\n\n1. Understanding Plant Root Orientation: Scientists have been studying the growth and development of plants in microgravity. They found that plants grown in space exhibit different root orientation compared to those grown on Earth. This discovery helps us understand how plants adapt and respond to the absence of gravity. This knowledge can be applied to improve agricultural practices and develop innovative techniques for growing plants in challenging environments on Earth.\n\n2. Tissue Damage and Repair: One fascinating area of research on the ISS involves studying how living organisms respond to injuries in space. Scientists have investigated tissue damage and repair mechanisms in various organisms, including humans. By studying the healing processes in microgravity, researchers gained insights into how wounds heal differently in space compared to on Earth. This knowledge has implications for developing new therapies and treatments for wound healing and tissue regeneration.\n\n3. Bubbles, Lightning, and Fire Dynamics: The ISS provides a unique laboratory environment for studying the behavior of bubbles, lightning, and fire in microgravity. Scientists have conducted experiments to understand how these phenomena behave differently without the influence of gravity. These studies have practical applications, such as improving combustion processes, enhancing fire safety measures, and developing more efficient cooling systems.\n\nThese are just a few examples of the exciting discoveries that have been made in the field of biology through research conducted on the ISS. The microgravity environment of space offers a unique perspective and enables researchers to uncover new insights into the workings of living organisms and their interactions with the environment.",
            "predictionValues": [
                {
                    "label": "resultText",
                    "value": "In the field of biology, there have been some exciting new discoveries made through research conducted on the International Space Station (ISS). Here are three examples:\n\n1. Understanding Plant Root Orientation: Scientists have been studying the growth and development of plants in microgravity. They found that plants grown in space exhibit different root orientation compared to those grown on Earth. This discovery helps us understand how plants adapt and respond to the absence of gravity. This knowledge can be applied to improve agricultural practices and develop innovative techniques for growing plants in challenging environments on Earth.\n\n2. Tissue Damage and Repair: One fascinating area of research on the ISS involves studying how living organisms respond to injuries in space. Scientists have investigated tissue damage and repair mechanisms in various organisms, including humans. By studying the healing processes in microgravity, researchers gained insights into how wounds heal differently in space compared to on Earth. This knowledge has implications for developing new therapies and treatments for wound healing and tissue regeneration.\n\n3. Bubbles, Lightning, and Fire Dynamics: The ISS provides a unique laboratory environment for studying the behavior of bubbles, lightning, and fire in microgravity. Scientists have conducted experiments to understand how these phenomena behave differently without the influence of gravity. These studies have practical applications, such as improving combustion processes, enhancing fire safety measures, and developing more efficient cooling systems.\n\nThese are just a few examples of the exciting discoveries that have been made in the field of biology through research conducted on the ISS. The microgravity environment of space offers a unique perspective and enables researchers to uncover new insights into the workings of living organisms and their interactions with the environment."
                }
            ],
            "deploymentApprovalStatus": "APPROVED",
            "extraModelOutput": {
                "CITATION_CONTENT_8": "3\nthe research study is received by others and how the \nknowledge is disseminated through citations in other \njournals. For example, six ISS studies have been \npublished in Nature, represented as a small node in the \ngraph. Network analysis shows that findings published \nin Nature are likely to be cited by other similar leading \njournals such as Science and Astrophysical Journal \nLetters (represented in bright yellow links) as well as \nspecialized journals such as Physical Review D and New \nJournal of Physics (represented in a yellow-green link). \nSix publications in Nature led to 512 citations according \nto VOSviewer\u2019s network map (version 1.6.11), an \nincrease of over 8,000% from publication to citation. \nFor comparison purposes, 6 publications in a small \njournal like American Journal of Botany led to 185 \ncitations and 107 publications in Acta Astronautica, \na popular journal among ISS scientists, led to 1,050 \ncitations (Figure 3, panel B). This count of 1,050",
                "CITATION_CONTENT_9": "Introduction\n4\nFigure 3. Count of publications reported in journals ranked in the top 100 according to global standards of Clarivate. A total of 567 top-tier publications \nthrough the end of FY-23 are shown by year and research category.\nIn this year\u2019s edition of the Annual Highlights of Results, we report findings from a \nwide range of topics in biology and biotechnology, physics, human research, Earth and \nspace science, and technology development \u2013 including investigations about plant root \norientation, tissue damage and repair, bubbles, lightning, fire dynamics, neutron stars, \ncosmic ray nuclei, imaging technology improvements, brain and vascular health, solar \npanel materials, grain flow, as well as satellite and robot control. \nThe findings highlighted here are only a small sample representative of the research \nconducted by the participating space agencies \u2013 ASI (Agenzia Spaziale Italiana), CSA \n(Canadian Space Agency), ESA (European Space Agency), JAXA (Japanese Aerospace",
                "CITATION_PAGE_3": 4,
                "CITATION_PAGE_8": 6,
                "CITATION_CONTENT_5": "23\nPUBLICATION HIGHLIGHTS: \nEARTH AND SPACE SCIENCE\nThe ISS laboratories enable scientific experiments in the biological sciences \nthat explore the complex responses of living organisms to the microgravity \nenvironment. The lab facilities support the exploration of biological systems \nranging from microorganisms and cellular biology to integrated functions \nof multicellular plants and animals. Several recent biological sciences \nexperiments have facilitated new technology developments that allow \ngrowth and maintenance of living cells, tissues, and organisms.\nThe Alpha Magnetic \nSpectrometer-02 (AMS-02) is \na state-of-the-art particle \nphysics detector constructed, \ntested, and operated by an \ninternational team composed \nof 60 institutes from \n16 countries and organized \nunder the United States \nDepartment of Energy (DOE) sponsorship. \nThe AMS-02 uses the unique environment of \nspace to advance knowledge of the universe \nand lead to the understanding of the universe\u2019s",
                "CITATION_SOURCE_5": "Space_Station_Annual_Highlights/iss_2017_highlights.pdf",
                "CITATION_CONTENT_3": "Introduction\n2\nExtensive international collaboration in the \nunique environment of LEO as well as procedural \nimprovements to assist researchers in the collection \nof data from the ISS have produced promising \nresults in the areas of protein crystal growth, tissue \nregeneration, vaccine and drug development, 3D \nprinting, and fiber optics, among many others. In \nthis year\u2019s edition of the Annual Highlights of Results, \nwe report findings from a wide range of topics in \nbiotechnology, physics, human research, Earth \nand space science, and technology development \n\u2013 including investigations about human retinal cells, \nbacterial resistance, black hole detection, space \nanemia, brain health, Bose-Einstein condensates, \nparticle self-assembly, RNA extraction technology, \nand more. The findings highlighted here represent \nonly a sample of the work ISS has contributed to \nsociety during the past 12 months.\nAs of Oct. 1, 2022, we have identified a total of 3,679",
                "CITATION_SOURCE_8": "Space_Station_Annual_Highlights/iss_2021_highlights.pdf",
                "CITATION_PAGE_7": 8,
                "CITATION_PAGE_6": 8,
                "CITATION_PAGE_2": 4,
                "CITATION_CONTENT_7": "Biology and Biotechnology Earth and Space Science Educational and Cultural Activities\nHuman Research Physical Science Technology Development and Demonstration",
                "CITATION_SOURCE_9": "Space_Station_Annual_Highlights/iss_2023_highlights.pdf",
                "datarobot_latency": 3.1466632366,
                "blocked_resultText": false,
                "CITATION_SOURCE_2": "Space_Station_Annual_Highlights/iss_2023_highlights.pdf",
                "CITATION_SOURCE_6": "Space_Station_Annual_Highlights/iss_2021_highlights.pdf",
                "CITATION_SOURCE_7": "Space_Station_Annual_Highlights/iss_2023_highlights.pdf",
                "datarobot_confidence_score": 0.6524822695,
                "CITATION_PAGE_9": 7,
                "CITATION_CONTENT_4": "Molecular Life Sciences. 2021 October 29; DOI: \n10.1007/s00018-021-03989-2.\nFigure 7. Immunoflourescent images of human retinal \ncells in different conditions. Image adopted from \nCialdai, Cellular and Molecular Life Sciences.\nThe ISS laboratory provides a platform for investigations in the biological sciences that \nexplores the complex responses of living organisms to the microgravity environment. Lab \nfacilities support the exploration of biological systems, from microorganisms and cellular \nbiology to the integrated functions of multicellular plants and animals.",
                "CITATION_SOURCE_1": "Space_Station_Annual_Highlights/iss_2023_highlights.pdf",
                "CITATION_SOURCE_0": "Space_Station_Annual_Highlights/iss_2018_highlights.pdf",
                "CITATION_SOURCE_3": "Space_Station_Annual_Highlights/iss_2022_highlights.pdf",
                "CITATION_PAGE_5": 26,
                "CITATION_PAGE_0": 7,
                "CITATION_PAGE_1": 11,
                "LLM_BLUEPRINT_ID": "662ba0062ade64c4fc4c1a1f",
                "CITATION_PAGE_4": 9,
                "datarobot_token_count": 320,
                "CITATION_CONTENT_0": "more effectively in space by addressing \nsuch topics as understanding radiation effects on \ncrew health, combating bone and muscle loss, \nimproving designs of systems that handle fluids \nin microgravity, and determining how to maintain \nenvironmental control efficiently. \nResults from the ISS provide new \ncontributions to the body of scientific \nknowledge in the physical sciences, life \nsciences, and Earth and space sciences \nto advance scientific discoveries in multi\u0002disciplinary ways. \nISS science results have Earth-based \napplications, including understanding our \nclimate, contributing to the treatment of \ndisease, improving existing materials, and inspiring \nthe future generation of scientists, clinicians, \ntechnologists, engineers, mathematicians, artists, \nand explorers.\nBENEFITS\nFOR HUMANITY\nDISCOVERY\nFigure 4. A heat map of all of the countries whose authors have cited scientific results publications from ISS Research through October 1, 2018.\nEXPLORATION",
                "CITATION_SOURCE_4": "Space_Station_Annual_Highlights/iss_2022_highlights.pdf",
                "CITATION_CONTENT_2": "capabilities (i.e., facilities), and data delivery are critical to the effective operation \nof scientific projects for accurate results to be shared with the scientific community, \nsponsors, legislators, and the public. \nOver 3,700 investigations have operated since Expedition 1, with more than 250 active \nresearch facilities, the participation of more than 100 countries, the work of more than \n5,000 researchers, and over 4,000 publications. The growth in research (Figure 1) and \ninternational collaboration (Figure 2) has prompted the publication of over 560 research \narticles in top-tier scientific journals with about 75 percent of those groundbreaking studies \noccurring since 2018 (Figure 3). \nBibliometric analyses conducted through VOSviewer1\n measure the impact of space station \nresearch by quantifying and visualizing networks of journals, citations, subject areas, and \ncollaboration between authors, countries, or organizations. Using bibliometrics, a broad",
                "CITATION_CONTENT_1": "technologists, engineers, mathematicians, artists, and explorers.\nEXPLORATION\nDISCOVERY\nBENEFITS\nFOR HUMANITY",
                "CITATION_CONTENT_6": "control efficiently. \nResults from the ISS provide new \ncontributions to the body of scientific \nknowledge in the physical sciences, life \nsciences, and Earth and space sciences \nto advance scientific discoveries in multi\u0002disciplinary ways. \nISS science results have Earth-based \napplications, including understanding our \nclimate, contributing to the treatment of \ndisease, improving existing materials, and \ninspiring the future generation of scientists, \nclinicians, technologists, engineers, \nmathematicians, artists and explorers.\nBENEFITS\nFOR HUMANITY\nDISCOVERY\nEXPLORATION"
            }
        },
    ]
}

時系列での予測の作成

ヒント

時系列予測は、すべての時間認識モデリングではなく、時系列プロジェクトに固有です。 特に、CSVファイルは特定の形式である必要があります。詳細については、時系列モデリングのページの予測に関するセクションを参照してください。

予測ポイントを使用して予測を行っている場合は、DataRobotが予測ポイントを自動生成するため、予測データの予測ウィンドウをスキップできます。 これを自動拡張と呼びます。 次の場合、自動拡張が自動的に適用されます。

  • 予測範囲ではなく、特定の予測ポイントに対して、予測が行われます。
  • 時系列プロジェクトには定期的な時間ステップがあり、ナウキャスティングは使用されません。

自動拡張を使用する場合は、次の点に注意してください。

  • モデルにとって重要な 事前に既知特徴量がある場合は、予測ウィンドウを手動で作成して予測精度を高めることをお勧めします。
  • 精度の追跡にデプロイでプライマリー日付/時刻列以外の 関連付けIDを使用する予定がある場合は、予測ウィンドウを手動で作成します。

時系列展開と通常の非時系列展開で予測を行うためのURLは同じです。 唯一の違いは、オプションで予測ポイント、予測の開始/終了日、またはその他の時系列固有のURLパラメーターを指定できることです。 サーバーは、デプロイIDを使用して、デプロイされたモデルを時系列デプロイとして自動的に検出し、それに応じて処理します。

curl -i -X POST "https://example.datarobot.com/predApi/v1.0/deployments/<deploymentId>/predictions" \
    -H "Authorization: Bearer <API key>" -F \
    file=@~/.home/path/to/dataset.csv  

複数系列プロジェクトのサンプル応答本文を以下に示します。

HTTP/1.1 200 OK
Content-Type: application/json
X-DataRobot-Execution-Time: 1405
X-DataRobot-Model-Cache-Hit: false

{
  "data": [
    {
      "seriesId": 1,
      "forecastPoint": "2018-01-09T00:00:00Z",
      "rowId": 365,
      "timestamp": "2018-01-10T00:00:00.000000Z",
      "predictionValues": [
        {
          "value": 45180.4041874386,
          "label": "target (actual)"
        }
      ],
      "forecastDistance": 1,
      "prediction": 45180.4041874386
    },
    {
      "seriesId": 1,
      "forecastPoint": "2018-01-09T00:00:00Z",
      "rowId": 366,
      "timestamp": "2018-01-11T00:00:00.000000Z",
      "predictionValues": [
        {
          "value": 47742.9432499386,
          "label": "target (actual)"
        }
      ],
      "forecastDistance": 2,
      "prediction": 47742.9432499386
    },
    {
      "seriesId": 1,
      "forecastPoint": "2018-01-09T00:00:00Z",
      "rowId": 367,
      "timestamp": "2018-01-12T00:00:00.000000Z",
      "predictionValues": [
        {
          "value": 46394.5698978878,
          "label": "target (actual)"
        }
      ],
      "forecastDistance": 3,
      "prediction": 46394.5698978878
    },
    {
      "seriesId": 2,
      "forecastPoint": "2018-01-09T00:00:00Z",
      "rowId": 697,
      "timestamp": "2018-01-10T00:00:00.000000Z",
      "predictionValues": [
        {
          "value": 39794.833199375,
          "label": "target (actual)"
        }
      ]
    }
  ]
} 

リクエストパラメーター

URIクエリパラメータを使用して、時系列予測リクエストをパラメータ化できます。 たとえば、デフォルトの推定予測ポイントを上書きすると、次のようになります。

curl -i -X POST "https://example.datarobot.com/predApi/v1.0/deployments/<deploymentId>/predictions?forecastPoint=1961-01-01T00:00:00?relaxKnownInAdvanceFeaturesCheck=true" \
    -H "Authorization: Bearer <API key>" -F \
    file=@~/.home/path/to/dataset.csv 

時系列固有のパラメーターの詳細なリストについては、デプロイの時系列予測を参照してください。

応答スキーム

応答スキーム標準の予測と一貫性がありますが、各PredictionRowオブジェクトにいくつかの列が追加されます。

名前 タイプ 備考
seriesId string、int、またはNone 複数系列プロジェクトの系列を識別する予測済み列の複数系列識別子。
forecastPoint 文字列 予測リクエストの予測ポイント(ユーザー設定またはDataRobotによる選択)に対応するISO 8601形式のDateTime文字列。
timestamp 文字列 予測された行のDateTime列に対応するISO 8601形式のDateTime文字列。
forecastDistance 整数 予測された行の予測距離識別子、またはスコアリングデータセットのforecastPointからの距離。
originalFormatTimestamp 文字列 予測された行のDateTime列に対応するDateTime文字列。 timestamp列とは異なり、この列はアップロードされた予測データセットと同じDateTime形式を維持します。 (この列は管理者によって有効化されている場合に表示されます。

予測の説明の作成

DataRobotの予測の説明機能を使用すると、例外的に高い予測値や例外的に低い予測値が発生する特定の入力の属性に関するインサイトを得ることができます。

ヒント

予測の説明を実行する前に、次の2つの重要な依存関係を実行する必要があります。

  1. モデルの 特徴量のインパクトを計算する必要があります。
  2. 選択したモデルを使用してデータセットで予測を生成する必要があります。

予測の説明を初期化するには、予測の説明タブを使用します。

予測の説明の作成は、標準の予測リクエストに非常に似ています。 最初に、予測の説明リクエストがPOSTリクエストとしてリソースに送信されます。

curl -i -X POST "https://example.datarobot.com/predApi/v1.0/deployments/<deploymentId>/predictionExplanations" \
    -H "Authorization: Bearer <API key>" -F \
    file=@~/.home/path/to/dataset.csv 

応答本文のサンプルを以下に示します。

HTTP/1.1 200 OK
Content-Type: application/json
X-DataRobot-Execution-Time: 841
X-DataRobot-Model-Cache-Hit: true

{
  "data": [
    {
      "predictionValues": [
        {
          "value": 0.6634830442,
          "label": 1
        },
        {
          "value": 0.3365169558,
          "label": 0
        }
      ],
      "prediction": 1,
      "rowId": 0,
      "predictionExplanations": [
        {
          "featureValue": 49,
          "strength": 0.6194461777,
          "feature": "driver_age",
          "qualitativeStrength": "+++",
          "label": 1
        },
        {
          "featureValue": 1,
          "strength": 0.3501610895,
          "feature": "territory",
          "qualitativeStrength": "++",
          "label": 1
        },
        {
          "featureValue": "M",
          "strength": -0.171075409,
          "feature": "gender",
          "qualitativeStrength": "--",
          "label": 1
        }
      ]
    },
    {
      "predictionValues": [
        {
          "value": 0.3565584672,
          "label": 1
        },
        {
          "value": 0.6434415328,
          "label": 0
        }
      ],
      "prediction": 0,
      "rowId": 1,
      "predictionExplanations": []
    }
  ]
} 

リクエストパラメーター

URIクエリーパラメーターを使用して、予測の説明の予測リクエストをパラメーター化することができます。

パラメーター名 タイプ 備考
maxExplanations 整数 予測ごとに生成されるコードの最大数。 デフォルトは3です。
thresholdLow 浮動小数 予測の説明の下限しきい値。 予測の説明を計算するには、予測は、この値以下(またはthresholdHighの値以上)である必要があります。 この値はnullに設定できます。
thresholdHigh 浮動小数 予測の説明の上限しきい値。 予測の説明を計算するには、予測は、この値以上(またはthresholdLowの値以下)である必要があります。 この値はnullに設定できます。
excludeAdjustedPredictions 文字列 モデル構築中にエクスポージャーが使用された場合、エクスポージャー調整された予測を予測応答に含めるか予測応答から除外します。 デフォルト値は「true」です(エクスポージャー調整された予測を除外します)。

パラメーター化されたリクエストの例を以下に示します。

curl -i -X POST "https://example.datarobot.com/predApi/v1.0/deployments/<deploymentId>/predictionExplanations?maxExplanations=2&thresholdLow=0.2&thresholdHigh=0.5"
    -H "Authorization: Bearer <API key>" -F \
    file=@~/.home/path/to/dataset.csv 

DataRobotのヘッダースキーマは予測応答のものと同じです。 応答スキームは標準の予測と一貫性がありますが、PredictionExplanationsの配列「predictionExplanations」が各PredictionRowオブジェクトに追加されます。

PredictionExplanationsスキーマ

オブジェクトの応答JSON配列:

名前 タイプ 備考
ラベル この予測の説明から派生した出力を説明します。 連続値プロジェクトの場合、これはターゲット特徴量の名前です。 分類プロジェクトの場合、これは、この予測の説明のpositiveの強度が確率の増加に対応するクラスです。
feature 文字列 予測に貢献する特徴量の名前。
featureValue - この行に対して特徴量が取った値。
strength 浮動小数 この特徴量の値が予測に影響した量。
qualitativeStrength 文字列 特徴量が予測に影響した強度を示す人間が読み取ることのできる説明(例:+++、–、+)。

ヒント

予測の説明のstrength値は、値[-1, 1]に縛られていません。この解釈は、モデルの特徴量の数が変更されると変わることがあります。 正規化された値としては、代わりにqualitativeStrengthを使用します。 qualitativeStrength[-1, 1]の範囲を視覚的に表現します。----1を表し、+++1を表します。 同じqualitativeStrengthの説明の場合、ランキングにstrengthを使用できます。

詳細については、予測の説明の出力の解釈のセクションを参照してください。

信頼性の監視を備えた予測の作成

信頼性の監視を備えた予測では、ユーザー定義の信頼性ルールを使用して予測を監視できます。

予測が「不確かな予測」トリガーに対して提供されたしきい値の範囲外になると、トリガーに割り当てられたアクションがデフォルトになります。 トリガーがアクティブになると、信頼性キーが予測応答の本文に追加されます。

以下に示すのは、サンプルの応答本文です。これは、Uncertain Prediction TriggerAction - No Operationを使用した連続値プロジェクトの応答です。

{
  "data": [
    {
      "predictionValues": [
        {
          "value": 122.8034057617,
          "label": "length"
        }
      ],
      "prediction": 122.8034057617,
      "rowId": 99,
      "humility": [
        {
          "ruleId": "5ebad4735f11b33a38ff3e0d",
          "triggered": true,
          "ruleName": "Uncertain Prediction Trigger"
        }
      ]
    }
  ]
} 

以下に示すのは、連続値モデルデプロイの応答本文の例です。 これは、「エラーを発生」アクションが設定された「不確かな予測」トリガーを使用します。

480 Error: {"message":"Humility ReturnError action triggered."} 

以下に示すのは、連続値モデルデプロイの応答本文の例です。 これは、「予測のオーバーライド」アクションが設定された「不確かな予測」トリガーを使用します。

{
  "data": [
    {
      "predictionValues": [
        {
          "value": 122.8034057617,
          "label": "length"
        }
      ],
      "prediction": 5220,
      "rowId": 99,
      "humility": [
        {
          "ruleId": "5ebad4735f11b33a38ff3e0d",
          "triggered": true,
          "ruleName": "Uncertain Prediction Trigger"
        }
      ]
    }
  ]
} 

応答スキーム

応答スキーマ標準の予測と一貫性がありますが、各Humilityオブジェクトの列のサブセットを含む新しい信頼性列が追加されます。

名前 タイプ 備考
ruleId 文字列 デプロイに割り当てられた信頼性ルールのID
トリガー済み ブーリアン ルールがトリガーされたかどうかに応じて、「True」または「False」を返します
ruleName 文字列 ユーザーによって定義されたルールまたはタイムスタンプを使用して自動生成されたルールの名前

エラーレスポンス

エラーはすべて200コード属性以外で表示されます。 4XXで始まるコードはリクエストエラーであることを示します(列の欠損、間違った認証情報、不明なモデルIDなど)。 メッセージ属性は、4XXコードが発生した場合、エラーの詳細説明を表示します。 例:

curl -H "Content-Type: application/json" -X POST --data '' \
    -H "Authorization: Bearer <API key>" \
    https://example.datarobot.com/predApi/v1.0/deployments/<deploymentId>

HTTP/1.1 400 BAD REQUEST
Date: Fri, 08 Feb 2019 11:00:00 GMT
Content-Type: application/json
Content-Length: 53
Connection: keep-alive
Server: nginx/1.12.2
X-DataRobot-Execution-Time: 332
X-DataRobot-Request-ID: fad6a0b62c1ff30db74c6359648d12fd

{
  "message": "The requested URL was not found on the server.  If you entered the URL manually, please check your spelling and try again."
} 

5XXで始まるコードはサーバー側のエラーを示します。 リクエストを再度試行するか、DataRobot担当者にお問い合わせください。

制限に関する説明

ここでは、専用予測インスタンスのサイズおよびタイムアウト制限について説明します。

  • 専用の予測サーバーに送信できるデータの最大量は、50MBです。

  • 行数の制限はありませんが、以下のタイムアウト制限があります。

    • セルフマネージドAIプラットフォーム:設定に応じて異なる
    • マネージドAIプラットフォーム:600秒

    リクエストがタイムアウトを超える場合、または専用予測サーバーを使用して大きなファイルのスコアリングを行う場合は、バッチスコアリングパッケージの使用を検討してください。

  • HTTPリクエストラインのサイズに制限があります(現在の制限は 8192バイトです)。

  • マネージドAIプラットフォームデプロイの場合、専用予測APIサーバーは、600秒以上アイドル状態になると、持続的なHTTP接続を自動で終了します。 持続接続を使用するには、クライアント側でこれらの切断を正しく処理できる必要があります。 次の例は、送信が失敗した場合にHTTPリクエストを自動的に再試行するようPython HTTPライブラリrequestsを設定します。

import requests
import urllib3

# create a transport adapter that will automatically retry GET/POST/HEAD requests on failures up to 3 times
adapter = requests.adapters.HTTPAdapter(
    max_retries=urllib3.Retry(
        total=3,
        method_whitelist=frozenset(['GET', 'POST', 'HEAD'])
    )
)

# create a Session (a pool of connections) and make it use the given adapter for HTTP and HTTPS requests
session = requests.Session()
session.mount('http://', adapter)
session.mount('https://', adapter)

# execute a prediction request that will be retried on transport failures, if needed
api_token = '<your api token>'
dr_key = '<your datarobot key>'
response = session.post(
    'https://example.datarobot.com/predApi/v1.0/deployments/<deploymentId>/predictions',
    headers={
        'Authorization': 'Bearer %s' % api_token,
        'DataRobot-Key': dr_key,
        'Content-Type': 'text/csv',
    },
    data='<your scoring data>',
)

print(response.content) 

モデルのキャッシュ

専用予測サーバーは、必要に応じてDataRobotクラスターからモデルをフェッチします。 同じモデルを使用する後続の予測の処理速度を向上させるために、DataRobotは特定の数のモデルをメモリーに格納(キャッシュ)します。 キャッシュがいっぱいになった場合に新しいモデルリクエストをするには、キャッシュ内の既存のモデルを1つ削除する必要があります。 DataRobotでは、最も以前に使用されたモデルが削除されます(必ずしもキャッシュ内に最も長く格納されているモデルではありません)。

セルフマネージドAIプラットフォームインストールの場合、キャッシュのデフォルトサイズは16モデルですが、このサイズはインストールごとに異なります。 特定のインストールのキャッシュサイズに関する質問については、DataRobotサポートに問い合わせてください。

予測サーバーは、複数の予測処理を実行します。それぞれの予測処理には、独自の排他的モデルキャッシュがあります。 予測処理は相互に共有されません。 そのため、2つのリクエストを連続して予測サーバーに送信した場合、それぞれのリクエストでモデルデータをダウンロードする必要が生じることがあります。

予測サーバーからの各応答には、使用されたモデルがキャッシュ内にあったかどうかを示す1つのヘッダー(X-DataRobot-Model-Cache-Hit)が含まれます。 モデルがキャッシュにあった場合、ヘッダーの値はtrueです。値がfalseの場合、モデルはキャッシュにありませんでした。

予測をすばやく作成するためのベストプラクティス

以下のチェックリストに予測をすばやく作成するための推奨事項をまとめます。

  • 持続的HTTP接続を実装する。これで予測APIへのネットワークラウンドトリップが削減され、レイテンシーが削減されます。

  • CSVデータを使用する。大量のデータのJSONシリアル化はCSVを使用するよりも長い時間がかかるので、予測入力にCCSVを使用することを検討してください。

  • リクエストされたモデルの数を少なくする。これで予測APIでモデルキャッシュを使用できるようになります。

  • データをチャンクにまとめる。50MBのリクエスト制限を超えずに、可能な限り多くの行をバッチにまとめます。 大きなファイルをスコアリングする場合は、ローカルファイルのスコアリングに加えて、S3とデータベース間のスコアリングもサポートするバッチ予測APIの使用を検討してください。


更新しました July 2, 2024