데이터 세트 만들기 및 데이터 가져오기

데이터 세트에는 커스텀 모델이 사용할 카테고리 라벨로 지정해 분류하려는 콘텐츠 유형의 대표 샘플이 있습니다. 데이터 세트는 모델 학습을 위한 입력으로 사용됩니다.

데이터 세트 빌드의 주요 단계는 다음과 같습니다.

  1. 데이터 세트 리소스 만들기
  2. 데이터 세트로 학습 데이터 가져오기
  3. 문서 라벨 지정 또는 항목 식별

분류와 감정 분석의 경우 2단계와 3단계가 결합되어 라벨이 지정된 상태에서 문서를 가져오는 경우가 많습니다.

데이터 세트 만들기

커스텀 모델을 생성하는 첫 단계는 모델 학습용 데이터를 저장할 비어 있는 데이터 세트를 만드는 것입니다. 새로 만든 데이터 세트에는 문서를 가져올 때까지는 어떤 데이터도 포함되지 않습니다.

웹 UI

데이터 세트를 만들려면 다음 안내를 따르세요.

  1. AutoML Natural Language UI를 열고 학습시킬 모델 유형에 해당하는 상자에서 시작하기를 선택합니다.

    데이터 세트 페이지에는 현재 프로젝트용으로 이전에 만든 데이터 세트의 상태가 표시됩니다.

    다른 프로젝트에 데이터 세트를 추가하려면 제목 표시줄의 오른쪽 위에 있는 드롭다운 목록에서 프로젝트를 선택하세요.

  2. 제목 표시줄에서 새 데이터 세트 버튼을 클릭합니다.

  3. 데이터 세트의 이름을 입력하고 데이터 세트를 저장할 지리적 위치를 지정합니다.

    자세한 내용은 위치를 참조하세요.

  4. 이 데이터 세트를 사용하여 학습시킬 모델에서 수행할 분석 유형을 지정하는 모델 목표를 선택합니다.

    • 단일 라벨 분류는 분류된 각 문서에 단일 라벨을 부여합니다.
    • 멀티 라벨 분류를 사용하면 한 문서에 여러 라벨을 지정할 수 있습니다.
    • 항목 추출은 문서 내 항목을 식별합니다.
    • 감정 분석은 문서 내에서 감정을 분석합니다.
  5. 데이터 세트 만들기를 클릭합니다.

    새 데이터 세트의 가져오기 페이지가 표시됩니다. 데이터세트로 데이터 가져오기를 참조하세요.

코드 샘플

분류

REST

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • project-id: 프로젝트 ID입니다.
  • location-id: 리소스의 위치로, 전역 위치의 경우 us-central1, 유럽 연합의 경우 eu

HTTP 메서드 및 URL:

POST https://automl.googleapis.com/v1/projects/project-id/locations/location-id/datasets

JSON 요청 본문:

{
  "displayName": "test_dataset",
  "textClassificationDatasetMetadata": {
    "classificationType": "MULTICLASS"
  }
}

요청을 보내려면 다음 옵션 중 하나를 펼칩니다.

다음과 비슷한 JSON 응답이 표시됩니다.

{
  "name": "projects/434039606874/locations/us-central1/datasets/356587829854924648",
  "displayName": "test_dataset",
  "createTime": "2018-04-26T18:02:59.825060Z",
  "textClassificationDatasetMetadata": {
    "classificationType": "MULTICLASS"
  }
}

Python

AutoML Natural Language용 클라이언트 라이브러리를 설치하고 사용하는 방법은 AutoML Natural Language 클라이언트 라이브러리를 참조하세요. 자세한 내용은 AutoML Natural Language Python API 참조 문서를 참조하세요.

AutoML Natural Language에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

from google.cloud import automl

