קבלת הסקות ממודל לזיהוי אובייקטים בתמונה

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

ההבדל בין הסקות אונליין לבין הסקות באצווה

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

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

קבלת הסקות אונליין

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

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

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

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

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

מסוף Google Cloud

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

    כניסה לדף Models

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

  3. לוחצים על הכרטיסייה Deploy & Test.

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

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

  5. כדי לפרוס את המודל בנקודת קצה חדשה, בוחרים באפשרות Create new endpoint ונותנים שם לנקודת הקצה החדשה. כדי לפרוס את המודל בנקודת קצה קיימת, בוחרים באפשרות Add to existing endpoint ובוחרים את נקודת הקצה מהרשימה הנפתחת.

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

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

  7. בוחרים באפשרות AutoML Image ומגדירים אותה באופן הבא:

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

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

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

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

    4. רק במודלים של סיווג (אופציונלי): בקטע Explainability options, בוחרים באפשרות Enable feature attributions for this model כדי להפעיל את Vertex AI ניתן להסברה. מאשרים את הגדרות התצוגה החזותית הקיימות או בוחרים ערכים חדשים ולוחצים על Done.

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

    5. לוחצים על Done במודל, וכשכל האחוזים של חלוקת התנועה נכונים, לוחצים על Continue.

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

    6. לוחצים על Deploy כדי לפרוס את המודל בנקודת הקצה.

API

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

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

