AutoML Natural Language API 튜토리얼

이 튜토리얼에서는 AutoML Natural Language를 사용하여 콘텐츠 분류를 위한 커스텀 모델을 생성하는 방법을 보여줍니다. 이 애플리케이션은 Kaggle 오픈소스 데이터 세트 HappyDB에서 'happy moments'로 크라우드 소싱된 코퍼스를 사용하여 커스텀 모델을 학습합니다. 결과 모델은 행복한 순간을 행복의 이유를 나타내는 카테고리로 분류합니다.

이 데이터는 크리에이티브 커먼즈 CCO: 퍼블릭 도메인 라이선스를 통해 제공됩니다.

이 튜토리얼에서는 커스텀 모델 학습, 커스텀 모델 성과 평가, 새 콘텐츠 분류에 관해 다룹니다.

기본 요건

프로젝트 환경 구성

  1. Google Cloud 계정에 로그인합니다. Google Cloud를 처음 사용하는 경우 계정을 만들고 Google 제품의 실제 성능을 평가해 보세요. 신규 고객에게는 워크로드를 실행, 테스트, 배포하는 데 사용할 수 있는 $300의 무료 크레딧이 제공됩니다.
  2. Google Cloud Console의 프로젝트 선택기 페이지에서 Google Cloud 프로젝트를 선택하거나 만듭니다.

    프로젝트 선택기로 이동

  3. Google Cloud 프로젝트에 결제가 사용 설정되어 있는지 확인합니다.

  4. API AutoML Natural Language 사용 설정

    API 사용 설정

  5. Google Cloud Console의 프로젝트 선택기 페이지에서 Google Cloud 프로젝트를 선택하거나 만듭니다.

    프로젝트 선택기로 이동

  6. Google Cloud 프로젝트에 결제가 사용 설정되어 있는지 확인합니다.

  7. API AutoML Natural Language 사용 설정

    API 사용 설정

  8. Google Cloud CLI를 설치합니다.
  9. 안내를 따라 서비스 계정을 만들고 키 파일을 다운로드합니다.
  10. 서비스 계정을 만들 때 다운로드한 서비스 계정 키 파일 경로로 GOOGLE_APPLICATION_CREDENTIALS 환경 변수를 설정합니다. 예를 들면 다음과 같습니다.
         export GOOGLE_APPLICATION_CREDENTIALS=key-file
  11. 다음 명령을 사용하여 AutoML 편집자 IAM 역할에 새 서비스 계정을 추가합니다. project-id를 Google Cloud 프로젝트 이름으로 바꾸고 service-account-name을 새 서비스 계정의 이름(예: service-account1@myproject.iam.gserviceaccount.com)으로 바꿉니다.
         gcloud auth login
         gcloud config set project project-id
         gcloud projects add-iam-policy-binding project-id 
    --member=serviceAccount:service-account-name
    --role='roles/automl.editor'
  12. AutoML Natural Language 서비스 계정으로 Google Cloud 프로젝트 리소스에 액세스하도록 허용합니다.
    gcloud projects add-iam-policy-binding project-id 
    --member="serviceAccount:custom-vision@appspot.gserviceaccount.com"
    --role="roles/storage.admin"
  13. 클라이언트 라이브러리를 설치합니다.
  14. PROJECT_ID 및 REGION_NAME 환경 변수를 설정합니다.

    project-id를 Google Cloud Platform 프로젝트의 프로젝트 ID로 바꿉니다. AutoML Natural Language는 현재 us-central1 위치가 필요합니다.
         export PROJECT_ID="project-id"
         export REGION_NAME="us-central1"
         
  15. Google Cloud Storage 버킷을 만들고 커스텀 모델 학습에 사용할 문서를 저장합니다.

    버킷 이름은 $PROJECT_ID-lcm 형식이어야 합니다. 다음 명령어는 $PROJECT_ID-lcm이라는 us-central1 리전에 스토리지 버킷을 만듭니다.
    gsutil mb -p $PROJECT_ID -c regional -l $REGION_NAME gs://$PROJECT_ID-lcm/
  16. happiness.csv 파일을 공개 버킷에서 Google Cloud Storage 버킷으로 복사합니다.

    happiness.csv 파일은 공개 버킷 cloud-ml-dataNL-classification 폴더에 있습니다.

