קבלת מסקנות אונליין למודלים של AutoML

בדף הזה מוסבר איך לקבל מסקנות והסברים אונליין (בזמן אמת) ממודלים של סיווג טבלאי או רגרסיה שאומנו ב-AutoML, באמצעות מסוף Google Cloud או Agent Platform API.

הסקת מסקנות אונליין היא בקשה סינכרונית, בניגוד להסקת מסקנות באצווה, שהיא בקשה אסינכרונית. משתמשים בהסקת מסקנות אונליין כששולחים בקשות בתגובה לקלט של אפליקציה או במצבים אחרים שבהם נדרשת הסקת מסקנות בזמן אמת.

כדי להשתמש במודל להצגת מסקנות אונליין, צריך קודם לפרוס את המודל לנקודת קצה. פריסת מודל משייכת משאבים פיזיים למודל, כדי שיוכל להכניס לשימוש בסביבת הייצור היקשים אונליין עם זמן אחזור קצר.

הנושאים שמוסברים במאמר:

  1. פריסת מודל בנקודת קצה
  2. קבלת הסקת מסקנות אונליין באמצעות המודל שפרסתם
  3. קבלת הסבר אונליין באמצעות המודל שפרסתם

לפני שמתחילים

כדי לקבל מסקנות אונליין, קודם צריך לאמן מודל סיווג או רגרסיה ולהעריך את רמת הדיוק שלו.

פריסת מודל בנקודת קצה

אפשר לפרוס יותר ממודל אחד לנקודת קצה, ואפשר לפרוס מודל ליותר מנקודת קצה אחת. מידע נוסף על אפשרויות ועל תרחישי שימוש להטמעה של מודלים

כדי לפרוס מודל, משתמשים באחת מהשיטות הבאות:

מסוף Google Cloud

  1. במסוף Google Cloud , בקטע Agent Platform, עוברים לדף Models.

    כניסה לדף Models

  2. לוחצים על שם המודל שרוצים לפרוס כדי לפתוח את דף הפרטים שלו.

  3. בוחרים בכרטיסייה Deploy & Test (פריסה ובדיקה).

    אם המודל כבר נפרס בנקודות קצה כלשהן, הן מפורטות בקטע Deploy your model.

  4. לוחצים על Deploy to endpoint.

  5. בדף Define your endpoint, מגדירים את האפשרויות הבאות:

    1. אפשר לבחור לפרוס את המודל לנקודת קצה חדשה או לנקודת קצה קיימת.

      • כדי לפרוס את המודל לנקודת קצה חדשה, בוחרים באפשרות יצירת נקודת קצה חדשה ומזינים שם לנקודת הקצה החדשה.
      • כדי לפרוס את המודל לנקודת קצה קיימת, בוחרים באפשרות הוספה לנקודת קצה קיימת ובוחרים את נקודת הקצה מהרשימה הנפתחת.
      • אפשר להוסיף יותר ממודל אחד לנקודת קצה, ואפשר להוסיף מודל ליותר מנקודת קצה אחת. מידע נוסף
    2. לוחצים על Continue.

  6. בדף Model settings, קובעים את ההגדרות הבאות:

    1. אם אתם פורסים את המודל לנקודת קצה חדשה, צריך להזין 100 בחלוקת התנועה. אם אתם פורסים את המודל לנקודת קצה קיימת שכבר פרוסים בה מודל אחד או יותר, אתם צריכים לעדכן את אחוז חלוקת התנועה של המודל שאתם פורסים ושל המודלים שכבר פרוסים, כך שסכום האחוזים יהיה 100%.

    2. מזינים את המספר המינימלי של צמתי מחשוב שרוצים לספק עבור המודל.

      זה מספר הצמתים שזמינים למודל הזה בכל רגע נתון. תחויבו על הצמתים שבהם נעשה שימוש, בין אם כדי לטפל בעומס של הסקת מסקנות או עבור צמתים במצב המתנה (מינימום), גם אם אין תנועה של הסקת מסקנות. לעיון בתמחור

    3. בוחרים את סוג המכונה.

      הגדלת משאבי המכונה תשפר את ביצועי ההסקה ותגדיל את העלויות.

    4. איך משנים את הגדרות ברירת המחדל של רישום מסקנות

    5. לוחצים על המשך.

  7. בדף Model monitoring (מעקב אחרי המודל), לוחצים על Continue (המשך).

  8. בדף Monitoring objectives, מגדירים את ההגדרות הבאות:

    1. מזינים את המיקום של נתוני האימון.
    2. מזינים את השם של עמודת היעד.
  9. לוחצים על Deploy (פריסה) כדי לפרוס את המודל בנקודת הקצה.

API

כשפורסים מודל באמצעות Agent Platform API, מבצעים את השלבים הבאים:

  1. אם צריך, יוצרים נקודת קצה.
  2. מוצאים את מזהה נקודת הקצה.
  3. פורסים את המודל בנקודת הקצה.

יצירת נקודת קצה

אם אתם פורסים מודל לנקודת קצה קיימת, אתם יכולים לדלג על השלב הזה.

gcloud

בדוגמה הבאה משתמשים בפקודה gcloud ai endpoints create:

  gcloud ai endpoints create \
    --region=LOCATION \
    --display-name=ENDPOINT_NAME

מחליפים את מה שכתוב בשדות הבאים:

  • LOCATION_ID: האזור שבו משתמשים ב-Agent Platform.
  • ENDPOINT_NAME: השם המוצג של נקודת הקצה.

    יכול להיות שיחלפו כמה שניות עד שכלי Google Cloud CLI ייצור את נקודת הקצה.

REST

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • LOCATION_ID: האזור שלכם.
  • PROJECT_ID: [מזהה הפרויקט](/resource-manager/docs/creating-managing-projects#identifiers). .
  • ENDPOINT_NAME: השם המוצג של נקודת הקצה.

ה-method של ה-HTTP וכתובת ה-URL:

POST https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/endpoints

תוכן בקשת JSON:

{
  "display_name": "ENDPOINT_NAME"
}

כדי לשלוח את הבקשה צריך להרחיב אחת מהאפשרויות הבאות:

אתם אמורים לקבל תגובת JSON שדומה לזו:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION_ID/endpoints/ENDPOINT_ID/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.aiplatform.v1.CreateEndpointOperationMetadata",
    "genericMetadata": {
      "createTime": "2020-11-05T17:45:42.812656Z",
      "updateTime": "2020-11-05T17:45:42.812656Z"
    }
  }
}
אפשר לבדוק את סטטוס הפעולה עד שהתשובה כוללת את "done": true.

Java

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Javaההוראות להגדרה במאמר מדריך למתחילים של Agent Platform באמצעות ספריות לקוח.

כדי לבצע אימות ב-Agent Platform, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.aiplatform.v1.CreateEndpointOperationMetadata;
import com.google.cloud.aiplatform.v1.Endpoint;
import com.google.cloud.aiplatform.v1.EndpointServiceClient;
import com.google.cloud.aiplatform.v1.EndpointServiceSettings;
import com.google.cloud.aiplatform.v1.LocationName;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateEndpointSample {

  public static void main(String[] args)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    String project = "YOUR_PROJECT_ID";
    String endpointDisplayName = "YOUR_ENDPOINT_DISPLAY_NAME";
    createEndpointSample(project, endpointDisplayName);
  }

  static void createEndpointSample(String project, String endpointDisplayName)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    EndpointServiceSettings endpointServiceSettings =
        EndpointServiceSettings.newBuilder()
            .setEndpoint("us-central1-aiplatform.googleapis.com:443")
            .build();

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (EndpointServiceClient endpointServiceClient =
        EndpointServiceClient.create(endpointServiceSettings)) {
      String location = "us-central1";
      LocationName locationName = LocationName.of(project, location);
      Endpoint endpoint = Endpoint.newBuilder().setDisplayName(endpointDisplayName).build();

      OperationFuture<Endpoint, CreateEndpointOperationMetadata> endpointFuture =
          endpointServiceClient.createEndpointAsync(locationName, endpoint);
      System.out.format("Operation name: %s\n", endpointFuture.getInitialFuture().get().getName());
      System.out.println("Waiting for operation to finish...");
      Endpoint endpointResponse = endpointFuture.get(300, TimeUnit.SECONDS);

      System.out.println("Create Endpoint Response");
      System.out.format("Name: %s\n", endpointResponse.getName());
      System.out.format("Display Name: %s\n", endpointResponse.getDisplayName());
      System.out.format("Description: %s\n", endpointResponse.getDescription());
      System.out.format("Labels: %s\n", endpointResponse.getLabelsMap());
      System.out.format("Create Time: %s\n", endpointResponse.getCreateTime());
      System.out.format("Update Time: %s\n", endpointResponse.getUpdateTime());
    }
  }
}