יצירת נקודת קצה (endpoint)

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

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: מזהה הפרויקט. .
  • ‫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. מידע נוסף מופיע במאמרי העזרה של ה-API מבוסס-Python.

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 בלי לפצל את התנועה בין כמה משאבי DeployedModel:

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

  • ‫ENDPOINT_ID: המזהה של נקודת הקצה.
  • ‫LOCATION_ID: האזור שבו אתם משתמשים ב-Agent Platform.
  • ‫MODEL_ID: המזהה של המודל לפריסה.
  • ‫DEPLOYED_MODEL_NAME: שם ל-DeployedModel. אפשר להשתמש בשם המוצג של Model גם בשביל DeployedModel.
  • ‫MIN_REPLICA_COUNT: המספר המינימלי של הצמתים לפריסה הזו. אפשר להגדיל או להקטין את מספר הצמתים לפי הצורך של עומס ההסקה, עד למספר המקסימלי של הצמתים ולעולם לא פחות מהמספר הזה של הצמתים.
  • ‫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 \
  --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 `
  --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 ^
  --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 כבר יש משאבי DeployedModel אחרים, אפשר לפצל את התנועה בין משאבי ה-DeployedModel החדשים והישנים. לדוגמה, כדי לשלוח 20% מהתנועה לגרסה החדשה של DeployedModel ו-80% לגרסה ישנה יותר, מריצים את הפקודה הבאה.

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

  • ‫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 \ 
  --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 \ 
  --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 \ 
  --min-replica-count=MIN_REPLICA_COUNT ^
  --max-replica-count=MAX_REPLICA_COUNT ^
  --traffic-split=0=20,OLD_DEPLOYED_MODEL_ID=80
 

REST

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

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

  • ‫LOCATION_ID: האזור שבו אתם משתמשים ב-Agent Platform.
  • PROJECT_ID: .
  • ‫ENDPOINT_ID: המזהה של נקודת הקצה.
  • ‫MODEL_ID: המזהה של המודל לפריסה.
  • ‫DEPLOYED_MODEL_NAME: שם ל-DeployedModel. אפשר להשתמש בשם המוצג של Model גם בשביל DeployedModel.
  • ‫MIN_REPLICA_COUNT: המספר המינימלי של הצמתים לפריסה הזו. אפשר להגדיל או להקטין את מספר הצמתים לפי הצורך של עומס ההסקה, עד למספר המקסימלי של הצמתים ולעולם לא פחות מהמספר הזה של הצמתים.
  • ‫MAX_REPLICA_COUNT: המספר המקסימלי של הצמתים בפריסה הזו. אפשר להגדיל או להקטין את מספר הצמתים בהתאם לעומס ההסקה, עד למספר הצמתים הזה, ולא פחות ממספר הצמתים המינימלי.
  • ‫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_ID/locations/LOCATION_ID/models/MODEL_ID",
    "displayName": "DEPLOYED_MODEL_NAME",
    "automaticResources": {
       "minReplicaCount": MIN_REPLICA_COUNT,
       "maxReplicaCount": MAX_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_ID/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.api.gax.longrunning.OperationTimedPollAlgorithm;
import com.google.api.gax.retrying.RetrySettings;
import com.google.cloud.aiplatform.v1.AutomaticResources;
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 com.google.cloud.aiplatform.v1.stub.EndpointServiceStubSettings;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.threeten.bp.Duration;

public class DeployModelSample {

  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 deployedModelDisplayName = "YOUR_DEPLOYED_MODEL_DISPLAY_NAME";
    String endpointId = "YOUR_ENDPOINT_NAME";
    String modelId = "YOUR_MODEL_ID";
    int timeout = 900;
    deployModelSample(project, deployedModelDisplayName, endpointId, modelId, timeout);
  }

  static void deployModelSample(
      String project,
      String deployedModelDisplayName,
      String endpointId,
      String modelId,
      int timeout)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {

    // Set long-running operations (LROs) timeout
    final OperationTimedPollAlgorithm operationTimedPollAlgorithm =
        OperationTimedPollAlgorithm.create(
            RetrySettings.newBuilder()
                .setInitialRetryDelay(Duration.ofMillis(5000L))
                .setRetryDelayMultiplier(1.5)
                .setMaxRetryDelay(Duration.ofMillis(45000L))
                .setInitialRpcTimeout(Duration.ZERO)
                .setRpcTimeoutMultiplier(1.0)
                .setMaxRpcTimeout(Duration.ZERO)
                .setTotalTimeout(Duration.ofSeconds(timeout))
                .build());

    EndpointServiceStubSettings.Builder endpointServiceStubSettingsBuilder =
        EndpointServiceStubSettings.newBuilder();
    endpointServiceStubSettingsBuilder
        .deployModelOperationSettings()
        .setPollingAlgorithm(operationTimedPollAlgorithm);
    EndpointServiceStubSettings endpointStubSettings = endpointServiceStubSettingsBuilder.build();
    EndpointServiceSettings endpointServiceSettings =
        EndpointServiceSettings.create(endpointStubSettings);
    endpointServiceSettings =
        endpointServiceSettings.toBuilder()
            .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";
      EndpointName endpointName = EndpointName.of(project, location, endpointId);
      // 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);
      ModelName modelName = ModelName.of(project, location, modelId);
      AutomaticResources automaticResourcesInput =
          AutomaticResources.newBuilder().setMinReplicaCount(1).setMaxReplicaCount(1).build();
      DeployedModel deployedModelInput =
          DeployedModel.newBuilder()
              .setModel(modelName.toString())
              .setDisplayName(deployedModelDisplayName)
              .setAutomaticResources(automaticResourcesInput)
              .build();

      OperationFuture<DeployModelResponse, DeployModelOperationMetadata> deployModelResponseFuture =
          endpointServiceClient.deployModelAsync(endpointName, deployedModelInput, trafficSplit);
      System.out.format(
          "Operation name: %s\n", deployModelResponseFuture.getInitialFuture().get().getName());
      System.out.println("Waiting for operation to finish...");
      DeployModelResponse deployModelResponse = deployModelResponseFuture.get(20, TimeUnit.MINUTES);

      System.out.println("Deploy Model Response");
      DeployedModel deployedModel = deployModelResponse.getDeployedModel();
      System.out.println("\tDeployed Model");
      System.out.format("\t\tid: %s\n", deployedModel.getId());
      System.out.format("\t\tmodel: %s\n", deployedModel.getModel());
      System.out.format("\t\tDisplay Name: %s\n", deployedModel.getDisplayName());
      System.out.format("\t\tCreate Time: %s\n", deployedModel.getCreateTime());

      DedicatedResources dedicatedResources = deployedModel.getDedicatedResources();
      System.out.println("\t\tDedicated Resources");
      System.out.format("\t\t\tMin Replica Count: %s\n", dedicatedResources.getMinReplicaCount());

      MachineSpec machineSpec = dedicatedResources.getMachineSpec();
      System.out.println("\t\t\tMachine Spec");
      System.out.format("\t\t\t\tMachine Type: %s\n", machineSpec.getMachineType());
      System.out.format("\t\t\t\tAccelerator Type: %s\n", machineSpec.getAcceleratorType());
      System.out.format("\t\t\t\tAccelerator Count: %s\n", machineSpec.getAcceleratorCount());

      AutomaticResources automaticResources = deployedModel.getAutomaticResources();
      System.out.println("\t\tAutomatic Resources");
      System.out.format("\t\t\tMin Replica Count: %s\n", automaticResources.getMinReplicaCount());
      System.out.format("\t\t\tMax Replica Count: %s\n", automaticResources.getMaxReplicaCount());
    }
  }
}

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 modelId = "YOUR_MODEL_ID";
// const endpointId = 'YOUR_ENDPOINT_ID';
// const deployedModelDisplayName = 'YOUR_DEPLOYED_MODEL_DISPLAY_NAME';
// const project = 'YOUR_PROJECT_ID';
// const location = 'YOUR_PROJECT_LOCATION';

const modelName = `projects/${project}/locations/${location}/models/${modelId}`;
const endpoint = `projects/${project}/locations/${location}/endpoints/${endpointId}`;
// 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 deployModel() {
  // Configure the parent resource
  // 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
  const trafficSplit = {0: 100};
  const deployedModel = {
    // format: 'projects/{project}/locations/{location}/models/{model}'
    model: modelName,
    displayName: deployedModelDisplayName,
    automaticResources: {minReplicaCount: 1, maxReplicaCount: 1},
  };
  const request = {
    endpoint,
    deployedModel,
    trafficSplit,
  };

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

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

  console.log('Deploy model response');
  const modelDeployed = result.deployedModel;
  console.log('\tDeployed model');
  if (!modelDeployed) {
    console.log('\t\tId : {}');
    console.log('\t\tModel : {}');
    console.log('\t\tDisplay name : {}');
    console.log('\t\tCreate time : {}');

    console.log('\t\tDedicated resources');
    console.log('\t\t\tMin replica count : {}');
    console.log('\t\t\tMachine spec {}');
    console.log('\t\t\t\tMachine type : {}');
    console.log('\t\t\t\tAccelerator type : {}');
    console.log('\t\t\t\tAccelerator count : {}');

    console.log('\t\tAutomatic resources');
    console.log('\t\t\tMin replica count : {}');
    console.log('\t\t\tMax replica count : {}');
  } else {
    console.log(`\t\tId : ${modelDeployed.id}`);
    console.log(`\t\tModel : ${modelDeployed.model}`);
    console.log(`\t\tDisplay name : ${modelDeployed.displayName}`);
    console.log(`\t\tCreate time : ${modelDeployed.createTime}`);

    const dedicatedResources = modelDeployed.dedicatedResources;
    console.log('\t\tDedicated resources');
    if (!dedicatedResources) {
      console.log('\t\t\tMin replica count : {}');
      console.log('\t\t\tMachine spec {}');
      console.log('\t\t\t\tMachine type : {}');
      console.log('\t\t\t\tAccelerator type : {}');
      console.log('\t\t\t\tAccelerator count : {}');
    } else {
      console.log(
        `\t\t\tMin replica count : \
          ${dedicatedResources.minReplicaCount}`
      );
      const machineSpec = dedicatedResources.machineSpec;
      console.log('\t\t\tMachine spec');
      console.log(`\t\t\t\tMachine type : ${machineSpec.machineType}`);
      console.log(
        `\t\t\t\tAccelerator type : ${machineSpec.acceleratorType}`
      );
      console.log(
        `\t\t\t\tAccelerator count : ${machineSpec.acceleratorCount}`
      );
    }

    const automaticResources = modelDeployed.automaticResources;
    console.log('\t\tAutomatic resources');
    if (!automaticResources) {
      console.log('\t\t\tMin replica count : {}');
      console.log('\t\t\tMax replica count : {}');
    } else {
      console.log(
        `\t\t\tMin replica count : \
          ${automaticResources.minReplicaCount}`
      );
      console.log(
        `\t\t\tMax replica count : \
          ${automaticResources.maxReplicaCount}`
      );
    }
  }
}
deployModel();

Python

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

def deploy_model_with_automatic_resources_sample(
    project,
    location,
    model_name: 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,
    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)

    model.deploy(
        endpoint=endpoint,
        deployed_model_display_name=deployed_model_display_name,
        traffic_percentage=traffic_percentage,
        traffic_split=traffic_split,
        min_replica_count=min_replica_count,
        max_replica_count=max_replica_count,
        metadata=metadata,
        sync=sync,
    )

    model.wait()

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

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

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

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

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

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

המסוף

משתמשים במסוף Google Cloud כדי לשלוח בקשה להסקה אונליין. צריך לפרוס את המודל בנקודת קצה.

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

    כניסה לדף Models

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

  3. לוחצים על הכרטיסייה Deploy & test.

  4. בקטע Test your model, מוסיפים פריטי בדיקה כדי לבקש הסקת מסקנות.

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

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

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

API

משתמשים ב-Agent Platform API כדי לבקש הסקת מסקנות אונליין. צריך לפרוס את המודל בנקודת קצה.

המטרות של סוג הנתונים "תמונה" כוללות סיווג וזיהוי אובייקטים.

הסקת מסקנות במודל Edge: כשמשתמשים במודלים של AutoML Image Edge להסקת מסקנות, צריך להמיר כל קובץ להסקת מסקנות שהוא לא בפורמט JPEG לקובץ בפורמט JPEG לפני ששולחים את הבקשה להסקת מסקנות.

gcloud

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

    {
      "instances": [{
        "content": "CONTENT"
      }],
      "parameters": {
        "confidenceThreshold": THRESHOLD_VALUE,
        "maxPredictions": MAX_PREDICTIONS
      }
    }
    

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

    • ‫CONTENT: תוכן התמונה בקידוד base64.
    • THRESHOLD_VALUE אופציונלי: המודל מחזיר רק חיזויים עם ציוני סמך בערך הזה לפחות.
    • ‫MAX_PREDICTIONS אופציונלי: המודל מחזיר עד מספר החיזויים הזה עם ציוני המהימנות הגבוהים ביותר.
  2. מריצים את הפקודה הבאה:

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

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

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

REST

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

  • ‫LOCATION_ID: האזור שבו נמצאת נקודת הקצה. לדוגמה: us-central1.
  • PROJECT_ID: .
  • ‫ENDPOINT_ID: המזהה של נקודת הקצה.
  • ‫CONTENT: תוכן התמונה בקידוד base64.
  • THRESHOLD_VALUE אופציונלי: המודל מחזיר רק חיזויים עם ציוני סמך בערך הזה לפחות.
  • ‫MAX_PREDICTIONS אופציונלי: המודל מחזיר עד מספר החיזויים הזה עם ציוני המהימנות הגבוהים ביותר.

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

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

גוף בקשת JSON:

{
  "instances": [{
    "content": "CONTENT"
  }],
  "parameters": {
    "confidenceThreshold": THRESHOLD_VALUE,
    "maxPredictions": MAX_PREDICTIONS
  }
}

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

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": [
    {
      "confidences": [
        0.975873291,
        0.972160876,
        0.879488528,
        0.866532683,
        0.686478078
      ],
      "displayNames": [
        "Salad",
        "Salad",
        "Tomato",
        "Tomato",
        "Salad"
      ],
      "ids": [
        "7517774415476555776",
        "7517774415476555776",
        "2906088397049167872",
        "2906088397049167872",
        "7517774415476555776"
      ],
      "bboxes": [
        [
          0.0869686604,
          0.977020741,
          0.395135701,
          1
        ],
        [
          0,
          0.488701463,
          0.00157663226,
          0.512249
        ],
        [
          0.361617863,
          0.509664357,
          0.772928834,
          0.914706349
        ],
        [
          0.310678929,
          0.45781514,
          0.565507233,
          0.711237729
        ],
        [
          0.584359646,
          1,
          0.00116168708,
          0.130817384
        ]
      ]
    }
  ],
  "deployedModelId": "3860570043075002368"
}

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.instance.ImageObjectDetectionPredictionInstance;
import com.google.cloud.aiplatform.v1.schema.predict.params.ImageObjectDetectionPredictionParams;
import com.google.cloud.aiplatform.v1.schema.predict.prediction.ImageObjectDetectionPredictionResult;
import com.google.protobuf.Value;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

public class PredictImageObjectDetectionSample {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String project = "YOUR_PROJECT_ID";
    String fileName = "YOUR_IMAGE_FILE_PATH";
    String endpointId = "YOUR_ENDPOINT_ID";
    predictImageObjectDetection(project, fileName, endpointId);
  }

  static void predictImageObjectDetection(String project, String fileName, String endpointId)
      throws IOException {
    PredictionServiceSettings settings =
        PredictionServiceSettings.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 (PredictionServiceClient predictionServiceClient =
        PredictionServiceClient.create(settings)) {
      String location = "us-central1";
      EndpointName endpointName = EndpointName.of(project, location, endpointId);

      byte[] contents = Base64.getEncoder().encode(Files.readAllBytes(Paths.get(fileName)));
      String content = new String(contents, StandardCharsets.UTF_8);

      ImageObjectDetectionPredictionParams params =
          ImageObjectDetectionPredictionParams.newBuilder()
              .setConfidenceThreshold((float) (0.5))
              .setMaxPredictions(5)
              .build();

      ImageObjectDetectionPredictionInstance instance =
          ImageObjectDetectionPredictionInstance.newBuilder().setContent(content).build();

      List<Value> instances = new ArrayList<>();
      instances.add(ValueConverter.toValue(instance));

      PredictResponse predictResponse =
          predictionServiceClient.predict(endpointName, instances, ValueConverter.toValue(params));
      System.out.println("Predict Image Object Detection Response");
      System.out.format("\tDeployed Model Id: %s\n", predictResponse.getDeployedModelId());

      System.out.println("Predictions");
      for (Value prediction : predictResponse.getPredictionsList()) {

        ImageObjectDetectionPredictionResult.Builder resultBuilder =
            ImageObjectDetectionPredictionResult.newBuilder();

        ImageObjectDetectionPredictionResult result =
            (ImageObjectDetectionPredictionResult)
                ValueConverter.fromValue(resultBuilder, prediction);

        for (int i = 0; i < result.getIdsCount(); i++) {
          System.out.printf("\tDisplay name: %s\n", result.getDisplayNames(i));
          System.out.printf("\tConfidences: %f\n", result.getConfidences(i));
          System.out.printf("\tIDs: %d\n", result.getIds(i));
          System.out.printf("\tBounding boxes: %s\n", result.getBboxes(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 filename = "YOUR_PREDICTION_FILE_NAME";
// const endpointId = "YOUR_ENDPOINT_ID";
// const project = 'YOUR_PROJECT_ID';
// const location = 'YOUR_PROJECT_LOCATION';
const aiplatform = require('@google-cloud/aiplatform');
const {instance, params, prediction} =
  aiplatform.protos.google.cloud.aiplatform.v1.schema.predict;

// Imports the Google Cloud Prediction Service Client library
const {PredictionServiceClient} = aiplatform.v1;

// 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 predictImageObjectDetection() {
  // Configure the endpoint resource
  const endpoint = `projects/${project}/locations/${location}/endpoints/${endpointId}`;

  const parametersObj = new params.ImageObjectDetectionPredictionParams({
    confidenceThreshold: 0.5,
    maxPredictions: 5,
  });
  const parameters = parametersObj.toValue();

  const fs = require('fs');
  const image = fs.readFileSync(filename, 'base64');
  const instanceObj = new instance.ImageObjectDetectionPredictionInstance({
    content: image,
  });

  const instanceVal = instanceObj.toValue();
  const instances = [instanceVal];
  const request = {
    endpoint,
    instances,
    parameters,
  };

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

  console.log('Predict image object detection response');
  console.log(`\tDeployed model id : ${response.deployedModelId}`);
  const predictions = response.predictions;
  console.log('Predictions :');
  for (const predictionResultVal of predictions) {
    const predictionResultObj =
      prediction.ImageObjectDetectionPredictionResult.fromValue(
        predictionResultVal
      );
    for (const [i, label] of predictionResultObj.displayNames.entries()) {
      console.log(`\tDisplay name: ${label}`);
      console.log(`\tConfidences: ${predictionResultObj.confidences[i]}`);
      console.log(`\tIDs: ${predictionResultObj.ids[i]}`);
      console.log(`\tBounding boxes: ${predictionResultObj.bboxes[i]}\n\n`);
    }
  }
}
predictImageObjectDetection();

Python

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

import base64

from google.cloud import aiplatform
from google.cloud.aiplatform.gapic.schema import predict


def predict_image_object_detection_sample(
    project: str,
    endpoint_id: str,
    filename: str,
    location: str = "us-central1",
    api_endpoint: str = "us-central1-aiplatform.googleapis.com",
):
    # The AI Platform services require regional API endpoints.
    client_options = {"api_endpoint": api_endpoint}
    # Initialize client that will be used to create and send requests.
    # This client only needs to be created once, and can be reused for multiple requests.
    client = aiplatform.gapic.PredictionServiceClient(client_options=client_options)
    with open(filename, "rb") as f:
        file_content = f.read()

    # The format of each instance should conform to the deployed model's prediction input schema.
    encoded_content = base64.b64encode(file_content).decode("utf-8")
    instance = predict.instance.ImageObjectDetectionPredictionInstance(
        content=encoded_content,
    ).to_value()
    instances = [instance]
    # See gs://google-cloud-aiplatform/schema/predict/params/image_object_detection_1.0.0.yaml for the format of the parameters.
    parameters = predict.params.ImageObjectDetectionPredictionParams(
        confidence_threshold=0.5,
        max_predictions=5,
    ).to_value()
    endpoint = client.endpoint_path(
        project=project, location=location, endpoint=endpoint_id
    )
    response = client.predict(
        endpoint=endpoint, instances=instances, parameters=parameters
    )
    print("response")
    print(" deployed_model_id:", response.deployed_model_id)
    # See gs://google-cloud-aiplatform/schema/predict/prediction/image_object_detection_1.0.0.yaml for the format of the predictions.
    predictions = response.predictions
    for prediction in predictions:
        print(" prediction:", dict(prediction))

קבלת הסקות באצווה

כדי לשלוח בקשה להסקת מסקנות באצווה, צריך לציין מקור קלט ופורמט פלט שבו Gemini Enterprise Agent Platform שומרת את תוצאות הסקת המסקנות. כדי להסיק מסקנות באצווה לסוג המודל AutoML Image, צריך קובץ קלט בפורמט JSON Lines ואת השם של קטגוריה ב-Cloud Storage שבה יישמר הפלט.

הדרישות לגבי נתוני הקלט

הקלט של בקשות Batch מציין את הפריטים שצריך לשלוח למודל לצורך היקש. במודלים לזיהוי אובייקטים בתמונות, אפשר להשתמש בקובץ JSON Lines כדי לציין רשימה של תמונות שרוצים להסיק מהן מסקנות, ואז לאחסן את קובץ ה-JSON Lines בקטגוריה של Cloud Storage. הדוגמה הבאה מציגה שורה אחת בקובץ קלט של JSON Lines:

{"content": "gs://sourcebucket/datasets/images/source_image.jpg", "mimeType": "image/jpeg"}

בקשה להסקת מסקנות באצווה

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

מסוף Google Cloud

משתמשים במסוף Google Cloud כדי לשלוח בקשה להסקה באצווה.

  1. במסוף Google Cloud , בקטע Agent Platform, נכנסים לדף Batch predictions.

    כניסה לדף Batch predictions

  2. לוחצים על Create כדי לפתוח את החלון New batch prediction ומבצעים את הפעולות הבאות:

    1. מזינים שם להסקה באצווה.
    2. בשדה Model name, בוחרים את שם המודל שבו רוצים להשתמש להסקה באצווה.
    3. בשדה Source path, מציינים את המיקום ב-Cloud Storage שבו נמצא קובץ הקלט בפורמט JSON Lines.
    4. בשדה Destination path, מציינים מיקום ב-Cloud Storage שבו יישמרו תוצאות ההסקה באצווה. פורמט ה-Output נקבע לפי מטרת המודל. מודלים של AutoML ליעדי תמונות יוצרים קובצי JSON Lines.

API

משתמשים ב-Agent Platform API כדי לשלוח בקשות להסקת מסקנות באצווה.

REST

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

  • ‫LOCATION_ID: האזור שבו המודל מאוחסן ושבו מופעלת משימת ההסקה באצווה. לדוגמה, us-central1.
  • PROJECT_ID:
  • ‫BATCH_JOB_NAME: השם המוצג של המשימה באצווה
  • ‫MODEL_ID: המזהה של המודל שבו משתמשים כדי להסיק מסקנות
  • ‫THRESHOLD_VALUE (אופציונלי): Gemini Enterprise Agent Platform מחזירה רק הסקות עם ציוני סמך בערך הזה לפחות. ערך ברירת המחדל הוא 0.0.
  • ‫MAX_PREDICTIONS (אופציונלי): Gemini Enterprise Agent Platform מחזיר עד מספר ההסקות הזה, החל מההסקות עם ציוני הסמך הגבוהים ביותר. ערך ברירת המחדל הוא 10.
  • ‫URI: ה-URI של Cloud Storage שבו נמצא קובץ ה-JSON Lines של הקלט.
  • ‫BUCKET: הקטגוריה שלכם ב-Cloud Storage
  • ‫PROJECT_NUMBER: מספר הפרויקט שנוצר באופן אוטומטי

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

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

גוף בקשת JSON:

{
    "displayName": "BATCH_JOB_NAME",
    "model": "projects/PROJECT/locations/LOCATION/models/MODEL_ID",
    "modelParameters": {
      "confidenceThreshold": THRESHOLD_VALUE,
      "maxPredictions": MAX_PREDICTIONS
    },
    "inputConfig": {
        "instancesFormat": "jsonl",
        "gcsSource": {
            "uris": ["URI"],
        },
    },
    "outputConfig": {
        "predictionsFormat": "jsonl",
        "gcsDestination": {
            "outputUriPrefix": "OUTPUT_BUCKET",
        },
    },
}

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

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/batchPredictionJobs"

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/batchPredictionJobs" | Select-Object -Expand Content

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

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION_ID/batchPredictionJobs/BATCH_JOB_ID",
  "displayName": "BATCH_JOB_NAME",
  "model": "projects/PROJECT_ID/locations/LOCATION_ID/models/MODEL_ID",
  "inputConfig": {
    "instancesFormat": "jsonl",
    "gcsSource": {
      "uris": [
        "CONTENT"
      ]
    }
  },
  "outputConfig": {
    "predictionsFormat": "jsonl",
    "gcsDestination": {
      "outputUriPrefix": "BUCKET"
    }
  },
  "state": "JOB_STATE_PENDING",
  "createTime": "2020-05-30T02:58:44.341643Z",
  "updateTime": "2020-05-30T02:58:44.341643Z",
  "modelDisplayName": "MODEL_NAME",
  "modelObjective": "MODEL_OBJECTIVE"
}

אפשר לדגום את הסטטוס של משימה באצווה באמצעות BATCH_JOB_ID עד שהערך של state הוא JOB_STATE_SUCCEEDED.

Python

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

def create_batch_prediction_job_sample(
    project: str,
    location: str,
    model_resource_name: str,
    job_display_name: str,
    gcs_source: Union[str, Sequence[str]],
    gcs_destination: str,
    sync: bool = True,
):
    aiplatform.init(project=project, location=location)

    my_model = aiplatform.Model(model_resource_name)

    batch_prediction_job = my_model.batch_predict(
        job_display_name=job_display_name,
        gcs_source=gcs_source,
        gcs_destination_prefix=gcs_destination,
        sync=sync,
    )

    batch_prediction_job.wait()

    print(batch_prediction_job.display_name)
    print(batch_prediction_job.resource_name)
    print(batch_prediction_job.state)
    return batch_prediction_job

אחזור תוצאות של הסקת מסקנות באצווה

‫Gemini Enterprise Agent Platform שולחת את הפלט של הסקת המסקנות באצווה ליעד שציינתם.

בסיום משימת ההסקה באצווה, הפלט של ההסקה נשמר בקטגוריה של Cloud Storage שציינתם בבקשה.

דוגמה לתוצאות של הסקת נתונים באצווה

הדוגמה הבאה מציגה תוצאות של הסקת אצווה ממודל לזיהוי אובייקטים בתמונה.

חשוב: התיבות התוחמות מוגדרות כך:

"bboxes": [ [xMin, xMax, yMin, yMax], ...]

כאשר xMin ו-xMax הם ערכי ה-X המינימליים והמקסימליים, ו- yMin ו-yMax הם ערכי ה-Y המינימליים והמקסימליים, בהתאמה.

{
  "instance": {"content": "gs://bucket/image.jpg", "mimeType": "image/jpeg"},
  "prediction": {
    "ids": [1, 2],
    "displayNames": ["cat", "dog"],
    "bboxes":  [
      [0.1, 0.2, 0.3, 0.4],
      [0.2, 0.3, 0.4, 0.5]
    ],
    "confidences": [0.7, 0.5]
  }
}