소스 코드 파일 위치

소스 코드가 필요하면 여기에서 확인할 수 있습니다. 원할 경우 언제든지 소스 코드 파일을 Google Cloud Platform 프로젝트 폴더에 복사하세요. 또는 각 단계에 도달할 때마다 이 페이지에서 코드를 직접 복사하는 것이 좋습니다.

Python

이 튜토리얼은 다음 Python 프로그램으로 구성됩니다.

  • language_text_classification_create_dataset.py – 데이터 세트를 만드는 기능을 포함합니다.
  • import_dataset.py – 데이터 세트를 가져오는 기능을 포함합니다.
  • language_text_classification_create_model.py – 모델을 만드는 기능을 포함합니다.
  • list_model_evaluations.py – 모델 평가를 나열하는 기능을 포함합니다.
  • language_text_classification_predict.py - 예측과 관련된 기능을 포함합니다.
  • delete_model.py - 모델을 삭제하는 기능을 포함합니다.

자바

이 튜토리얼은 다음 자바 파일로 구성됩니다.

  • LanguageTextClassificationCreateDataset.java – 데이터 세트를 만드는 기능을 포함합니다.
  • ImportDataset.java – 데이터 세트를 가져오는 기능을 포함합니다.
  • LanguageTextClassificationCreateModel.java – 모델을 만드는 기능을 포함합니다.
  • ListModelEvaluations.java – 모델 평가를 나열하는 기능을 포함합니다.
  • LanguageTextClassificationPredict.java - 예측과 관련된 기능을 포함합니다.
  • DeleteModel.java – 모델을 삭제하는 기능을 포함합니다.

Node.js

이 튜토리얼은 다음 Node.js 프로그램으로 구성됩니다.

  • language_text_classification_create_dataset.js – 데이터 세트를 만드는 기능을 포함합니다.
  • import_dataset.js – 데이터 세트를 가져오는 기능을 포함합니다.
  • language_text_classification_create_model.js – 모델을 만드는 기능을 포함합니다.
  • list_model_evaluations.js – 모델 평가를 나열하는 기능을 포함합니다.
  • language_text_classification_predict.js - 예측과 관련된 기능을 포함합니다.
  • delete_model.js - 모델을 삭제하는 기능을 포함합니다.

애플리케이션 실행

1단계: 데이터 세트 생성

커스텀 모델을 생성하는 첫 단계는 모델 학습용 데이터를 저장할 비어 있는 데이터 세트를 만드는 것입니다. 데이터 세트를 생성할 때 커스텀 모델이 수행할 다음 분류 유형을 지정합니다.

  • MULTICLASS는 각 분류된 문서에 단일 라벨을 부여합니다.
  • MULTILABEL은 문서에 다중 라벨을 부여합니다.

이 튜토리얼에서는 이름이 'happydb'로 지정된 데이터 세트를 생성하고 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();

요청

create_dataset 함수를 실행하고 비어 있는 데이터 세트를 만듭니다. 다음 코드 줄을 수정해야 합니다.

  • project_id를 PROJECT_ID로 설정합니다.
  • 데이터 세트의 display_name을 설정합니다(happydb).

Python

python language_text_classification_create_dataset.py

자바

mvn compile exec:java -Dexec.mainClass="com.example.automl.LanguageTextClassificationCreateDataset"

Node.js

node language_text_classification_create_dataset.js

응답

응답에는 향후 요청에 참조할 데이터 세트 ID와 같이 새로 생성된 데이터 세트의 세부정보가 포함됩니다. 반환된 데이터 세트 ID 값에 환경 변수 DATASET_ID를 설정하는 것이 좋습니다.

Dataset name: projects/216065747626/locations/us-central1/datasets/TCN7372141011130533778
Dataset id: TCN7372141011130533778
Dataset display name: happydb
Text classification dataset specification:
       classification_type: MULTICLASS
Dataset example count: 0
Dataset create time:
       seconds: 1530251987
       nanos: 216586000

2단계: 학습 항목을 데이터 세트로 가져오기

다음 단계는 타겟 카테고리를 사용해 라벨이 지정된 학습 항목 목록을 데이터 세트에 입력하는 것입니다.