Node.js

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Node.jsההוראות להגדרה במאמר מדריך למתחילים של Agent Platform באמצעות ספריות לקוח.

כדי לבצע אימות ב-Agent Platform, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

/**
 * TODO(developer): Uncomment these variables before running the sample.\
 * (Not necessary if passing values as arguments)
 */

// const endpointDisplayName = 'YOUR_ENDPOINT_DISPLAY_NAME';
// const project = 'YOUR_PROJECT_ID';
// const location = 'YOUR_PROJECT_LOCATION';

// Imports the Google Cloud Endpoint Service Client library
const {EndpointServiceClient} = require('@google-cloud/aiplatform');

// Specifies the location of the api endpoint
const clientOptions = {
  apiEndpoint: 'us-central1-aiplatform.googleapis.com',
};

// Instantiates a client
const endpointServiceClient = new EndpointServiceClient(clientOptions);

async function createEndpoint() {
  // Configure the parent resource
  const parent = `projects/${project}/locations/${location}`;
  const endpoint = {
    displayName: endpointDisplayName,
  };
  const request = {
    parent,
    endpoint,
  };

  // Get and print out a list of all the endpoints for this resource
  const [response] = await endpointServiceClient.createEndpoint(request);
  console.log(`Long running operation : ${response.name}`);

  // Wait for operation to complete
  await response.promise();
  const result = response.result;

  console.log('Create endpoint response');
  console.log(`\tName : ${result.name}`);
  console.log(`\tDisplay name : ${result.displayName}`);
  console.log(`\tDescription : ${result.description}`);
  console.log(`\tLabels : ${JSON.stringify(result.labels)}`);
  console.log(`\tCreate time : ${JSON.stringify(result.createTime)}`);
  console.log(`\tUpdate time : ${JSON.stringify(result.updateTime)}`);
}
createEndpoint();

Python

במאמר התקנת Vertex AI SDK ל-Python מוסבר איך להתקין או לעדכן את Vertex AI SDK ל-Python. מידע נוסף מופיע ב מאמרי העזרה של Python API.

def create_endpoint_sample(
    project: str,
    display_name: str,
    location: str,
):
    aiplatform.init(project=project, location=location)

    endpoint = aiplatform.Endpoint.create(
        display_name=display_name,
        project=project,
        location=location,
    )

    print(endpoint.display_name)
    print(endpoint.resource_name)
    return endpoint

קבלת מזהה נקודת הקצה

כדי לפרוס את המודל, צריך את מזהה נקודת הקצה.

gcloud

בדוגמה הבאה משתמשים בפקודה gcloud ai endpoints list:

  gcloud ai endpoints list \
    --region=LOCATION \
    --filter=display_name=ENDPOINT_NAME

מחליפים את מה שכתוב בשדות הבאים:

  • LOCATION_ID: האזור שבו משתמשים ב-Agent Platform.
  • ENDPOINT_NAME: השם המוצג של נקודת הקצה.

    רושמים את המספר שמופיע בעמודה ENDPOINT_ID. משתמשים במזהה הזה בשלב הבא.

REST

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • LOCATION_ID: האזור שבו משתמשים ב-Agent Platform.
  • PROJECT_ID: .
  • ENDPOINT_NAME: השם המוצג של נקודת הקצה.

ה-method של ה-HTTP וכתובת ה-URL:

GET https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/endpoints?filter=display_name=ENDPOINT_NAME

כדי לשלוח את הבקשה צריך להרחיב אחת מהאפשרויות הבאות:

אתם אמורים לקבל תגובת JSON שדומה לזו:

{
  "endpoints": [
    {
      "name": "projects/PROJECT_NUMBER/locations/LOCATION_ID/endpoints/ENDPOINT_ID",
      "displayName": "ENDPOINT_NAME",
      "etag": "AMEw9yPz5pf4PwBHbRWOGh0PcAxUdjbdX2Jm3QO_amguy3DbZGP5Oi_YUKRywIE-BtLx",
      "createTime": "2020-04-17T18:31:11.585169Z",
      "updateTime": "2020-04-17T18:35:08.568959Z"
    }
  ]
}
שימו לב ל-ENDPOINT_ID.

פריסת המודל

בוחרים את הכרטיסייה של השפה או הסביבה שלכם:

gcloud

בדוגמאות הבאות משתמשים בפקודה gcloud ai endpoints deploy-model.

בדוגמה הבאה מתבצעת פריסה של Model אל Endpoint בלי להשתמש במעבדי GPU כדי להאיץ את הצגת התחזיות, ובלי לפצל את התנועה בין כמה משאבי DeployedModel:

לפני השימוש בנתוני הפקודה הבאים, צריך להחליף את הנתונים הבאים:

  • ENDPOINT_ID: המזהה של נקודת הקצה.
  • LOCATION_ID: האזור שבו משתמשים ב-Agent Platform.
  • MODEL_ID: המזהה של המודל שרוצים לפרוס.
  • DEPLOYED_MODEL_NAME: שם ל-DeployedModel. אפשר להשתמש גם בשם המוצג של Model בשביל DeployedModel.
  • MACHINE_TYPE: אופציונלי. משאבי המכונה שמשמשים לכל צומת בפריסה הזו. הגדרת ברירת המחדל היא n1-standard-2. מידע נוסף על סוגי מכונות
  • MIN_REPLICA_COUNT: מספר הצמתים המינימלי לפריסה הזו. אפשר להגדיל או להקטין את מספר הצמתים לפי הצורך בהתאם לעומס ההסקה, עד למספר המקסימלי של הצמתים, אבל אף פעם לא פחות ממספר הצמתים הזה. הערך הזה חייב להיות שווה ל-1 או גדול ממנו. אם לא מציינים את הדגל --min-replica-count, ערך ברירת המחדל הוא 1.
  • MAX_REPLICA_COUNT: המספר המקסימלי של הצמתים לפריסה הזו. אפשר להגדיל או להקטין את מספר הצמתים בהתאם לעומס ההסקה, עד למספר הצמתים הזה ולעולם לא פחות ממספר הצמתים המינימלי. אם לא מציינים את הדגל --max-replica-count, המספר המקסימלי של הצמתים מוגדר לערך של --min-replica-count.

מריצים את הפקודה gcloud ai endpoints deploy-model:

‫Linux,‏ macOS או Cloud Shell

gcloud ai endpoints deploy-model ENDPOINT_ID\
  --region=LOCATION_ID \
  --model=MODEL_ID \
  --display-name=DEPLOYED_MODEL_NAME \
  --machine-type=MACHINE_TYPE \
  --min-replica-count=MIN_REPLICA_COUNT \
  --max-replica-count=MAX_REPLICA_COUNT \
  --traffic-split=0=100

‏Windows (PowerShell)