# TODO(developer): Uncomment and set the following variables
# project_id = "YOUR_PROJECT_ID"
# display_name = "YOUR_DATASET_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.
metadata = automl.TextClassificationDatasetMetadata(
    classification_type=automl.ClassificationType.MULTICLASS
)
dataset = automl.Dataset(
    display_name=display_name,
    text_classification_dataset_metadata=metadata,
)

# Create a dataset with the dataset metadata in the region.
response = client.create_dataset(parent=project_location, dataset=dataset)

created_dataset = response.result()

# Display the dataset information
print(f"Dataset name: {created_dataset.name}")
print("Dataset id: {}".format(created_dataset.name.split("/")[-1]))

Java

AutoML Natural Language용 클라이언트 라이브러리를 설치하고 사용하는 방법은 AutoML Natural Language 클라이언트 라이브러리를 참조하세요. 자세한 내용은 AutoML Natural Language Java API 참조 문서를 참조하세요.

AutoML Natural Language에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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.LocationName;
import com.google.cloud.automl.v1.OperationMetadata;
import com.google.cloud.automl.v1.TextClassificationDatasetMetadata;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

class LanguageTextClassificationCreateDataset {

  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;

      // Specify the text classification type for the dataset.
      TextClassificationDatasetMetadata metadata =
          TextClassificationDatasetMetadata.newBuilder()
              .setClassificationType(classificationType)
              .build();
      Dataset dataset =
          Dataset.newBuilder()
              .setDisplayName(displayName)
              .setTextClassificationDatasetMetadata(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 Natural Language용 클라이언트 라이브러리를 설치하고 사용하는 방법은 AutoML Natural Language 클라이언트 라이브러리를 참조하세요. 자세한 내용은 AutoML Natural Language Node.js API 참조 문서를 참조하세요.

AutoML Natural Language에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

/**
 * 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
  const request = {
    parent: client.locationPath(projectId, location),
    dataset: {
      displayName: displayName,
      textClassificationDatasetMetadata: {
        classificationType: 'MULTICLASS',
      },
    },
  };

  // 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();

Go

AutoML Natural Language용 클라이언트 라이브러리를 설치하고 사용하는 방법은 AutoML Natural Language 클라이언트 라이브러리를 참조하세요. 자세한 내용은 AutoML Natural Language Go API 참조 문서를 참조하세요.

AutoML Natural Language에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import (
	"context"
	"fmt"
	"io"

	automl "cloud.google.com/go/automl/apiv1"
	"cloud.google.com/go/automl/apiv1/automlpb"
)

// languageTextClassificationCreateDataset creates a dataset for text classification.
func languageTextClassificationCreateDataset(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_TextClassificationDatasetMetadata{
				TextClassificationDatasetMetadata: &automlpb.TextClassificationDatasetMetadata{
					// Specify the classification type:
					// - MULTILABEL: Multiple labels are allowed for one example.
					// - MULTICLASS: At most one label is allowed per example.
					ClassificationType: automlpb.ClassificationType_MULTICLASS,
				},
			},
		},
	}

	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
}

추가 언어

C#: 클라이언트 라이브러리 페이지의 C# 설정 안내를 따른 후 .NET용 AutoML 자연 언어 참조 문서를 참조하세요.

PHP: 클라이언트 라이브러리 페이지의 PHP 설정 안내를 따른 후 PHP용 AutoML 자연 언어 참조 문서를 참조하세요.

Ruby: 클라이언트 라이브러리 페이지의 Ruby 설정 안내를 따른 후 Ruby용 AutoML 자연 언어 참조 문서를 참조하세요.

항목 추출

REST

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • project-id: 프로젝트 ID입니다.
  • location-id: 리소스의 위치로, 전역 위치의 경우 us-central1, 유럽 연합의 경우 eu

HTTP 메서드 및 URL:

POST https://automl.googleapis.com/v1/projects/project-id/locations/location-id/datasets

JSON 요청 본문:

{
  "displayName": "test_dataset",
  "textExtractionDatasetMetadata": {
   }
}

요청을 보내려면 다음 옵션 중 하나를 펼칩니다.

다음과 비슷한 JSON 응답이 표시됩니다.

{
  name: "projects/000000000000/locations/us-central1/datasets/TEN5582774688079151104"
  display_name: "test_dataset"
  create_time {
     seconds: 1539886451
     nanos: 757650000
   }
   text_extraction_dataset_metadata {
   }
}

Python

AutoML Natural Language용 클라이언트 라이브러리를 설치하고 사용하는 방법은 AutoML Natural Language 클라이언트 라이브러리를 참조하세요. 자세한 내용은 AutoML Natural Language Python API 참조 문서를 참조하세요.

AutoML Natural Language에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

from google.cloud import automl

# TODO(developer): Uncomment and set the following variables
# project_id = "YOUR_PROJECT_ID"
# display_name = "YOUR_DATASET_NAME"

client = automl.AutoMlClient()

# A resource that represents Google Cloud Platform location.
project_location = f"projects/{project_id}/locations/us-central1"
metadata = automl.TextExtractionDatasetMetadata()
dataset = automl.Dataset(
    display_name=display_name, text_extraction_dataset_metadata=metadata
)

# Create a dataset with the dataset metadata in the region.
response = client.create_dataset(parent=project_location, dataset=dataset)

created_dataset = response.result()

# Display the dataset information
print(f"Dataset name: {created_dataset.name}")
print("Dataset id: {}".format(created_dataset.name.split("/")[-1]))

Java

AutoML Natural Language용 클라이언트 라이브러리를 설치하고 사용하는 방법은 AutoML Natural Language 클라이언트 라이브러리를 참조하세요. 자세한 내용은 AutoML Natural Language Java API 참조 문서를 참조하세요.

AutoML Natural Language에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.automl.v1.AutoMlClient;
import com.google.cloud.automl.v1.Dataset;
import com.google.cloud.automl.v1.LocationName;
import com.google.cloud.automl.v1.OperationMetadata;
import com.google.cloud.automl.v1.TextExtractionDatasetMetadata;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

class LanguageEntityExtractionCreateDataset {

  static void createDataset() 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");

      TextExtractionDatasetMetadata metadata = TextExtractionDatasetMetadata.newBuilder().build();
      Dataset dataset =
          Dataset.newBuilder()
              .setDisplayName(displayName)
              .setTextExtractionDatasetMetadata(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 Natural Language용 클라이언트 라이브러리를 설치하고 사용하는 방법은 AutoML Natural Language 클라이언트 라이브러리를 참조하세요. 자세한 내용은 AutoML Natural Language Node.js API 참조 문서를 참조하세요.

AutoML Natural Language에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

/**
 * 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
  const request = {
    parent: client.locationPath(projectId, location),
    dataset: {
      displayName: displayName,
      textExtractionDatasetMetadata: {},
    },
  };

  // 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();

Go

AutoML Natural Language용 클라이언트 라이브러리를 설치하고 사용하는 방법은 AutoML Natural Language 클라이언트 라이브러리를 참조하세요. 자세한 내용은 AutoML Natural Language Go API 참조 문서를 참조하세요.

AutoML Natural Language에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import (
	"context"
	"fmt"
	"io"

	automl "cloud.google.com/go/automl/apiv1"
	"cloud.google.com/go/automl/apiv1/automlpb"
)

// languageEntityExtractionCreateDataset creates a dataset for text entity extraction.
func languageEntityExtractionCreateDataset(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_TextExtractionDatasetMetadata{
				TextExtractionDatasetMetadata: &automlpb.TextExtractionDatasetMetadata{},
			},
		},
	}

	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
}

추가 언어

C#: 클라이언트 라이브러리 페이지의 C# 설정 안내를 따른 후 .NET용 AutoML 자연 언어 참조 문서를 참조하세요.

PHP: 클라이언트 라이브러리 페이지의 PHP 설정 안내를 따른 후 PHP용 AutoML 자연 언어 참조 문서를 참조하세요.

Ruby: 클라이언트 라이브러리 페이지의 Ruby 설정 안내를 따른 후 Ruby용 AutoML 자연 언어 참조 문서를 참조하세요.

감정 분석

REST

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • project-id: 프로젝트 ID입니다.
  • location-id: 리소스의 위치로, 전역 위치의 경우 us-central1, 유럽 연합의 경우 eu

HTTP 메서드 및 URL:

POST https://automl.googleapis.com/v1/projects/project-id/locations/location-id/datasets

JSON 요청 본문:

{
  "displayName": "test_dataset",
  "textSentimentDatasetMetadata": {
    "sentimentMax": 4
  }
}

요청을 보내려면 다음 옵션 중 하나를 펼칩니다.

다음과 비슷한 JSON 응답이 표시됩니다.

{
  name: "projects/000000000000/locations/us-central1/datasets/TST8962998974766436002"
  display_name: "test_dataset_name"
  create_time {
    seconds: 1538855662
    nanos: 51542000
  }
  text_sentiment_dataset_metadata {
    sentiment_max: 7
  }
}

Python

AutoML Natural Language용 클라이언트 라이브러리를 설치하고 사용하는 방법은 AutoML Natural Language 클라이언트 라이브러리를 참조하세요. 자세한 내용은 AutoML Natural Language Python API 참조 문서를 참조하세요.

AutoML Natural Language에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

from google.cloud import automl

# TODO(developer): Uncomment and set the following variables
# project_id = "YOUR_PROJECT_ID"
# display_name = "YOUR_DATASET_NAME"

client = automl.AutoMlClient()

# A resource that represents Google Cloud Platform location.
project_location = f"projects/{project_id}/locations/us-central1"

# Each dataset requires a sentiment score with a defined sentiment_max
# value, for more information on TextSentimentDatasetMetadata, see:
# https://cloud.google.com/natural-language/automl/docs/prepare#sentiment-analysis
# https://cloud.google.com/automl/docs/reference/rpc/google.cloud.automl.v1#textsentimentdatasetmetadata
metadata = automl.TextSentimentDatasetMetadata(
    sentiment_max=4
)  # Possible max sentiment score: 1-10

dataset = automl.Dataset(
    display_name=display_name, text_sentiment_dataset_metadata=metadata
)

# Create a dataset with the dataset metadata in the region.
response = client.create_dataset(parent=project_location, dataset=dataset)

created_dataset = response.result()

# Display the dataset information
print(f"Dataset name: {created_dataset.name}")
print("Dataset id: {}".format(created_dataset.name.split("/")[-1]))

Java

AutoML Natural Language용 클라이언트 라이브러리를 설치하고 사용하는 방법은 AutoML Natural Language 클라이언트 라이브러리를 참조하세요. 자세한 내용은 AutoML Natural Language Java API 참조 문서를 참조하세요.

AutoML Natural Language에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.automl.v1.AutoMlClient;
import com.google.cloud.automl.v1.Dataset;
import com.google.cloud.automl.v1.LocationName;
import com.google.cloud.automl.v1.OperationMetadata;
import com.google.cloud.automl.v1.TextSentimentDatasetMetadata;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

class LanguageSentimentAnalysisCreateDataset {

  static void createDataset() 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 text classification type for the dataset.
      TextSentimentDatasetMetadata metadata =
          TextSentimentDatasetMetadata.newBuilder()
              .setSentimentMax(4) // Possible max sentiment score: 1-10
              .build();
      Dataset dataset =
          Dataset.newBuilder()
              .setDisplayName(displayName)
              .setTextSentimentDatasetMetadata(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 Natural Language용 클라이언트 라이브러리를 설치하고 사용하는 방법은 AutoML Natural Language 클라이언트 라이브러리를 참조하세요. 자세한 내용은 AutoML Natural Language Node.js API 참조 문서를 참조하세요.

AutoML Natural Language에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

/**
 * 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
  const request = {
    parent: client.locationPath(projectId, location),
    dataset: {
      displayName: displayName,
      textSentimentDatasetMetadata: {
        sentimentMax: 4, // Possible max sentiment score: 1-10
      },
    },
  };

  // 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();

Go

AutoML Natural Language용 클라이언트 라이브러리를 설치하고 사용하는 방법은 AutoML Natural Language 클라이언트 라이브러리를 참조하세요. 자세한 내용은 AutoML Natural Language Go API 참조 문서를 참조하세요.

AutoML Natural Language에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import (
	"context"
	"fmt"
	"io"

	automl "cloud.google.com/go/automl/apiv1"
	"cloud.google.com/go/automl/apiv1/automlpb"
)

// languageSentimentAnalysisCreateDataset creates a dataset for text sentiment analysis.
func languageSentimentAnalysisCreateDataset(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_TextSentimentDatasetMetadata{
				TextSentimentDatasetMetadata: &automlpb.TextSentimentDatasetMetadata{
					SentimentMax: 4, // Possible max sentiment score: 1-10
				},
			},
		},
	}

	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
}

추가 언어

C#: 클라이언트 라이브러리 페이지의 C# 설정 안내를 따른 후 .NET용 AutoML 자연 언어 참조 문서를 참조하세요.

PHP: 클라이언트 라이브러리 페이지의 PHP 설정 안내를 따른 후 PHP용 AutoML 자연 언어 참조 문서를 참조하세요.

Ruby: 클라이언트 라이브러리 페이지의 Ruby 설정 안내를 따른 후 Ruby용 AutoML 자연 언어 참조 문서를 참조하세요.

데이터세트로 학습 데이터 가져오기

데이터 세트를 생성한 후 Cloud Storage 버킷에 저장된 CSV 파일에서 문서용 문서 URI 및 레이블을 가져올 수 있습니다. 데이터 준비 및 가져올 CSV 파일 만들기에 대한 자세한 내용은 학습 데이터 준비를 참조하세요.

문서를 빈 데이터 세트로 가져오거나 추가 문서를 기존 데이터 세트로 가져올 수 있습니다.

웹 UI

데이터세트로는 문서를 가져오려면 다음 안내를 따르세요.

  1. 데이터세트 페이지에서 문서를 가져올 데이터세트를 선택합니다.

  2. 가져오기 탭에서 학습 문서를 찾을 위치를 지정합니다.

    할 수 있는 작업

    • 로컬 컴퓨터 또는 Cloud Storage에서 교육 문서 및 관련 범주 레이블이 포함된 .csv 파일을 업로드하십시오.

    • 학습 문서를 포함하는 .txt, .pdf 또는 .zip 파일 모음을 로컬 컴퓨터에서 업로드합니다.

  3. 가져올 파일과 가져온 문서의 Cloud Storage 경로를 선택합니다.

  4. 가져오기를 클릭합니다.

코드 샘플

REST

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • project-id: 프로젝트 ID입니다.
  • location-id: 리소스의 위치로, 전역 위치의 경우 us-central1, 유럽 연합의 경우 eu
  • dataset-id: 데이터 세트 ID
  • bucket-name: Cloud Storage 버킷
  • csv-file-name: CSV 학습 데이터 파일

HTTP 메서드 및 URL:

POST https://automl.googleapis.com/v1/projects/project-id/locations/location-id/datasets/dataset-id:importData

JSON 요청 본문:

{
  "inputConfig": {
    "gcsSource": {
      "inputUris": ["gs://bucket-name/csv-file-name.csv"]
      }
  }
}

요청을 보내려면 다음 옵션 중 하나를 펼칩니다.

다음과 비슷한 출력이 표시됩니다. 작업 ID를 사용하여 작업 상태를 가져올 수 있습니다. 예제를 보려면 작업 상태 가져오기를 참조하세요.

{
  "name": "projects/434039606874/locations/us-central1/operations/1979469554520650937",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.automl.v1beta1.OperationMetadata",
    "createTime": "2018-04-27T01:28:36.128120Z",
    "updateTime": "2018-04-27T01:28:36.128150Z",
    "cancellable": true
  }
}

Python

AutoML Natural Language용 클라이언트 라이브러리를 설치하고 사용하는 방법은 AutoML Natural Language 클라이언트 라이브러리를 참조하세요. 자세한 내용은 AutoML Natural Language Python API 참조 문서를 참조하세요.

AutoML Natural Language에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

from google.cloud import automl

# TODO(developer): Uncomment and set the following variables
# project_id = "YOUR_PROJECT_ID"
# dataset_id = "YOUR_DATASET_ID"
# path = "gs://YOUR_BUCKET_ID/path/to/data.csv"

client = automl.AutoMlClient()
# Get the full path of the dataset.
dataset_full_id = client.dataset_path(project_id, "us-central1", dataset_id)
# Get the multiple Google Cloud Storage URIs
input_uris = path.split(",")
gcs_source = automl.GcsSource(input_uris=input_uris)
input_config = automl.InputConfig(gcs_source=gcs_source)
# Import data from the input URI
response = client.import_data(name=dataset_full_id, input_config=input_config)

print("Processing import...")
print(f"Data imported. {response.result()}")

Java

AutoML Natural Language용 클라이언트 라이브러리를 설치하고 사용하는 방법은 AutoML Natural Language 클라이언트 라이브러리를 참조하세요. 자세한 내용은 AutoML Natural Language Java API 참조 문서를 참조하세요.

AutoML Natural Language에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.automl.v1.AutoMlClient;
import com.google.cloud.automl.v1.DatasetName;
import com.google.cloud.automl.v1.GcsSource;
import com.google.cloud.automl.v1.InputConfig;
import com.google.cloud.automl.v1.OperationMetadata;
import com.google.protobuf.Empty;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

class ImportDataset {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR_PROJECT_ID";
    String datasetId = "YOUR_DATASET_ID";
    String path = "gs://BUCKET_ID/path_to_training_data.csv";
    importDataset(projectId, datasetId, path);
  }

  // Import a dataset
  static void importDataset(String projectId, String datasetId, String path)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // 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()) {
      // Get the complete path of the dataset.
      DatasetName datasetFullId = DatasetName.of(projectId, "us-central1", datasetId);

      // Get multiple Google Cloud Storage URIs to import data from
      GcsSource gcsSource =
          GcsSource.newBuilder().addAllInputUris(Arrays.asList(path.split(","))).build();

      // Import data from the input URI
      InputConfig inputConfig = InputConfig.newBuilder().setGcsSource(gcsSource).build();
      System.out.println("Processing import...");

      // Start the import job
      OperationFuture<Empty, OperationMetadata> operation =
          client.importDataAsync(datasetFullId, inputConfig);

      System.out.format("Operation name: %s%n", operation.getName());

      // If you want to wait for the operation to finish, adjust the timeout appropriately. The
      // operation will still run if you choose not to wait for it to complete. You can check the
      // status of your operation using the operation's name.
      Empty response = operation.get(45, TimeUnit.MINUTES);
      System.out.format("Dataset imported. %s%n", response);
    } catch (TimeoutException e) {
      System.out.println("The operation's polling period was not long enough.");
      System.out.println("You can use the Operation's name to get the current status.");
      System.out.println("The import job is still running and will complete as expected.");
      throw e;
    }
  }
}

Node.js

AutoML Natural Language용 클라이언트 라이브러리를 설치하고 사용하는 방법은 AutoML Natural Language 클라이언트 라이브러리를 참조하세요. 자세한 내용은 AutoML Natural Language Node.js API 참조 문서를 참조하세요.

AutoML Natural Language에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'us-central1';
// const datasetId = 'YOUR_DISPLAY_ID';
// const path = 'gs://BUCKET_ID/path_to_training_data.csv';

// Imports the Google Cloud AutoML library
const {AutoMlClient} = require('@google-cloud/automl').v1;

// Instantiates a client
const client = new AutoMlClient();

async function importDataset() {
  // Construct request
  const request = {
    name: client.datasetPath(projectId, location, datasetId),
    inputConfig: {
      gcsSource: {
        inputUris: path.split(','),
      },
    },
  };

  // Import dataset
  console.log('Proccessing import');
  const [operation] = await client.importData(request);

  // Wait for operation to complete.
  const [response] = await operation.promise();
  console.log(`Dataset imported: ${response}`);
}

importDataset();

Go

AutoML Natural Language용 클라이언트 라이브러리를 설치하고 사용하는 방법은 AutoML Natural Language 클라이언트 라이브러리를 참조하세요. 자세한 내용은 AutoML Natural Language Go API 참조 문서를 참조하세요.

AutoML Natural Language에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import (
	"context"
	"fmt"
	"io"

	automl "cloud.google.com/go/automl/apiv1"
	"cloud.google.com/go/automl/apiv1/automlpb"
)

// importDataIntoDataset imports data into a dataset.
func importDataIntoDataset(w io.Writer, projectID string, location string, datasetID string, inputURI string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// datasetID := "TRL123456789..."
	// inputURI := "gs://BUCKET_ID/path_to_training_data.csv"

	ctx := context.Background()
	client, err := automl.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("NewClient: %w", err)
	}
	defer client.Close()

	req := &automlpb.ImportDataRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/datasets/%s", projectID, location, datasetID),
		InputConfig: &automlpb.InputConfig{
			Source: &automlpb.InputConfig_GcsSource{
				GcsSource: &automlpb.GcsSource{
					InputUris: []string{inputURI},
				},
			},
		},
	}

	op, err := client.ImportData(ctx, req)
	if err != nil {
		return fmt.Errorf("ImportData: %w", err)
	}
	fmt.Fprintf(w, "Processing operation name: %q\n", op.Name())

	if err := op.Wait(ctx); err != nil {
		return fmt.Errorf("Wait: %w", err)
	}

	fmt.Fprintf(w, "Data imported.\n")

	return nil
}

추가 언어

C#: 클라이언트 라이브러리 페이지의 C# 설정 안내를 따른 후 .NET용 AutoML 자연 언어 참조 문서를 참조하세요.

PHP: 클라이언트 라이브러리 페이지의 PHP 설정 안내를 따른 후 PHP용 AutoML 자연 언어 참조 문서를 참조하세요.

Ruby: 클라이언트 라이브러리 페이지의 Ruby 설정 안내를 따른 후 Ruby용 AutoML 자연 언어 참조 문서를 참조하세요.

교육 문서에 라벨 지정

데이터 세트에 있는 각 문서에 AutoML Natural Language를 통해 유사한 문서에 라벨을 지정하는 방식으로 라벨이 지정되어야 모델 학습에 유용합니다. 학습 데이터의 품질은 생성하는 모델의 효율성에 상당한 영향을 주며, 나아가 모델에서 반환한 예측의 품질에도 영향을 줍니다. AutoML Natural Language는 학습 중에 라벨이 지정되지 않은 문서를 무시합니다.

다음 세 가지 방법으로 학습 문서에 라벨을 제공할 수 있습니다.

  • .csv 파일에 라벨을 포함합니다(분류 및 감정 분석에만 해당).
  • AutoML Natural Language UI에서 문서에 라벨을 지정합니다.
  • AI Platform Data Labeling Service를 사용하는 수동 라벨러를 통해 라벨링 요청

AutoML API에는 라벨을 지정하는 메소드가 포함되어 있지 않습니다.

.csv 파일에서 문서를 라벨링하는 방법에 대한 자세한 내용은 학습 데이터 준비를 참조하세요.

분류 및 감정 분석을 위한 라벨링

AutoML Natural Language UI에서 문서를 라벨링하려면 데이터 세트 목록 페이지에서 데이터 세트를 선택하여 세부정보를 확인합니다. 선택한 데이터 세트의 표시 이름이 제목 표시줄에 나타나고 페이지에는 데이터 세트에 있는 개별 문서가 현재 라벨과 함께 나열됩니다. 왼쪽의 탐색 메뉴에 라벨이 지정된 문서와 라벨이 지정되지 않은 문서 수에 대한 요약 정보가 표시되며 라벨 또는 감정 값을 기준으로 문서 목록을 필터링할 수 있습니다.

텍스트 항목 페이지

텍스트 항목 페이지

라벨이 지정되지 않은 문서에 라벨 또는 감정 값을 지정하거나 문서 라벨을 바꾸려면 업데이트하려는 문서와 지정하려는 라벨 또는 값을 선택합니다. 문서 라벨을 업데이트하는 방법에는 다음과 같이 두 가지가 있습니다.

  • 업데이트할 문서 옆의 체크박스를 클릭한 다음 문서 목록 상단에 표시되는 라벨 드롭다운 목록에서 적용할 라벨을 선택합니다.

  • 업데이트할 문서의 행을 클릭한 다음 텍스트 세부사항 페이지에 표시되는 목록에서 적용할 라벨이나 값을 선택합니다.

항목 추출을 위해 항목 식별

커스텀 모델 학습 전에 데이터 세트의 학습 문서에 주석을 추가해야 합니다. 가져오기 전에 학습 문서에 주석을 추가하거나 AutoML Natural Language UI에서 주석을 추가할 수 있습니다.

AutoML Natural Language UI에서 주석을 추가하려면 데이터 세트 목록 페이지에서 데이터 세트를 선택하여 세부정보를 확인합니다. 선택한 데이터 세트의 표시 이름이 제목 표시줄에 나타나고 페이지에는 데이터 세트에 있는 개별 문서와 각 문서에 추가된 주석이 함께 나열됩니다. 왼쪽의 탐색 메뉴에 라벨과 각 라벨이 표시되는 횟수가 요약되어 있습니다. 라벨을 기준으로 문서 목록을 필터링할 수도 있습니다.

주석 목록

문서에 주석을 추가하거나 삭제하려면 업데이트할 문서를 더블클릭합니다. 수정 페이지에는 이전의 모든 주석이 강조표시된 상태로 선택한 문서의 전체 텍스트가 표시됩니다.

항목 편집기

레이아웃 정보를 포함하여 가져온 PDF 학습 문서의 수정 페이지에는 일반 텍스트구조화된 텍스트의 두 가지 탭이 있습니다. 일반 텍스트 탭에는 학습 문서의 원본 콘텐츠가 서식 없이 표시됩니다. 구조화된 텍스트 탭에서 학습 문서의 기본 레이아웃을 다시 만듭니다. 일반 텍스트 탭에는 원본 PDF 파일로 연결되는 링크도 있습니다.

구조화된 텍스트 편집기

새 주석을 추가하려면 항목을 나타내는 텍스트를 강조표시하고 주석 대화상자에서 라벨을 선택한 다음 저장을 클릭합니다. 구조화된 텍스트 탭에서 주석을 추가하면 AutoML Natural Language가 페이지에서 주석의 위치를 학습 중에 고려되는 요소로 캡처합니다.

주석 추가

주석을 삭제하려면 오른쪽 라벨 목록에서 텍스트를 찾아 옆에 있는 휴지통 아이콘을 클릭합니다.