import_dataset 함수 인터페이스는 모든 학습 문서의 위치와 각 학습 문서에 적절한 라벨을 나열하는 .csv 파일을 입력으로 사용합니다. (필수 형식에 대한 자세한 내용은 학습 데이터 준비하기를 참조하세요.) 이 튜토리얼에서는 위에서 Google Cloud Storage에 업로드한 happiness.csv를 사용합니다.

코드 복사

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

요청

import_data 함수를 실행하여 학습 콘텐츠를 가져옵니다. 변경할 첫 번째 코드는 이전 단계의 데이터 세트 ID이며 두 번째 코드는 happiness.csv의 URI입니다. 다음 코드 줄을 수정해야 합니다.

  • project_id를 PROJECT_ID로 설정합니다.
  • 이전 단계의 출력에서 데이터 세트의 dataset_id를 설정합니다.
  • URI인 path를 설정합니다(gs://YOUR_PROJECT_ID-lcm/csv/happiness.csv).

Python

python import_dataset.py

자바

mvn compile exec:java -Dexec.mainClass="com.example.automl.ImportDataset"

Node.js

node import_dataset.js

응답

Processing import...
Dataset imported.

3단계: 모델 만들기(학습)

라벨이 지정된 학습 문서 데이터 세트를 만들었으므로 이제 새로운 모델을 학습할 수 있습니다.

코드 복사

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"
# display_name = "YOUR_MODEL_NAME"

client = automl.AutoMlClient()

# A resource that represents Google Cloud Platform location.
project_location = f"projects/{project_id}/locations/us-central1"
# Leave model unset to use the default base model provided by Google
metadata = automl.TextClassificationModelMetadata()
model = automl.Model(
    display_name=display_name,
    dataset_id=dataset_id,
    text_classification_model_metadata=metadata,
)

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

print(f"Training operation name: {response.operation.name}")
print("Training started...")

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

class LanguageTextClassificationCreateModel {

  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 datasetId = "YOUR_DATASET_ID";
    String displayName = "YOUR_DATASET_NAME";
    createModel(projectId, datasetId, displayName);
  }

  // Create a model
  static void createModel(String projectId, String datasetId, 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");
      // Set model metadata.
      TextClassificationModelMetadata metadata =
          TextClassificationModelMetadata.newBuilder().build();
      Model model =
          Model.newBuilder()
              .setDisplayName(displayName)
              .setDatasetId(datasetId)
              .setTextClassificationModelMetadata(metadata)
              .build();

      // Create a model with the model metadata in the region.
      OperationFuture<Model, OperationMetadata> future =
          client.createModelAsync(projectLocation, model);
      // OperationFuture.get() will block until the model is created, which may take several hours.
      // 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("Training operation name: %s\n", future.getInitialFuture().get().getName());
      System.out.println("Training started...");
    }
  }
}

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 dataset_id = 'YOUR_DATASET_ID';
// 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 createModel() {
  // Construct request
  const request = {
    parent: client.locationPath(projectId, location),
    model: {
      displayName: displayName,
      datasetId: datasetId,
      textClassificationModelMetadata: {}, // Leave unset, to use the default base model
    },
  };

  // Don't wait for the LRO
  const [operation] = await client.createModel(request);
  console.log(`Training started... ${operation}`);
  console.log(`Training operation name: ${operation.name}`);
}

createModel();

요청

create_model 함수를 호출하여 모델을 만듭니다. 데이터 세트 ID는 이전 단계의 데이터 세트 ID입니다. 다음 코드 줄을 수정해야 합니다.

  • project_id를 PROJECT_ID로 설정합니다.
  • 이전 단계의 출력에서 데이터 세트의 dataset_id를 설정합니다.
  • 모델(happydb_model)의 display_name을 설정합니다.

Python

python language_text_classification_create_model.py

자바

mvn compile exec:java -Dexec.mainClass="com.example.automl.LanguageTextClassificationCreateModel"

Node.js

node language_text_classification_create_model.js

응답

create_model 함수는 학습 작업을 시작하고 작업명을 출력합니다. 학습은 비동기식으로 진행되고 완료하는 데 시간이 걸릴 수 있으므로 작업 ID를 사용하여 학습 상태를 확인할 수 있습니다. 학습이 끝나면 create_model이 모델 ID를 반환합니다. 데이터 세트 ID와 마찬가지로 MODEL_ID 환경 변수를 반환된 모델 ID 값으로 설정할 수 있습니다.