gcloud ai endpoints deploy-model ENDPOINT_ID`
  --region=LOCATION_ID `
  --model=MODEL_ID `
  --display-name=DEPLOYED_MODEL_NAME `
  --machine-type=MACHINE_TYPE `
  --min-replica-count=MIN_REPLICA_COUNT `
  --max-replica-count=MAX_REPLICA_COUNT `
  --traffic-split=0=100

Windows‏ (cmd.exe)

gcloud ai endpoints deploy-model ENDPOINT_ID^
  --region=LOCATION_ID ^
  --model=MODEL_ID ^
  --display-name=DEPLOYED_MODEL_NAME ^
  --machine-type=MACHINE_TYPE ^
  --min-replica-count=MIN_REPLICA_COUNT ^
  --max-replica-count=MAX_REPLICA_COUNT ^
  --traffic-split=0=100
 

חלוקת התנועה

הדגל --traffic-split=0=100 בדוגמאות שלמעלה שולח 100% מתנועת החיזוי שמתקבלת ב-Endpoint אל DeployedModel החדש, שמיוצג על ידי המזהה הזמני 0. אם ב-Endpoint כבר יש משאבים אחרים, אפשר לפצל את התנועה בין המשאבים החדשים לבין המשאבים הישנים.DeployedModelEndpointDeployedModel לדוגמה, כדי לשלוח 20% מהתנועה ל-DeployedModel החדש ו-80% מהתנועה ל-DeployedModel ישן יותר, מריצים את הפקודה הבאה.

לפני השימוש בנתוני הפקודה הבאים, צריך להחליף את הנתונים הבאים:

  • OLD_DEPLOYED_MODEL_ID: המזהה של DeployedModel הקיים.

מריצים את הפקודה gcloud ai endpoints deploy-model:

‫Linux,‏ macOS או Cloud Shell

gcloud ai endpoints deploy-model ENDPOINT_ID\
  --region=LOCATION_ID \
  --model=MODEL_ID \
  --display-name=DEPLOYED_MODEL_NAME \ 
  --machine-type=MACHINE_TYPE \
  --min-replica-count=MIN_REPLICA_COUNT \
  --max-replica-count=MAX_REPLICA_COUNT \
  --traffic-split=0=20,OLD_DEPLOYED_MODEL_ID=80

‏Windows (PowerShell)

gcloud ai endpoints deploy-model ENDPOINT_ID`
  --region=LOCATION_ID `
  --model=MODEL_ID `
  --display-name=DEPLOYED_MODEL_NAME \ 
  --machine-type=MACHINE_TYPE `
  --min-replica-count=MIN_REPLICA_COUNT `
  --max-replica-count=MAX_REPLICA_COUNT `
  --traffic-split=0=20,OLD_DEPLOYED_MODEL_ID=80

Windows‏ (cmd.exe)

gcloud ai endpoints deploy-model ENDPOINT_ID^
  --region=LOCATION_ID ^
  --model=MODEL_ID ^
  --display-name=DEPLOYED_MODEL_NAME \ 
  --machine-type=MACHINE_TYPE ^
  --min-replica-count=MIN_REPLICA_COUNT ^
  --max-replica-count=MAX_REPLICA_COUNT ^
  --traffic-split=0=20,OLD_DEPLOYED_MODEL_ID=80
 

REST

משתמשים בשיטה endpoints.predict כדי לבקש הסקה אונליין.

פורסים את המודל.

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • LOCATION_ID: האזור שבו משתמשים ב-Agent Platform.
  • PROJECT_ID: .
  • ENDPOINT_ID: המזהה של נקודת הקצה.
  • MODEL_ID: המזהה של המודל שרוצים לפרוס.
  • DEPLOYED_MODEL_NAME: שם ל-DeployedModel. אפשר להשתמש גם בשם המוצג של Model בשביל DeployedModel.
  • MACHINE_TYPE: אופציונלי. משאבי המכונה שמשמשים לכל צומת בפריסה הזו. הגדרת ברירת המחדל היא n1-standard-2. מידע נוסף על סוגי מכונות
  • ACCELERATOR_TYPE: סוג המאיץ שיצורף למכונה. אופציונלי אם לא מציינים את ACCELERATOR_COUNT או אם הערך שלו הוא אפס. לא מומלץ לשימוש ב: מודלים של AutoML או מודלים שאומנו בהתאמה אישית ומשתמשים בתמונות שלא מבוססות על GPU. מידע נוסף
  • ACCELERATOR_COUNT: מספר המאיצים שכל עותק משוכפל צריך להשתמש בהם. זה שינוי אופציונלי. צריך להיות אפס או לא מוגדר למודלים של AutoML או למודלים שאומנו בהתאמה אישית שמשתמשים בתמונות שאינן GPU.
  • MIN_REPLICA_COUNT: מספר הצמתים המינימלי לפריסה הזו. אפשר להגדיל או להקטין את מספר הצמתים לפי הצורך בהתאם לעומס ההסקה, עד למספר המקסימלי של הצמתים, אבל אף פעם לא פחות ממספר הצמתים הזה. הערך הזה חייב להיות שווה ל-1 או גדול ממנו.
  • MAX_REPLICA_COUNT: המספר המקסימלי של הצמתים לפריסה הזו. אפשר להגדיל או להקטין את מספר הצמתים בהתאם לעומס ההסקה, עד למספר הצמתים הזה ולעולם לא פחות ממספר הצמתים המינימלי.
  • REQUIRED_REPLICA_COUNT: אופציונלי. מספר הצמתים הנדרש כדי שהפריסה הזו תסומן כהצלחה. הערך חייב להיות גדול מ-1 או שווה לו, וקטן ממספר הצמתים המינימלי או שווה לו. אם לא מציינים ערך, ערך ברירת המחדל הוא המספר המינימלי של צמתים.
  • TRAFFIC_SPLIT_THIS_MODEL: אחוז תנועת החיזוי לנקודת הקצה הזו שינותב למודל שנפרס באמצעות הפעולה הזו. ברירת המחדל היא 100. סכום כל האחוזים של התנועה צריך להיות 100. מידע נוסף על פיצול תנועה
  • DEPLOYED_MODEL_ID_N: אופציונלי. אם מודלים אחרים נפרסים בנקודת הקצה הזו, צריך לעדכן את אחוז חלוקת התנועה שלהם כך שסכום כל האחוזים יהיה 100.
  • TRAFFIC_SPLIT_MODEL_N: ערך אחוז פיצול התנועה למזהה המודל שנפרס.
  • PROJECT_NUMBER: מספר הפרויקט שנוצר באופן אוטומטי

ה-method של ה-HTTP וכתובת ה-URL:

POST https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/endpoints/ENDPOINT_ID:deployModel

תוכן בקשת JSON:

{
  "deployedModel": {
    "model": "projects/PROJECT/locations/us-central1/models/MODEL_ID",
    "displayName": "DEPLOYED_MODEL_NAME",
    "dedicatedResources": {
       "machineSpec": {
         "machineType": "MACHINE_TYPE",
         "acceleratorType": "ACCELERATOR_TYPE",
         "acceleratorCount": "ACCELERATOR_COUNT"
       },
       "minReplicaCount": MIN_REPLICA_COUNT,
       "maxReplicaCount": MAX_REPLICA_COUNT,
       "requiredReplicaCount": REQUIRED_REPLICA_COUNT
     },
  },
  "trafficSplit": {
    "0": TRAFFIC_SPLIT_THIS_MODEL,
    "DEPLOYED_MODEL_ID_1": TRAFFIC_SPLIT_MODEL_1,
    "DEPLOYED_MODEL_ID_2": TRAFFIC_SPLIT_MODEL_2
  },
}

כדי לשלוח את הבקשה צריך להרחיב אחת מהאפשרויות הבאות:

אתם אמורים לקבל תגובת JSON שדומה לזו:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/endpoints/ENDPOINT_ID/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.aiplatform.v1.DeployModelOperationMetadata",
    "genericMetadata": {
      "createTime": "2020-10-19T17:53:16.502088Z",
      "updateTime": "2020-10-19T17:53:16.502088Z"
    }
  }
}

Java

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Javaההוראות להגדרה במאמר מדריך למתחילים של Agent Platform באמצעות ספריות לקוח.

כדי לבצע אימות ב-Agent Platform, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.aiplatform.v1.DedicatedResources;
import com.google.cloud.aiplatform.v1.DeployModelOperationMetadata;
import com.google.cloud.aiplatform.v1.DeployModelResponse;
import com.google.cloud.aiplatform.v1.DeployedModel;
import com.google.cloud.aiplatform.v1.EndpointName;
import com.google.cloud.aiplatform.v1.EndpointServiceClient;
import com.google.cloud.aiplatform.v1.EndpointServiceSettings;
import com.google.cloud.aiplatform.v1.MachineSpec;
import com.google.cloud.aiplatform.v1.ModelName;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;

public class DeployModelCustomTrainedModelSample {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException {
    // TODO(developer): Replace these variables before running the sample.
    String project = "PROJECT";
    String endpointId = "ENDPOINT_ID";
    String modelName = "MODEL_NAME";
    String deployedModelDisplayName = "DEPLOYED_MODEL_DISPLAY_NAME";
    deployModelCustomTrainedModelSample(project, endpointId, modelName, deployedModelDisplayName);
  }

  static void deployModelCustomTrainedModelSample(
      String project, String endpointId, String model, String deployedModelDisplayName)
      throws IOException, ExecutionException, InterruptedException {
    EndpointServiceSettings settings =
        EndpointServiceSettings.newBuilder()
            .setEndpoint("us-central1-aiplatform.googleapis.com:443")
            .build();
    String location = "us-central1";

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (EndpointServiceClient client = EndpointServiceClient.create(settings)) {
      MachineSpec machineSpec = MachineSpec.newBuilder().setMachineType("n1-standard-2").build();
      DedicatedResources dedicatedResources =
          DedicatedResources.newBuilder().setMinReplicaCount(1).setMachineSpec(machineSpec).build();

      String modelName = ModelName.of(project, location, model).toString();
      DeployedModel deployedModel =
          DeployedModel.newBuilder()
              .setModel(modelName)
              .setDisplayName(deployedModelDisplayName)
              // `dedicated_resources` must be used for non-AutoML models
              .setDedicatedResources(dedicatedResources)
              .build();
      // key '0' assigns traffic for the newly deployed model
      // Traffic percentage values must add up to 100
      // Leave dictionary empty if endpoint should not accept any traffic
      Map<String, Integer> trafficSplit = new HashMap<>();
      trafficSplit.put("0", 100);
      EndpointName endpoint = EndpointName.of(project, location, endpointId);
      OperationFuture<DeployModelResponse, DeployModelOperationMetadata> response =
          client.deployModelAsync(endpoint, deployedModel, trafficSplit);

      // You can use OperationFuture.getInitialFuture to get a future representing the initial
      // response to the request, which contains information while the operation is in progress.
      System.out.format("Operation name: %s\n", response.getInitialFuture().get().getName());

      // OperationFuture.get() will block until the operation is finished.
      DeployModelResponse deployModelResponse = response.get();
      System.out.format("deployModelResponse: %s\n", deployModelResponse);
    }
  }
}

Python

במאמר התקנת Vertex AI SDK ל-Python מוסבר איך להתקין או לעדכן את Vertex AI SDK ל-Python. מידע נוסף מופיע ב מאמרי העזרה של Python API.

def deploy_model_with_dedicated_resources_sample(
    project,
    location,
    model_name: str,
    machine_type: str,
    endpoint: Optional[aiplatform.Endpoint] = None,
    deployed_model_display_name: Optional[str] = None,
    traffic_percentage: Optional[int] = 0,
    traffic_split: Optional[Dict[str, int]] = None,
    min_replica_count: int = 1,
    max_replica_count: int = 1,
    accelerator_type: Optional[str] = None,
    accelerator_count: Optional[int] = None,
    explanation_metadata: Optional[explain.ExplanationMetadata] = None,
    explanation_parameters: Optional[explain.ExplanationParameters] = None,
    metadata: Optional[Sequence[Tuple[str, str]]] = (),
    sync: bool = True,
):
    """
    model_name: A fully-qualified model resource name or model ID.
          Example: "projects/123/locations/us-central1/models/456" or
          "456" when project and location are initialized or passed.
    """

    aiplatform.init(project=project, location=location)

    model = aiplatform.Model(model_name=model_name)

    # The explanation_metadata and explanation_parameters should only be
    # provided for a custom trained model and not an AutoML model.
    model.deploy(
        endpoint=endpoint,
        deployed_model_display_name=deployed_model_display_name,
        traffic_percentage=traffic_percentage,
        traffic_split=traffic_split,
        machine_type=machine_type,
        min_replica_count=min_replica_count,
        max_replica_count=max_replica_count,
        accelerator_type=accelerator_type,
        accelerator_count=accelerator_count,
        explanation_metadata=explanation_metadata,
        explanation_parameters=explanation_parameters,
        metadata=metadata,
        sync=sync,
    )

    model.wait()

    print(model.display_name)
    print(model.resource_name)
    return model

Node.js

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Node.jsההוראות להגדרה במאמר מדריך למתחילים של Agent Platform באמצעות ספריות לקוח.

כדי לבצע אימות ב-Agent Platform, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

const automl = require('@google-cloud/automl');
const client = new automl.v1beta1.AutoMlClient();

/**
 * Demonstrates using the AutoML client to create a model.
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const projectId = '[PROJECT_ID]' e.g., "my-gcloud-project";
// const computeRegion = '[REGION_NAME]' e.g., "us-central1";
// const datasetId = '[DATASET_ID]' e.g., "TBL2246891593778855936";
// const tableId = '[TABLE_ID]' e.g., "1991013247762825216";
// const columnId = '[COLUMN_ID]' e.g., "773141392279994368";
// const modelName = '[MODEL_NAME]' e.g., "testModel";
// const trainBudget = '[TRAIN_BUDGET]' e.g., "1000",
// `Train budget in milli node hours`;

// A resource that represents Google Cloud Platform location.
const projectLocation = client.locationPath(projectId, computeRegion);

// Get the full path of the column.
const columnSpecId = client.columnSpecPath(
  projectId,
  computeRegion,
  datasetId,
  tableId,
  columnId
);

// Set target column to train the model.
const targetColumnSpec = {name: columnSpecId};

// Set tables model metadata.
const tablesModelMetadata = {
  targetColumnSpec: targetColumnSpec,
  trainBudgetMilliNodeHours: trainBudget,
};

// Set datasetId, model name and model metadata for the dataset.
const myModel = {
  datasetId: datasetId,
  displayName: modelName,
  tablesModelMetadata: tablesModelMetadata,
};

// Create a model with the model metadata in the region.
client
  .createModel({parent: projectLocation, model: myModel})
  .then(responses => {
    const initialApiResponse = responses[1];
    console.log(`Training operation name: ${initialApiResponse.name}`);
    console.log('Training started...');
  })
  .catch(err => {
    console.error(err);
  });

איך משנים את הגדרות ברירת המחדל של רישום מסקנות

קבלת סטטוס פעולה

חלק מהבקשות מפעילות תהליכים ארוכים שדורשים זמן להשלמה. הבקשות האלה מחזירות שם פעולה, שאפשר להשתמש בו כדי לראות את הסטטוס של הפעולה או לבטל אותה. Agent Platform מספקת שיטות עזר לביצוע קריאות לפעולות ממושכות. מידע נוסף זמין במאמר בנושא עבודה עם פעולות ממושכות.

קבלת הסקה אונליין באמצעות המודל שפרסתם

כדי לבצע הסקה אונליין, שולחים פריט בדיקה אחד או יותר למודל לצורך ניתוח, והמודל מחזיר תוצאות שמבוססות על היעד של המודל. משתמשים ב Google Cloud מסוף או ב-Agent Platform API כדי לבקש הסקה אונליין.

מסוף Google Cloud

  1. במסוף Google Cloud , בקטע Agent Platform, עוברים לדף Models.

    כניסה לדף Models

  2. ברשימת המודלים, לוחצים על שם המודל כדי לבקש מסקנות.

  3. בוחרים בכרטיסייה Deploy & test (פריסה ובדיקה).

  4. בקטע Test your model (בדיקת המודל), מוסיפים פריטי בדיקה כדי לבקש הסקה. נתוני ההסקה של נקודת הבסיס ימולאו בשבילכם, או שתוכלו להזין נתוני הסקה משלכם וללחוץ על חיזוי.

    אחרי שההסקה מסתיימת, Gemini Enterprise Agent Platform מחזירה את התוצאות במסוף.

‫API: סיווג

gcloud

  1. יוצרים קובץ בשם request.json עם התוכן הבא:

          {
      "instances": [
        {
          PREDICTION_DATA_ROW
        }
      ]
    }
        

    מחליפים את מה שכתוב בשדות הבאים:

    • PREDICTION_DATA_ROW: אובייקט JSON עם מפתחות כשמות התכונות וערכים כערכי התכונות התואמים. לדוגמה, אם יש לכם מערך נתונים עם שלושה מאפיינים – מספר, מערך של מחרוזות וקטגוריה – שורת הנתונים יכולה להיראות כמו בקשת הדוגמה הבאה:

      "length":3.6,
      "material":"cotton",
      "tag_array": ["abc","def"]
      

      חובה לציין ערך לכל תכונה שכלולה באימון. הפורמט של הנתונים שמשמשים להסקת מסקנות צריך להיות זהה לפורמט שמשמש לאימון. פרטים נוספים זמינים במאמר בנושא פורמט הנתונים למסקנות.

  2. מריצים את הפקודה הבאה:

    gcloud ai endpoints predict ENDPOINT_ID \
      --region=LOCATION_ID \
      --json-request=request.json

    מחליפים את מה שכתוב בשדות הבאים:

    • ENDPOINT_ID: המזהה של נקודת הקצה.
    • LOCATION_ID: האזור שבו משתמשים ב-Agent Platform.

REST

משתמשים בשיטה endpoints.predict כדי לבקש הסקה אונליין.

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • LOCATION_ID: האזור שבו נמצאת נקודת הקצה. לדוגמה, us-central1.
  • PROJECT_ID: .
  • ENDPOINT_ID: המזהה של נקודת הקצה.
  • PREDICTION_DATA_ROW: אובייקט JSON עם מפתחות כשמות התכונות וערכים כערכי התכונות התואמים. לדוגמה, אם יש לכם מערך נתונים עם שלושה מאפיינים – מספר, מערך של מחרוזות וקטגוריה – שורת הנתונים יכולה להיראות כמו בקשת הדוגמה הבאה:

    "length":3.6,
    "material":"cotton",
    "tag_array": ["abc","def"]
    

    חובה לציין ערך לכל תכונה שכלולה באימון. הפורמט של הנתונים שמשמשים להסקת מסקנות צריך להיות זהה לפורמט שמשמש לאימון. פרטים נוספים זמינים במאמר בנושא פורמט הנתונים למסקנות.

  • DEPLOYED_MODEL_ID: פלט של שיטת predict, וקלט קביל של שיטת explain. המזהה של המודל ששימש ליצירת ההיקש. אם אתם צריכים לבקש הסברים לגבי מסקנה שביקשתם בעבר, ויש לכם יותר ממודל אחד שפרסתם, אתם יכולים להשתמש במזהה הזה כדי לוודא שההסברים יוחזרו לגבי אותו מודל שסיפק את המסקנה הקודמת.

ה-method של ה-HTTP וכתובת ה-URL:

POST https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/endpoints/ENDPOINT_ID:predict

גוף בקשת JSON:

{
  "instances": [
    {
      PREDICTION_DATA_ROW
    }
  ]
}

כדי לשלוח את הבקשה עליכם לבחור אחת מהאפשרויות הבאות:

curl

שומרים את גוף הבקשה בקובץ בשם request.json ומריצים את הפקודה הבאה:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/endpoints/ENDPOINT_ID:predict"

PowerShell

שומרים את גוף הבקשה בקובץ בשם request.json ומריצים את הפקודה הבאה:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/endpoints/ENDPOINT_ID:predict" | Select-Object -Expand Content

אתם אמורים לקבל תגובת JSON שדומה לזו:

   {
     "predictions": [
      {
         "scores": [
           0.96771615743637085,
           0.032283786684274673
         ],
         "classes": [
           "0",
           "1"
         ]
      }
     ]
     "deployedModelId": "2429510197"
   }
   

Java

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Javaההוראות להגדרה במאמר מדריך למתחילים של Agent Platform באמצעות ספריות לקוח.

כדי לבצע אימות ב-Agent Platform, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


import com.google.cloud.aiplatform.util.ValueConverter;
import com.google.cloud.aiplatform.v1.EndpointName;
import com.google.cloud.aiplatform.v1.PredictResponse;
import com.google.cloud.aiplatform.v1.PredictionServiceClient;
import com.google.cloud.aiplatform.v1.PredictionServiceSettings;
import com.google.cloud.aiplatform.v1.schema.predict.prediction.TabularClassificationPredictionResult;
import com.google.protobuf.ListValue;
import com.google.protobuf.Value;
import com.google.protobuf.util.JsonFormat;
import java.io.IOException;
import java.util.List;

public class PredictTabularClassificationSample {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String project = "YOUR_PROJECT_ID";
    String instance = "[{ “feature_column_a”: “value”, “feature_column_b”: “value”}]";
    String endpointId = "YOUR_ENDPOINT_ID";
    predictTabularClassification(instance, project, endpointId);
  }

  static void predictTabularClassification(String instance, String project, String endpointId)
      throws IOException {
    PredictionServicPredictionServiceSettingsceSettings =
        PredictionServicPredictionServiceSettings          .setEndpoint("us-central1-aiplatform.googleapis.com:443")
            .build();

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (PredictionServicPredictionServiceClientceClient =
        PredictionServicPredictionServiceClientonServiceSettings)) {
      String location = "us-central1";
      EndpointName endEndpointNameEndpointName.of(EndpointNameation, endpointId);

      ListValue.BuildeListValueue = ListValue.newBuiListValue     JsonFormat.parseJsonFormatinstance, listValue);
      List<Value> instanListValuelistValue.getValuesList();

      Value parametersValuelue.newBuilderValuetListValue(listValue).build();
      PredictResponse PredictResponse =
          predictionServiceClient.predict(endpointName, instanceList, parameters);
      System.out.println("Predict Tabular Classification Response");
      System.out.format("\tDeployed Model Id: %s\n", predictResponse.predictResponse.getDeployedModelId().out.println("Predictions");
      for (Value predictionValueedictResponse.predictResponse.getPredictionsList()larClassificTabularClassificationPredictionResultuilder =
            TabularClassificTabularClassificationPredictionResult       TabularClassificTabularClassificationPredictionResult      (TabularClassificTabularClassificationPredictionResult  ValueConverter.fValueConvertertBuilder, prediction);

        for (int i = 0; i < result.getClasseresult.getClassesCount()   System.out.printf("\tClass: %s", result.getClasseresult.getClasses(i)tem.out.printf("\tScore: %f", result.getScoresresult.getScores(i)   }
    }
  }
}

Node.js

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Node.jsההוראות להגדרה במאמר מדריך למתחילים של Agent Platform באמצעות ספריות לקוח.

כדי לבצע אימות ב-Agent Platform, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

/**
 * TODO(developer): Uncomment these variables before running the sample.\
 * (Not necessary if passing values as arguments)
 */

// const endpointId = 'YOUR_ENDPOINT_ID';
// const project = 'YOUR_PROJECT_ID';
// const location = 'YOUR_PROJECT_LOCATION';
const aiplatform = require('@google-cloud/aiplatform');
const {prediction} =
  aiplatform.protos.google.cloud.aiplatform.v1.schema.predict;

// Imports the Google Cloud Prediction service client
const {PredictionServiceClient} = aiplatform.v1;

// Import the helper module for converting arbitrary protobuf.Value objects.
const {helpers} = aiplatform;

// Specifies the location of the api endpoint
const clientOptions = {
  apiEndpoint: 'us-central1-aiplatform.googleapis.com',
};

// Instantiates a client
const predictionServiceClient = new PredictionServiceClient(clientOptions);

async function predictTablesClassification() {
  // Configure the endpoint resource
  const endpoint = `projects/${project}/locations/${location}/endpoints/${endpointId}`;
  const parameters = helpers.toValue({});

  const instance = helpers.toValue({
    petal_length: '1.4',
    petal_width: '1.3',
    sepal_length: '5.1',
    sepal_width: '2.8',
  });

  const instances = [instance];
  const request = {
    endpoint,
    instances,
    parameters,
  };

  // Predict request
  const [response] = await predictionServiceClient.predict(request);

  console.log('Predict tabular classification response');
  console.log(`\tDeployed model id : ${response.deployedModelId}\n`);
  const predictions = response.predictions;
  console.log('Predictions :');
  for (const predictionResultVal of predictions) {
    const predictionResultObj =
      prediction.TabularClassificationPredictionResult.fromValue(
        predictionResultVal
      );
    for (const [i, class_] of predictionResultObj.classes.entries()) {
      console.log(`\tClass: ${class_}`);
      console.log(`\tScore: ${predictionResultObj.scores[i]}\n\n`);
    }
  }
}
predictTablesClassification();

Python

במאמר התקנת Vertex AI SDK ל-Python מוסבר איך להתקין או לעדכן את Vertex AI SDK ל-Python. מידע נוסף מופיע ב מאמרי העזרה של Python API.

def predict_tabular_classification_sample(
    project: str,
    location: str,
    endpoint_name: str,
    instances: List[Dict],
):
    """
    Args
        project: Your project ID or project number.
        location: Region where Endpoint is located. For example, 'us-central1'.
        endpoint_name: A fully qualified endpoint name or endpoint ID. Example: "projects/123/locations/us-central1/endpoints/456" or
               "456" when project and location are initialized or passed.
        instances: A list of one or more instances (examples) to return a prediction for.
    """
    aiplatform.init(project=project, location=location)

    endpoint = aiplatform.Endpoint(endpoint_name)

    response = endpoint.predict(instances=instances)

    for prediction_ in response.predictions:
        print(prediction_)

API: Regression

gcloud

  1. יוצרים קובץ בשם `request.json` עם התוכן הבא:

          {
      "instances": [
        {
          PREDICTION_DATA_ROW
        }
      ]
    }
        

    מחליפים את מה שכתוב בשדות הבאים:

    • PREDICTION_DATA_ROW: אובייקט JSON עם מפתחות כשמות התכונות וערכים כערכי התכונות התואמים. לדוגמה, אם יש לכם מערך נתונים עם שלושה מאפיינים – מספר, מערך של מספרים וקטגוריה – שורת הנתונים יכולה להיראות כמו הבקשה לדוגמה הבאה:

      "age":3.6,
      "sq_ft":5392,
      "code": "90331"
      

      חובה לציין ערך לכל תכונה שכלולה באימון. הפורמט של הנתונים שמשמשים להסקת מסקנות צריך להיות זהה לפורמט שמשמש לאימון. פרטים נוספים זמינים במאמר בנושא פורמט הנתונים למסקנות.

  2. מריצים את הפקודה הבאה:

    gcloud ai endpoints predict ENDPOINT_ID \
      --region=LOCATION_ID \
      --json-request=request.json

    מחליפים את מה שכתוב בשדות הבאים:

    • ENDPOINT_ID: המזהה של נקודת הקצה.
    • LOCATION_ID: האזור שבו משתמשים ב-Agent Platform.

REST

משתמשים בשיטה endpoints.predict כדי לבקש הסקה אונליין.

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • LOCATION_ID: האזור שבו נמצאת נקודת הקצה. לדוגמה, us-central1.
  • PROJECT_ID: .
  • ENDPOINT_ID: המזהה של נקודת הקצה.
  • PREDICTION_DATA_ROW: אובייקט JSON עם מפתחות כשמות התכונות וערכים כערכי התכונות התואמים. לדוגמה, אם יש לכם מערך נתונים עם שלושה מאפיינים – מספר, מערך של מספרים וקטגוריה – שורת הנתונים יכולה להיראות כמו הבקשה לדוגמה הבאה:

    "age":3.6,
    "sq_ft":5392,
    "code": "90331"
    

    חובה לציין ערך לכל תכונה שכלולה באימון. הפורמט של הנתונים שמשמשים להסקת מסקנות צריך להיות זהה לפורמט שמשמש לאימון. פרטים נוספים זמינים במאמר בנושא פורמט הנתונים למסקנות.

  • DEPLOYED_MODEL_ID: פלט של שיטת predict, וקלט קביל של שיטת explain. המזהה של המודל ששימש ליצירת ההיקש. אם אתם צריכים לבקש הסברים לגבי מסקנה שביקשתם בעבר, ויש לכם יותר ממודל אחד שפרסתם, אתם יכולים להשתמש במזהה הזה כדי לוודא שההסברים יוחזרו לגבי אותו מודל שסיפק את המסקנה הקודמת.

ה-method של ה-HTTP וכתובת ה-URL:

POST https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/endpoints/ENDPOINT_ID:predict

גוף בקשת JSON:

{
  "instances": [
    {
      PREDICTION_DATA_ROW
    }
  ]
}

כדי לשלוח את הבקשה עליכם לבחור אחת מהאפשרויות הבאות:

curl

שומרים את גוף הבקשה בקובץ בשם request.json ומריצים את הפקודה הבאה:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/endpoints/ENDPOINT_ID:predict"

PowerShell

שומרים את גוף הבקשה בקובץ בשם request.json ומריצים את הפקודה הבאה:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/endpoints/ENDPOINT_ID:predict" | Select-Object -Expand Content

אתם אמורים לקבל תגובת JSON שדומה לזו:


{
  "predictions": [
    [
      {
        "value": 65.14233,
        "lower_bound": 4.6572,
        "upper_bound": 164.0279
      }
    ]
  ],
  "deployedModelId": "DEPLOYED_MODEL_ID"
}

Java

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Javaההוראות להגדרה במאמר מדריך למתחילים של Agent Platform באמצעות ספריות לקוח.

כדי לבצע אימות ב-Agent Platform, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


import com.google.cloud.aiplatform.util.ValueConverter;
import com.google.cloud.aiplatform.v1.EndpointName;
import com.google.cloud.aiplatform.v1.PredictResponse;
import com.google.cloud.aiplatform.v1.PredictionServiceClient;
import com.google.cloud.aiplatform.v1.PredictionServiceSettings;
import com.google.cloud.aiplatform.v1.schema.predict.prediction.TabularRegressionPredictionResult;
import com.google.protobuf.ListValue;
import com.google.protobuf.Value;
import com.google.protobuf.util.JsonFormat;
import java.io.IOException;
import java.util.List;

public class PredictTabularRegressionSample {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String project = "YOUR_PROJECT_ID";
    String instance = "[{ “feature_column_a”: “value”, “feature_column_b”: “value”}]";
    String endpointId = "YOUR_ENDPOINT_ID";
    predictTabularRegression(instance, project, endpointId);
  }

  static void predictTabularRegression(String instance, String project, String endpointId)
      throws IOException {
    PredictionServicPredictionServiceSettingsceSettings =
        PredictionServicPredictionServiceSettings          .setEndpoint("us-central1-aiplatform.googleapis.com:443")
            .build();

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (PredictionServicPredictionServiceClientceClient =
        PredictionServicPredictionServiceClientonServiceSettings)) {
      String location = "us-central1";
      EndpointName endEndpointNameEndpointName.of(EndpointNameation, endpointId);

      ListValue.BuildeListValueue = ListValue.newBuiListValue     JsonFormat.parseJsonFormatinstance, listValue);
      List<Value> instanListValuelistValue.getValuesList();

      Value parametersValuelue.newBuilderValuetListValue(listValue).build();
      PredictResponse PredictResponse =
          predictionServiceClient.predict(endpointName, instanceList, parameters);
      System.out.println("Predict Tabular Regression Response");
      System.out.format("\tDisplay Model Id: %s\n", predictResponse.predictResponse.getDeployedModelId().out.println("Predictions");
      for (Value predictionValueedictResponse.predictResponse.getPredictionsList()larRegressioTabularRegressionPredictionResultuilder =
            TabularRegressioTabularRegressionPredictionResult        TabularRegressioTabularRegressionPredictionResult      (TabularRegressioTabularRegressionPredictionResult.fValueConvertertBuilder, prediction);

        System.out.printf("\tUpper bound: %f\n", result.getUpperBresult.getUpperBound()m.out.printf("\tLower bound: %f\n", result.getLowerBresult.getLowerBound()m.out.printf("\tValue: %f\n", result.getValue(result.getValue()
  }
}

Node.js

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Node.jsההוראות להגדרה במאמר מדריך למתחילים של Agent Platform באמצעות ספריות לקוח.

כדי לבצע אימות ב-Agent Platform, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

/**
 * TODO(developer): Uncomment these variables before running the sample.\
 * (Not necessary if passing values as arguments)
 */

// const endpointId = 'YOUR_ENDPOINT_ID';
// const project = 'YOUR_PROJECT_ID';
// const location = 'YOUR_PROJECT_LOCATION';
const aiplatform = require('@google-cloud/aiplatform');
const {prediction} =
  aiplatform.protos.google.cloud.aiplatform.v1.schema.predict;

// Imports the Google Cloud Prediction service client
const {PredictionServiceClient} = aiplatform.v1;

// Import the helper module for converting arbitrary protobuf.Value objects.
const {helpers} = aiplatform;

// Specifies the location of the api endpoint
const clientOptions = {
  apiEndpoint: 'us-central1-aiplatform.googleapis.com',
};

// Instantiates a client
const predictionServiceClient = new PredictionServiceClient(clientOptions);

async function predictTablesRegression() {
  // Configure the endpoint resource
  const endpoint = `projects/${project}/locations/${location}/endpoints/${endpointId}`;
  const parameters = helpers.toValue({});

  // TODO (erschmid): Make this less painful
  const instance = helpers.toValue({
    BOOLEAN_2unique_NULLABLE: false,
    DATETIME_1unique_NULLABLE: '2019-01-01 00:00:00',
    DATE_1unique_NULLABLE: '2019-01-01',
    FLOAT_5000unique_NULLABLE: 1611,
    FLOAT_5000unique_REPEATED: [2320, 1192],
    INTEGER_5000unique_NULLABLE: '8',
    NUMERIC_5000unique_NULLABLE: 16,
    STRING_5000unique_NULLABLE: 'str-2',
    STRUCT_NULLABLE: {
      BOOLEAN_2unique_NULLABLE: false,
      DATE_1unique_NULLABLE: '2019-01-01',
      DATETIME_1unique_NULLABLE: '2019-01-01 00:00:00',
      FLOAT_5000unique_NULLABLE: 1308,
      FLOAT_5000unique_REPEATED: [2323, 1178],
      FLOAT_5000unique_REQUIRED: 3089,
      INTEGER_5000unique_NULLABLE: '1777',
      NUMERIC_5000unique_NULLABLE: 3323,
      TIME_1unique_NULLABLE: '23:59:59.999999',
      STRING_5000unique_NULLABLE: 'str-49',
      TIMESTAMP_1unique_NULLABLE: '1546387199999999',
    },
    TIMESTAMP_1unique_NULLABLE: '1546387199999999',
    TIME_1unique_NULLABLE: '23:59:59.999999',
  });

  const instances = [instance];
  const request = {
    endpoint,
    instances,
    parameters,
  };

  // Predict request
  const [response] = await predictionServiceClient.predict(request);

  console.log('Predict tabular regression response');
  console.log(`\tDeployed model id : ${response.deployedModelId}`);
  const predictions = response.predictions;
  console.log('\tPredictions :');
  for (const predictionResultVal of predictions) {
    const predictionResultObj =
      prediction.TabularRegressionPredictionResult.fromValue(
        predictionResultVal
      );
    console.log(`\tUpper bound: ${predictionResultObj.upper_bound}`);
    console.log(`\tLower bound: ${predictionResultObj.lower_bound}`);
    console.log(`\tLower bound: ${predictionResultObj.value}`);
  }
}
predictTablesRegression();

Python

במאמר התקנת Vertex AI SDK ל-Python מוסבר איך להתקין או לעדכן את Vertex AI SDK ל-Python. מידע נוסף מופיע ב מאמרי העזרה של Python API.

def predict_tabular_regression_sample(
    project: str,
    location: str,
    endpoint_name: str,
    instances: List[Dict],
):
    aiplatform.init(project=project, location=location)

    endpoint = aiplatform.Endpoint(endpoint_name)

    response = endpoint.predict(instances=instances)

    for prediction_ in response.predictions:
        print(prediction_)

פירוש תוצאות התחזית

סיווג

מודלים של סיווג מחזירים ציון מהימנות.

ציון הביטחון מציין את עוצמת השיוך של כל סיווג או תווית לפריט בדיקה במודל. ככל שהמספר גבוה יותר, כך רמת הביטחון של המודל גבוהה יותר לגבי ההחלטה להחיל את התווית על הפריט הזה. אתם קובעים מה צריך להיות ציון מהימנות התוצאות כדי שתקבלו את התוצאות של המודל.

רגרסיה

מודלים של רגרסיה מחזירים ערך הסקה. בנוסף, כשמדובר ביעדים ב-BigQuery, הם מחזירים גם מרווח היקש. רווח ההסקה מספק טווח של ערכים שהמודל בטוח ב-95% שהוא מכיל את התוצאה בפועל.

קבלת הסבר אונליין באמצעות המודל שפרסתם

אתם יכולים לבקש הסבר על ההסקה (שנקרא גם שיוך תכונות) כדי לראות איך המודל הגיע להסקה. ערכי החשיבות של התכונות המקומיות מציינים את מידת התרומה של כל תכונה לתוצאת ההסקה. ייחוס תכונות כלול בהיקשים של Agent Platform באמצעות Vertex AI ניתן להסברה.

המסוף

כשמשתמשים במסוף Google Cloud כדי לבקש הסקה אונליין, ערכי החשיבות של התכונות המקומיות מוחזרים באופן אוטומטי.

אם השתמשתם בערכי החיזוי שמולאו מראש, כל ערכי החשיבות של התכונות המקומיות הם אפס. הסיבה לכך היא שהערכים שמולאו מראש הם נתוני התחזית הבסיסיים, ולכן התחזית שמוחזרת היא ערך התחזית הבסיסי.

gcloud

  1. יוצרים קובץ בשם request.json עם התוכן הבא:

    {
      "instances": [
        {
          PREDICTION_DATA_ROW
        }
      ]
    }
    

    מחליפים את מה שכתוב בשדות הבאים:

    • PREDICTION_DATA_ROW: אובייקט JSON עם מפתחות כשמות התכונות וערכים כערכי התכונות התואמים. לדוגמה, אם יש לכם מערך נתונים עם שלושה מאפיינים – מספר, מערך של מחרוזות וקטגוריה – שורת הנתונים יכולה להיראות כמו בקשת הדוגמה הבאה:

      "length":3.6,
      "material":"cotton",
      "tag_array": ["abc","def"]
      

      חובה לציין ערך לכל תכונה שכלולה באימון. הפורמט של הנתונים שמשמשים להסקת מסקנות צריך להיות זהה לפורמט שמשמש לאימון. פרטים נוספים זמינים במאמר בנושא פורמט הנתונים למסקנות.

  2. מריצים את הפקודה הבאה:

    gcloud ai endpoints explain ENDPOINT_ID \
      --region=LOCATION_ID \
      --json-request=request.json

    מחליפים את מה שכתוב בשדות הבאים:

    • ENDPOINT_ID: המזהה של נקודת הקצה.
    • LOCATION_ID: האזור שבו משתמשים ב-Agent Platform.

    אופציונלי: אם רוצים לשלוח בקשה להסבר לDeployedModel ספציפי ב-Endpoint, אפשר לציין את הדגל --deployed-model-id:

    gcloud ai endpoints explain ENDPOINT_ID \
      --region=LOCATION \
      --deployed-model-id=DEPLOYED_MODEL_ID \
      --json-request=request.json

    בנוסף לפלייסהולדרים שמתוארים למעלה, מחליפים את מה שכתוב בשדות הבאים:

    • DEPLOYED_MODEL_ID אופציונלי: המזהה של המודל שנפרס שרוצים לקבל עבורו הסברים. המזהה נכלל בתשובה של method ‏predict. אם אתם צריכים לבקש הסברים למודל מסוים ויש לכם יותר ממודל אחד שפרוס באותה נקודת קצה, אתם יכולים להשתמש במזהה הזה כדי לוודא שההסברים יוחזרו עבור המודל המסוים הזה.

REST

בדוגמה הבאה מוצגת בקשת הסקה אונליין עבור מודל סיווג טבלאי עם שיוך תכונות מקומי. פורמט הבקשה זהה למודלים של רגרסיה.

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • LOCATION: האזור שבו נמצאת נקודת הקצה. לדוגמה, us-central1.
  • PROJECT: .
  • ENDPOINT_ID: המזהה של נקודת הקצה.
  • PREDICTION_DATA_ROW: אובייקט JSON עם מפתחות כשמות התכונות וערכים כערכי התכונות התואמים. לדוגמה, אם יש לכם מערך נתונים עם שלושה מאפיינים – מספר, מערך של מחרוזות וקטגוריה – שורת הנתונים יכולה להיראות כמו בקשת הדוגמה הבאה:

    "length":3.6,
    "material":"cotton",
    "tag_array": ["abc","def"]
    

    חובה לציין ערך לכל תכונה שכלולה באימון. הפורמט של הנתונים שמשמשים להסקת מסקנות צריך להיות זהה לפורמט שמשמש לאימון. פרטים נוספים זמינים במאמר בנושא פורמט הנתונים למסקנות.

  • DEPLOYED_MODEL_ID (אופציונלי): המזהה של המודל שנפרס, שעבורו רוצים לקבל הסברים. המזהה נכלל בתשובה של method ‏predict. אם אתם צריכים לבקש הסברים למודל מסוים ויש לכם יותר ממודל אחד שפרסתם לאותה נקודת קצה, תוכלו להשתמש במזהה הזה כדי לוודא שההסברים יוחזרו למודל המסוים הזה.

ה-method של ה-HTTP וכתובת ה-URL:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/endpoints/ENDPOINT_ID:explain

גוף בקשת JSON:

{
  "instances": [
    {
      PREDICTION_DATA_ROW
    }
  ],
  "deployedModelId": "DEPLOYED_MODEL_ID"
}

כדי לשלוח את הבקשה עליכם לבחור אחת מהאפשרויות הבאות:

curl

שומרים את גוף הבקשה בקובץ בשם request.json ומריצים את הפקודה הבאה:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/endpoints/ENDPOINT_ID:explain"

PowerShell

שומרים את גוף הבקשה בקובץ בשם request.json ומריצים את הפקודה הבאה:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/endpoints/ENDPOINT_ID:explain" | Select-Object -Expand Content
 

Python

במאמר התקנת Vertex AI SDK ל-Python מוסבר איך להתקין או לעדכן את Vertex AI SDK ל-Python. מידע נוסף מופיע ב מאמרי העזרה של Python API.

def explain_sample(project: str, location: str, endpoint_id: str, instance_dict: Dict):

    aiplatform.init(project=project, location=location)

    endpoint = aiplatform.Endpoint(endpoint_id)

    response = endpoint.explain(instances=[instance_dict], parameters={})

    for explanation in response.explanations:
        print(" explanation")
        # Feature attributions.
        attributions = explanation.attributions
        for attribution in attributions:
            print("  attribution")
            print("   baseline_output_value:", attribution.baseline_output_value)
            print("   instance_output_value:", attribution.instance_output_value)
            print("   output_display_name:", attribution.output_display_name)
            print("   approximation_error:", attribution.approximation_error)
            print("   output_name:", attribution.output_name)
            output_index = attribution.output_index
            for output_index in output_index:
                print("   output_index:", output_index)

    for prediction in response.predictions:
        print(prediction)

קבלת הסברים על חיזוי שהוחזר בעבר

ההסברים מגדילים את השימוש במשאבים, ולכן כדאי להשתמש בהם רק כשצריכים אותם באופן ספציפי. לפעמים כדאי לבקש הסברים לתוצאת היקש שכבר קיבלתם, למשל אם ההיקש היה חריג חשוד טעות או לא הגיוני.

אם כל ההסקות שלכם מגיעות מאותו מודל, אתם יכולים פשוט לשלוח מחדש את נתוני הבקשה, ולבקש הסברים הפעם. עם זאת, אם יש לכם כמה מודלים שמחזירים מסקנות, אתם צריכים לוודא שאתם שולחים את בקשת ההסבר למודל הנכון. כדי לראות הסברים על מודל מסוים, צריך לכלול בבקשה את מזהה המודל שפרסתם deployedModelID, שמופיע בתגובה לבקשת ההיסק המקורית. שימו לב שמזהה המודל שנפרס שונה ממזהה המודל.

פירוש תוצאות ההסבר

כדי לחשב את חשיבות התכונה המקומית, קודם מחשבים את ציון ההסקה של ערך הבסיס. ערכי הבסיס מחושבים מנתוני האימון, באמצעות ערך החציון לתכונות מספריות והשכיח לתכונות קטגוריות. המסקנה שנוצרת מהערכים הבסיסיים היא ציון המסקנה הבסיסי. ערכי הבסיס מחושבים פעם אחת עבור מודל ולא משתנים.

לכל מאפיין, חשיבות המאפיין המקומי לגבי מסקנה ספציפית מציינת את מידת ההשפעה של המאפיין על התוצאה בהשוואה לציון הבסיסי של המסקנה. סכום כל ערכי חשיבות התכונות שווה להפרש בין ציון ההסקה של ערך הבסיס לבין תוצאת ההסקה.

במודלים של סיווג, הציון תמיד בין 0.0 ל-1.0, כולל. לכן, ערכי החשיבות של התכונות המקומיות עבור מודלים של סיווג הם תמיד בין ‎-1.0 ל-1.0 (כולל).

דוגמאות לשאילתות של שיוך מאפיינים ומידע נוסף מופיעים במאמר שיוך מאפיינים לסיווג ולרגרסיה.

פלט לדוגמה של מסקנות והסברים

סיווג

המטען הייעודי (payload) שמוחזר מהסקת מסקנות אונליין ממודל סיווג טבלאי עם חשיבות התכונות נראה דומה לדוגמה הבאה.

הערך instanceOutputValue של 0.928652400970459 הוא ציון המהימנות של הסיווג עם הציון הכי גבוה, במקרה הזה class_a. השדה baselineOutputValue מכיל את ציון ההסקה של הבסיס, 0.808652400970459. התכונה שהשפיעה הכי הרבה על התוצאה הזו הייתה feature_3.

{
"predictions": [
  {
    "scores": [
      0.928652400970459,
      0.071347599029541
    ],
    "classes": [
      "class_a",
      "class_b"
    ]
  }
]
"explanations": [
  {
    "attributions": [
      {
        "baselineOutputValue": 0.808652400970459,
        "instanceOutputValue": 0.928652400970459,
        "approximationError":  0.0058915703929231,
        "featureAttributions": {
          "feature_1": 0.012394922231235,
          "feature_2": 0.050212341234556,
          "feature_3": 0.057392736534209,
        },
        "outputIndex": [
          0
        ],
        "outputName": "scores"
      }
    ],
  }
]
"deployedModelId": "234567"
}

רגרסיה

מטען הייעודי (payload) שמוחזר עבור הסקה אונליין עם חשיבות התכונות ממודל רגרסיה טבלאי של AutoML נראה דומה לדוגמה הבאה.

הערך instanceOutputValue של 1795.1246466281819 הוא הערך הצפוי, והשדות lower_bound ו-upper_bound מספקים את הרווח בר-הסמך של 95%. השדה baselineOutputValue מכיל את ציון ההסקה של הבסיס, 1788.7423095703125. התכונה שהשפיעה הכי הרבה על התוצאה הזו הייתה feature_3.

{
"predictions": [
  {
    "value": 1795.1246466281819,
    "lower_bound": 246.32196807861328,
    "upper_bound": 8677.51904296875
  }
]
"explanations": [
  {
    "attributions": [
      {
        "baselineOutputValue": 1788.7423095703125,
        "instanceOutputValue": 1795.1246466281819,
        "approximationError": 0.0038215703911553,
        "featureAttributions": {
          "feature_1": 0.123949222312359,
          "feature_2": 0.802123412345569,
          "feature_3": 5.456264423211472,
        },
        "outputIndex": [
          -1
        ]
      }
    ]
  }
],
"deployedModelId": "345678"
}

המאמרים הבאים