创建用于图片分类的数据集。
深入探索
如需查看包含此代码示例的详细文档,请参阅以下内容:
代码示例
Go
如需了解详情,请参阅 AutoML Vision Go API 参考文档。
如需向 AutoML Vision 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证。
import (
"context"
"fmt"
"io"
automl "cloud.google.com/go/automl/apiv1"
"cloud.google.com/go/automl/apiv1/automlpb"
)
// visionClassificationCreateDataset creates a dataset for image classification.
func visionClassificationCreateDataset(w io.Writer, projectID string, location string, datasetName string) error {
// projectID := "my-project-id"
// location := "us-central1"
// datasetName := "dataset_display_name"
ctx := context.Background()
client, err := automl.NewClient(ctx)
if err != nil {
return fmt.Errorf("NewClient: %w", err)
}
defer client.Close()
req := &automlpb.CreateDatasetRequest{
Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location),
Dataset: &automlpb.Dataset{
DisplayName: datasetName,
DatasetMetadata: &automlpb.Dataset_ImageClassificationDatasetMetadata{
ImageClassificationDatasetMetadata: &automlpb.ImageClassificationDatasetMetadata{
// Specify the classification type:
// - MULTILABEL: Multiple labels are allowed for one example.
// - MULTICLASS: At most one label is allowed per example.
ClassificationType: automlpb.ClassificationType_MULTILABEL,
},
},
},
}
op, err := client.CreateDataset(ctx, req)
if err != nil {
return fmt.Errorf("CreateDataset: %w", err)
}
fmt.Fprintf(w, "Processing operation name: %q\n", op.Name())
dataset, err := op.Wait(ctx)
if err != nil {
return fmt.Errorf("Wait: %w", err)
}
fmt.Fprintf(w, "Dataset name: %v\n", dataset.GetName())
return nil
}
Java
如需了解详情,请参阅 AutoML Vision Java API 参考文档。
如需向 AutoML Vision 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证。
import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.automl.v1.AutoMlClient;
import com.google.cloud.automl.v1.ClassificationType;
import com.google.cloud.automl.v1.Dataset;
import com.google.cloud.automl.v1.ImageClassificationDatasetMetadata;
import com.google.cloud.automl.v1.LocationName;
import com.google.cloud.automl.v1.OperationMetadata;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
class VisionClassificationCreateDataset {
public static void main(String[] args)
throws IOException, ExecutionException, InterruptedException {
// TODO(developer): Replace these variables before running the sample.
String projectId = "YOUR_PROJECT_ID";
String displayName = "YOUR_DATASET_NAME";
createDataset(projectId, displayName);
}
// Create a dataset
static void createDataset(String projectId, String displayName)
throws IOException, ExecutionException, InterruptedException {
// 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 (AutoMlClient client = AutoMlClient.create()) {
// A resource that represents Google Cloud Platform location.
LocationName projectLocation = LocationName.of(projectId, "us-central1");
// Specify the classification type
// Types:
// MultiLabel: Multiple labels are allowed for one example.
// MultiClass: At most one label is allowed per example.
ClassificationType classificationType = ClassificationType.MULTILABEL;
ImageClassificationDatasetMetadata metadata =
ImageClassificationDatasetMetadata.newBuilder()
.setClassificationType(classificationType)
.build();
Dataset dataset =
Dataset.newBuilder()
.setDisplayName(displayName)
.setImageClassificationDatasetMetadata(metadata)
.build();
OperationFuture<Dataset, OperationMetadata> future =
client.createDatasetAsync(projectLocation, dataset);
Dataset createdDataset = future.get();
// Display the dataset information.
System.out.format("Dataset name: %s\n", createdDataset.getName());
// To get the dataset id, you have to parse it out of the `name` field. As dataset Ids are
// required for other methods.
// Name Form: `projects/{project_id}/locations/{location_id}/datasets/{dataset_id}`
String[] names = createdDataset.getName().split("/");
String datasetId = names[names.length - 1];
System.out.format("Dataset id: %s\n", datasetId);
}
}
}
Node.js
如需了解详情,请参阅 AutoML Vision Node.js API 参考文档。
如需向 AutoML Vision 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证。
/**
* TODO(developer): Uncomment these variables before running the sample.
*/
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'us-central1';
// const displayName = 'YOUR_DISPLAY_NAME';
// Imports the Google Cloud AutoML library
const {AutoMlClient} = require('@google-cloud/automl').v1;
// Instantiates a client
const client = new AutoMlClient();
async function createDataset() {
// Construct request
// Specify the classification type
// Types:
// MultiLabel: Multiple labels are allowed for one example.
// MultiClass: At most one label is allowed per example.
const request = {
parent: client.locationPath(projectId, location),
dataset: {
displayName: displayName,
imageClassificationDatasetMetadata: {
classificationType: 'MULTILABEL',
},
},
};
// Create dataset
const [operation] = await client.createDataset(request);
// Wait for operation to complete.
const [response] = await operation.promise();
console.log(`Dataset name: ${response.name}`);
console.log(`
Dataset id: ${
response.name
.split('/')
[response.name.split('/').length - 1].split('\n')[0]
}`);
}
createDataset();
Python
如需了解详情,请参阅 AutoML Vision Python API 参考文档。
如需向 AutoML Vision 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证。
from google.cloud import automl
# TODO(developer): Uncomment and set the following variables
# project_id = "YOUR_PROJECT_ID"
# display_name = "your_datasets_display_name"
client = automl.AutoMlClient()
# A resource that represents Google Cloud Platform location.
project_location = f"projects/{project_id}/locations/us-central1"
# Specify the classification type
# Types:
# MultiLabel: Multiple labels are allowed for one example.
# MultiClass: At most one label is allowed per example.
# https://cloud.google.com/automl/docs/reference/rpc/google.cloud.automl.v1#classificationtype
metadata = automl.ImageClassificationDatasetMetadata(
classification_type=automl.ClassificationType.MULTILABEL
)
dataset = automl.Dataset(
display_name=display_name,
image_classification_dataset_metadata=metadata,
)
# Create a dataset with the dataset metadata in the region.
response = client.create_dataset(
parent=project_location, dataset=dataset, timeout=300
)
created_dataset = response.result()
# Display the dataset information
print(f"Dataset name: {created_dataset.name}")
print("Dataset id: {}".format(created_dataset.name.split("/")[-1]))
后续步骤
如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器。