Training operation name: projects/216065747626/locations/us-central1/operations/TCN3007727620979824033
Training started...
Model name: projects/216065747626/locations/us-central1/models/TCN7683346839371803263
Model id: TCN7683346839371803263
Model display name: happydb_model
Model create time:
        seconds: 1529649600
        nanos: 966000000
Model deployment state: deployed

4단계: 모델 평가하기

학습이 끝난 후 정밀도, 재현율, F1 점수를 검토하고 모델의 준비 상태를 평가할 수 있습니다.

display_evaluation 함수는 모델 ID를 매개변수로 사용합니다.

코드 복사

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"
# model_id = "YOUR_MODEL_ID"

client = automl.AutoMlClient()
# Get the full path of the model.
model_full_id = client.model_path(project_id, "us-central1", model_id)

print("List of model evaluations:")
for evaluation in client.list_model_evaluations(parent=model_full_id, filter=""):
    print(f"Model evaluation name: {evaluation.name}")
    print(f"Model annotation spec id: {evaluation.annotation_spec_id}")
    print(f"Create Time: {evaluation.create_time}")
    print(f"Evaluation example count: {evaluation.evaluated_example_count}")
    print(
        "Classification model evaluation metrics: {}".format(
            evaluation.classification_evaluation_metrics
        )
    )

Java

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

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


import com.google.cloud.automl.v1.AutoMlClient;
import com.google.cloud.automl.v1.ListModelEvaluationsRequest;
import com.google.cloud.automl.v1.ModelEvaluation;
import com.google.cloud.automl.v1.ModelName;
import java.io.IOException;

class ListModelEvaluations {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR_PROJECT_ID";
    String modelId = "YOUR_MODEL_ID";
    listModelEvaluations(projectId, modelId);
  }

  // List model evaluations
  static void listModelEvaluations(String projectId, String modelId) throws IOException {
    // 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 full path of the model.
      ModelName modelFullId = ModelName.of(projectId, "us-central1", modelId);
      ListModelEvaluationsRequest modelEvaluationsrequest =
          ListModelEvaluationsRequest.newBuilder().setParent(modelFullId.toString()).build();

      // List all the model evaluations in the model by applying filter.
      System.out.println("List of model evaluations:");
      for (ModelEvaluation modelEvaluation :
          client.listModelEvaluations(modelEvaluationsrequest).iterateAll()) {

        System.out.format("Model Evaluation Name: %s\n", modelEvaluation.getName());
        System.out.format("Model Annotation Spec Id: %s", modelEvaluation.getAnnotationSpecId());
        System.out.println("Create Time:");
        System.out.format("\tseconds: %s\n", modelEvaluation.getCreateTime().getSeconds());
        System.out.format("\tnanos: %s", modelEvaluation.getCreateTime().getNanos() / 1e9);
        System.out.format(
            "Evalution Example Count: %d\n", modelEvaluation.getEvaluatedExampleCount());
        System.out.format(
            "Classification Model Evaluation Metrics: %s\n",
            modelEvaluation.getClassificationEvaluationMetrics());
      }
    }
  }
}

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 modelId = 'YOUR_MODEL_ID';

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

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

async function listModelEvaluations() {
  // Construct request
  const request = {
    parent: client.modelPath(projectId, location, modelId),
    filter: '',
  };

  const [response] = await client.listModelEvaluations(request);

  console.log('List of model evaluations:');
  for (const evaluation of response) {
    console.log(`Model evaluation name: ${evaluation.name}`);
    console.log(`Model annotation spec id: ${evaluation.annotationSpecId}`);
    console.log(`Model display name: ${evaluation.displayName}`);
    console.log('Model create time');
    console.log(`\tseconds ${evaluation.createTime.seconds}`);
    console.log(`\tnanos ${evaluation.createTime.nanos / 1e9}`);
    console.log(
      `Evaluation example count: ${evaluation.evaluatedExampleCount}`
    );
    console.log(
      `Classification model evaluation metrics: ${evaluation.classificationEvaluationMetrics}`
    );
  }
}

listModelEvaluations();

요청

다음 요청을 실행하여 모델의 전체 평가 성능을 표시하도록 요청합니다. 다음 코드 줄을 수정해야 합니다.

  • project_id를 PROJECT_ID로 설정합니다.
  • model_id를 모델의 ID로 설정합니다.

Python

python list_model_evaluations.py

자바

mvn compile exec:java -Dexec.mainClass="com.example.automl.ListModelEvaluations"

Node.js

node list_model_evaluations.js

응답

정밀도와 재현율 점수가 너무 낮으면 학습 데이터 세트를 강화하고 모델을 재학습할 수 있습니다. 자세한 내용은 모델 평가를 참조하세요.

Precision and recall are based on a score threshold of 0.5
Model Precision: 96.3%
Model Recall: 95.7%
Model F1 score: 96.0%
Model Precision@1: 96.33%
Model Recall@1: 95.74%
Model F1 score@1: 96.04%

5단계: 모델 배포

커스텀 모델이 품질 기준을 충족하면 모델을 배포한 후 예측을 요청할 수 있습니다.

코드 복사

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"
# model_id = "YOUR_MODEL_ID"

client = automl.AutoMlClient()
# Get the full path of the model.
model_full_id = client.model_path(project_id, "us-central1", model_id)
response = client.deploy_model(name=model_full_id)

print(f"Model deployment finished. {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.DeployModelRequest;
import com.google.cloud.automl.v1.ModelName;
import com.google.cloud.automl.v1.OperationMetadata;
import com.google.protobuf.Empty;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

class DeployModel {

  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 modelId = "YOUR_MODEL_ID";
    deployModel(projectId, modelId);
  }

  // Deploy a model for prediction
  static void deployModel(String projectId, String modelId)
      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()) {
      // Get the full path of the model.
      ModelName modelFullId = ModelName.of(projectId, "us-central1", modelId);
      DeployModelRequest request =
          DeployModelRequest.newBuilder().setName(modelFullId.toString()).build();
      OperationFuture<Empty, OperationMetadata> future = client.deployModelAsync(request);

      future.get();
      System.out.println("Model deployment finished");
    }
  }
}

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 modelId = 'YOUR_MODEL_ID';

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

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

async function deployModel() {
  // Construct request
  const request = {
    name: client.modelPath(projectId, location, modelId),
  };

  const [operation] = await client.deployModel(request);

  // Wait for operation to complete.
  const [response] = await operation.promise();
  console.log(`Model deployment finished. ${response}`);
}

deployModel();

요청

deploy_model 함수의 경우 다음 코드 줄을 수정해야 합니다.

  • project_id를 PROJECT_ID로 설정합니다.
  • model_id를 모델의 ID로 설정합니다.

Python

python deploy_model.py

자바

mvn compile exec:java -Dexec.mainClass="com.example.automl.DeployModel.java"

Node.js

node deploy_model.js

응답

Model deployment finished.

6단계: 모델을 활용한 예측

모델을 배포한 후에는 모델을 사용하여 새로운 콘텐츠를 분류할 수 있습니다.

코드 복사

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"
# model_id = "YOUR_MODEL_ID"
# content = "text to predict"

prediction_client = automl.PredictionServiceClient()

# Get the full path of the model.
model_full_id = automl.AutoMlClient.model_path(project_id, "us-central1", model_id)

# Supported mime_types: 'text/plain', 'text/html'
# https://cloud.google.com/automl/docs/reference/rpc/google.cloud.automl.v1#textsnippet
text_snippet = automl.TextSnippet(content=content, mime_type="text/plain")
payload = automl.ExamplePayload(text_snippet=text_snippet)

response = prediction_client.predict(name=model_full_id, payload=payload)

for annotation_payload in response.payload:
    print(f"Predicted class name: {annotation_payload.display_name}")
    print(f"Predicted class score: {annotation_payload.classification.score}")

Java

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

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

import com.google.cloud.automl.v1.AnnotationPayload;
import com.google.cloud.automl.v1.ExamplePayload;
import com.google.cloud.automl.v1.ModelName;
import com.google.cloud.automl.v1.PredictRequest;
import com.google.cloud.automl.v1.PredictResponse;
import com.google.cloud.automl.v1.PredictionServiceClient;
import com.google.cloud.automl.v1.TextSnippet;
import java.io.IOException;

class LanguageTextClassificationPredict {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR_PROJECT_ID";
    String modelId = "YOUR_MODEL_ID";
    String content = "text to predict";
    predict(projectId, modelId, content);
  }

  static void predict(String projectId, String modelId, String content) throws IOException {
    // 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 client = PredictionServiceClient.create()) {
      // Get the full path of the model.
      ModelName name = ModelName.of(projectId, "us-central1", modelId);

      // For available mime types, see:
      // https://cloud.google.com/automl/docs/reference/rest/v1/projects.locations.models/predict#textsnippet
      TextSnippet textSnippet =
          TextSnippet.newBuilder()
              .setContent(content)
              .setMimeType("text/plain") // Types: text/plain, text/html
              .build();
      ExamplePayload payload = ExamplePayload.newBuilder().setTextSnippet(textSnippet).build();
      PredictRequest predictRequest =
          PredictRequest.newBuilder().setName(name.toString()).setPayload(payload).build();

      PredictResponse response = client.predict(predictRequest);

      for (AnnotationPayload annotationPayload : response.getPayloadList()) {
        System.out.format("Predicted class name: %s\n", annotationPayload.getDisplayName());
        System.out.format(
            "Predicted sentiment score: %.2f\n\n",
            annotationPayload.getClassification().getScore());
      }
    }
  }
}

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 modelId = 'YOUR_MODEL_ID';
// const content = 'text to predict'

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

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

async function predict() {
  // Construct request
  const request = {
    name: client.modelPath(projectId, location, modelId),
    payload: {
      textSnippet: {
        content: content,
        mimeType: 'text/plain', // Types: 'text/plain', 'text/html'
      },
    },
  };

  const [response] = await client.predict(request);

  for (const annotationPayload of response.payload) {
    console.log(`Predicted class name: ${annotationPayload.displayName}`);
    console.log(
      `Predicted class score: ${annotationPayload.classification.score}`
    );
  }
}

predict();

요청

predict 함수의 경우 다음 코드 줄을 수정해야 합니다.

  • project_id를 PROJECT_ID로 설정합니다.
  • model_id를 모델의 ID로 설정합니다.
  • 예측할 content를 설정합니다.

Python

python language_text_classification_predict.py

자바

mvn compile exec:java -Dexec.mainClass="com.example.automl.LanguageTextClassificationPredict"

Node.js

node language_text_classification_predict.js

응답

이 기능은 콘텐츠가 각 카테고리에 일치하는 정도에 따라 분류 점수를 반환합니다.

Prediction results:
Predicted class name: affection
Predicted class score: 0.9702693223953247

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"
# model_id = "YOUR_MODEL_ID"

client = automl.AutoMlClient()
# Get the full path of the model.
model_full_id = client.model_path(project_id, "us-central1", model_id)
response = client.delete_model(name=model_full_id)

print(f"Model deleted. {response.result()}")

Java

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

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

import com.google.cloud.automl.v1.AutoMlClient;
import com.google.cloud.automl.v1.ModelName;
import com.google.protobuf.Empty;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

class DeleteModel {

  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 modelId = "YOUR_MODEL_ID";
    deleteModel(projectId, modelId);
  }

  // Delete a model
  static void deleteModel(String projectId, String modelId)
      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()) {
      // Get the full path of the model.
      ModelName modelFullId = ModelName.of(projectId, "us-central1", modelId);

      // Delete a model.
      Empty response = client.deleteModelAsync(modelFullId).get();

      System.out.println("Model deletion started...");
      System.out.println(String.format("Model deleted. %s", response));
    }
  }
}

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 modelId = 'YOUR_MODEL_ID';

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

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

async function deleteModel() {
  // Construct request
  const request = {
    name: client.modelPath(projectId, location, modelId),
  };

  const [response] = await client.deleteModel(request);
  console.log(`Model deleted: ${response}`);
}

deleteModel();

요청

delete_model 작업 유형으로 요청하여 생성한 모델을 삭제합니다. 다음 코드 줄을 수정해야 합니다.

  • project_id를 PROJECT_ID로 설정합니다.
  • model_id를 모델의 ID로 설정합니다.

Python

python delete_model.py

자바

mvn compile exec:java -Dexec.mainClass="com.example.automl.DeleteModel"

Node.js

node delete_model.js

응답

Model deleted.