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

이 페이지에서는 데이터세트를 만들고 표 형식의 데이터를 데이터세트로 가져오는 방법을 설명합니다. 그런 다음 해당 데이터세트에서 AutoML Tables를 사용해 모델을 학습시킬 수 있습니다.

소개

데이터세트는 소스 테이블 데이터와 모델 학습 매개변수를 결정하는 스키마 정보가 포함된 Google Cloud 객체입니다. 데이터 세트는 모델 학습을 위한 입력으로 사용됩니다.

프로젝트는 여러 데이터 세트가 있을 수 있습니다. 사용 가능한 데이터세트 목록을 가져오거나 필요 없는 데이터세트를 삭제할 수 있습니다.

데이터세트나 스키마 정보를 업데이트하면 해당 데이터세트를 사용하는 이후의 모델도 영향을 받습니다. 학습을 이미 시작한 모델은 영향을 받지 않습니다.

시작하기 전에

AutoML Tables를 사용하려면 먼저 시작하기 전에의 지침에 따라 프로젝트를 설정해야 합니다. 데이터세트를 만들려면 먼저 학습 데이터 준비의 설명대로 학습 데이터를 만들어야 합니다.

데이터세트 만들기

콘솔

  1. Google Cloud Console의 AutoML Tables 페이지에서 데이터 세트 생성 프로세스를 시작합니다.

    AutoML Tables 페이지로 이동

  2. 데이터세트를 선택하고 새 데이터세트를 선택합니다.

  3. 데이터 세트의 이름을 입력하고 데이터 세트를 생성할 리전을 지정합니다.

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

  4. 데이터 세트 만들기를 클릭합니다.

    가져오기 탭이 표시됩니다. 이제 데이터를 가져올 수 있습니다.

REST

데이터세트를 만들려면 datasets.create 메서드를 사용합니다.

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

  • endpoint: 전역 위치인 경우 automl.googleapis.com, EU 리전인 경우 eu-automl.googleapis.com입니다.
  • project-id: Google Cloud 프로젝트 ID입니다.
  • location: 리소스의 위치로 전역인 경우 us-central1, 유럽 연합인 경우 eu입니다.
  • dataset-display-name: 데이터 세트의 표시 이름입니다.

HTTP 메서드 및 URL:

POST https://endpoint/v1beta1/projects/project-id/locations/location/datasets

JSON 요청 본문:

{
  "displayName": "dataset-display-name",
  "tablesDatasetMetadata": { },
}

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: project-id" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://endpoint/v1beta1/projects/project-id/locations/location/datasets"

PowerShell

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "project-id" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://endpoint/v1beta1/projects/project-id/locations/location/datasets" | Select-Object -Expand Content

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

{
  "name": "projects/1234/locations/us-central1/datasets/TBL6543",
  "displayName": "sample_dataset",
  "createTime": "2019-12-23T23:03:34.139313Z",
  "updateTime": "2019-12-23T23:03:34.139313Z",
  "etag": "AB3BwFq6VkX64fx7z2Y4T4z-0jUQLKgFvvtD1RcZ2oikA=",
  "tablesDatasetMetadata": {
    "areStatsFresh": true
    "statsUpdateTime": "1970-01-01T00:00:00Z",
    "tablesDatasetType": "BASIC"
  }
}

데이터 세트로 항목 가져오기나 모델 학습과 같은 다른 작업에 사용할 수 있도록 (응답에서) 새 데이터 세트의 name을 저장합니다.

이제 데이터를 가져올 수 있습니다.

Java

리소스가 EU 리전에 있다면 엔드포인트를 명시적으로 설정해야 합니다. 자세히 알아보기

import com.google.cloud.automl.v1beta1.AutoMlClient;
import com.google.cloud.automl.v1beta1.Dataset;
import com.google.cloud.automl.v1beta1.LocationName;
import com.google.cloud.automl.v1beta1.TablesDatasetMetadata;
import java.io.IOException;

class TablesCreateDataset {

  public static void main(String[] args) throws IOException {
    // 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 {
    // 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");
      TablesDatasetMetadata metadata = TablesDatasetMetadata.newBuilder().build();
      Dataset dataset =
          Dataset.newBuilder()
              .setDisplayName(displayName)
              .setTablesDatasetMetadata(metadata)
              .build();

      Dataset createdDataset = client.createDataset(projectLocation, dataset);

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

리소스가 EU 리전에 있다면 엔드포인트를 명시적으로 설정해야 합니다. 자세히 알아보기

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

/**
 * Demonstrates using the AutoML client to create a dataset
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const projectId = '[PROJECT_ID]' e.g., "my-gcloud-project";
// const computeRegion = '[REGION_NAME]' e.g., "us-central1";
// const datasetName = '[DATASET_NAME]' e.g., “myDataset”;

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

// Set dataset name and metadata.
const myDataset = {
  displayName: datasetName,
  tablesDatasetMetadata: {},
};

// Create a dataset with the dataset metadata in the region.
client
  .createDataset({parent: projectLocation, dataset: myDataset})
  .then(responses => {
    const dataset = responses[0];
    // Display the dataset information.
    console.log(`Dataset name: ${dataset.name}`);
    console.log(`Dataset Id: ${dataset.name.split('/').pop(-1)}`);
    console.log(`Dataset display name: ${dataset.displayName}`);
    console.log(`Dataset example count: ${dataset.exampleCount}`);
    console.log(
      `Tables dataset metadata: ${util.inspect(
        dataset.tablesDatasetMetadata,
        false,
        null
      )}`
    );
  })
  .catch(err => {
    console.error(err);
  });

Python

AutoML Tables용 클라이언트 라이브러리에는 AutoML Tables API로 간소화할 수 있는 추가 Python 메서드가 포함됩니다. 이러한 메서드는 데이터세트와 모델을 id가 아닌 이름으로 지칭합니다. 데이터 세트와 모델 이름은 고유해야 합니다. 자세한 내용은 클라이언트 참조를 확인하세요.

리소스가 EU 리전에 있다면 엔드포인트를 명시적으로 설정해야 합니다. 자세히 알아보기

# TODO(developer): Uncomment and set the following variables
# project_id = 'PROJECT_ID_HERE'
# compute_region = 'COMPUTE_REGION_HERE'
# dataset_display_name = 'DATASET_DISPLAY_NAME_HERE'

from google.cloud import automl_v1beta1 as automl

client = automl.TablesClient(project=project_id, region=compute_region)

# Create a dataset with the given display name
dataset = client.create_dataset(dataset_display_name)

# Display the dataset information.
print(f"Dataset name: {dataset.name}")
print("Dataset id: {}".format(dataset.name.split("/")[-1]))
print(f"Dataset display name: {dataset.display_name}")
print("Dataset metadata:")
print(f"\t{dataset.tables_dataset_metadata}")
print(f"Dataset example count: {dataset.example_count}")
print(f"Dataset create time: {dataset.create_time}")

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

이미 데이터가 포함된 데이터 세트로는 데이터를 가져올 수 없습니다. 이때는 먼저 새 데이터세트를 만들어야 합니다.

Console

  1. 필요한 경우 데이터세트 페이지의 목록에서 데이터세트를 선택하여 가져오기 탭을 엽니다.

  2. BigQuery, Cloud Storage, 로컬 컴퓨터 중에서 데이터를 가져올 소스를 선택합니다. 필요한 정보를 제공하세요.

    로컬 컴퓨터에서 CSV 파일을 로드하는 경우 Cloud Storage 버킷을 제공해야 합니다. AutoML Tables로 파일을 가져오기 전에 해당 파일이 이 버킷에 로드됩니다. 파일을 삭제하지 않으면 데이터 가져오기 후에도 계속 유지됩니다.

    버킷은 데이터 세트와 같은 위치에 있어야 합니다. 자세히 알아보기

  3. 가져오기를 클릭하여 가져오기 프로세스를 시작합니다.

    가져오기 프로세스 완료 후 학습 탭이 표시되면 모델을 학습시킬 수 있습니다.

REST

datasets.importData 메서드를 사용해 데이터를 가져옵니다.

가져오기 소스가 가져오기 소스 준비의 설명대로 요구사항을 준수하는지 확인하세요.

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

  • endpoint: 전역 위치인 경우 automl.googleapis.com, EU 리전인 경우 eu-automl.googleapis.com입니다.
  • project-id: Google Cloud 프로젝트 ID입니다.
  • location: 리소스의 위치로 전역인 경우 us-central1, 유럽 연합인 경우 eu입니다.
  • dataset-id: 데이터 세트의 ID입니다. TBL6543).
  • input-config: 데이터 소스 위치 정보입니다.
    • BigQuery: { "bigquerySource": { "inputUri": "bq://projectId.bqDatasetId.bqTableId } }"
    • Cloud Storage: { "gcsSource": { "inputUris": ["gs://bucket-name/csv-file-name.csv"] } }

HTTP 메서드 및 URL:

POST https://endpoint/v1beta1/projects/project-id/locations/location/datasets/dataset-id:importData

JSON 요청 본문:

{
  "inputConfig": input-config,
}

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: project-id" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://endpoint/v1beta1/projects/project-id/locations/location/datasets/dataset-id:importData"

PowerShell

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "project-id" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://endpoint/v1beta1/projects/project-id/locations/location/datasets/dataset-id:importData" | Select-Object -Expand Content

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

{
  "name": "projects/292381/locations/us-central1/operations/TBL6543",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.automl.v1beta1.OperationMetadata",
    "createTime": "2019-12-26T20:42:06.092180Z",
    "updateTime": "2019-12-26T20:42:06.092180Z",
    "cancellable": true,
    "worksOn": [
      "projects/292381/locations/us-central1/datasets/TBL6543"
    ],
    "importDataDetails": {},
    "state": "RUNNING"
  }
}

데이터 세트로 데이터 가져오기는 장기 실행 작업입니다. 작업 상태를 폴링하거나 작업이 반환될 때까지 기다립니다. 자세히 알아보기

가져오기 프로세스가 완료되면 모델을 학습시킬 수 있습니다.

Java

리소스가 EU 리전에 있다면 엔드포인트를 명시적으로 설정해야 합니다. 자세히 알아보기

import com.google.cloud.automl.v1beta1.AutoMlClient;
import com.google.cloud.automl.v1beta1.BigQuerySource;
import com.google.cloud.automl.v1beta1.DatasetName;
import com.google.cloud.automl.v1beta1.GcsSource;
import com.google.cloud.automl.v1beta1.InputConfig;
import com.google.protobuf.Empty;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.ExecutionException;

class TablesImportDataset {

  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 path = "gs://BUCKET_ID/path/to//data.csv or bq://project_id.dataset_id.table_id";
    importDataset(projectId, datasetId, path);
  }

  // Import a dataset via BigQuery or Google Cloud Storage
  static void importDataset(String projectId, String datasetId, String path)
      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 complete path of the dataset.
      DatasetName datasetFullId = DatasetName.of(projectId, "us-central1", datasetId);

      InputConfig.Builder inputConfigBuilder = InputConfig.newBuilder();

      // Determine which source type was used for the input path (BigQuery or GCS)
      if (path.startsWith("bq")) {
        // Get training data file to be imported from a BigQuery source.
        BigQuerySource.Builder bigQuerySource = BigQuerySource.newBuilder();
        bigQuerySource.setInputUri(path);
        inputConfigBuilder.setBigquerySource(bigQuerySource);
      } else {
        // Get multiple Google Cloud Storage URIs to import data from
        GcsSource gcsSource =
            GcsSource.newBuilder().addAllInputUris(Arrays.asList(path.split(","))).build();
        inputConfigBuilder.setGcsSource(gcsSource);
      }

      // Import data from the input URI
      System.out.println("Processing import...");

      Empty response = client.importDataAsync(datasetFullId, inputConfigBuilder.build()).get();
      System.out.format("Dataset imported. %s%n", response);
    }
  }
}

Node.js

리소스가 EU 리전에 있다면 엔드포인트를 명시적으로 설정해야 합니다. 자세히 알아보기

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

/**
 * Demonstrates using the AutoML client to import data.
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const projectId = '[PROJECT_ID]' e.g., "my-gcloud-project";
// const computeRegion = '[REGION_NAME]' e.g., "us-central1";
// const datasetId = '[DATASET_ID]' e.g., "TBL2246891593778855936";
// const path = '[GCS_PATH]' | '[BIGQUERY_PATH]'
// e.g., "gs://<bucket-name>/<csv file>" or
// "bq://<project_id>.<dataset_id>.<table_id>",
// `string or array of paths in AutoML Tables format`;

// Get the full path of the dataset.
const datasetFullId = client.datasetPath(projectId, computeRegion, datasetId);

let inputConfig = {};
if (path.startsWith('bq')) {
  // Get Bigquery URI.
  inputConfig = {
    bigquerySource: {
      inputUri: path,
    },
  };
} else {
  // Get the multiple Google Cloud Storage URIs.
  const inputUris = path.split(',');
  inputConfig = {
    gcsSource: {
      inputUris: inputUris,
    },
  };
}

// Import the dataset from the input URI.
client
  .importData({name: datasetFullId, inputConfig: inputConfig})
  .then(responses => {
    const operation = responses[0];
    console.log('Processing import...');
    return operation.promise();
  })
  .then(responses => {
    // The final result of the operation.
    const operationDetails = responses[2];

    // Get the data import details.
    console.log('Data import details:');
    console.log('\tOperation details:');
    console.log(`\t\tName: ${operationDetails.name}`);
    console.log(`\t\tDone: ${operationDetails.done}`);
  })
  .catch(err => {
    console.error(err);
  });

Python

AutoML Tables용 클라이언트 라이브러리에는 AutoML Tables API로 간소화할 수 있는 추가 Python 메서드가 포함됩니다. 이러한 메서드는 데이터세트와 모델을 id가 아닌 이름으로 지칭합니다. 데이터 세트와 모델 이름은 고유해야 합니다. 자세한 내용은 클라이언트 참조를 확인하세요.

리소스가 EU 리전에 있다면 엔드포인트를 명시적으로 설정해야 합니다. 자세히 알아보기

# TODO(developer): Uncomment and set the following variables
# project_id = 'PROJECT_ID_HERE'
# compute_region = 'COMPUTE_REGION_HERE'
# dataset_display_name = 'DATASET_DISPLAY_NAME'
# path = 'gs://path/to/file.csv' or 'bq://project_id.dataset.table_id'

from google.cloud import automl_v1beta1 as automl

client = automl.TablesClient(project=project_id, region=compute_region)

response = None
if path.startswith("bq"):
    response = client.import_data(
        dataset_display_name=dataset_display_name,
        bigquery_input_uri=path,
        dataset_name=dataset_name,
    )
else:
    # Get the multiple Google Cloud Storage URIs.
    input_uris = path.split(",")
    response = client.import_data(
        dataset_display_name=dataset_display_name,
        gcs_input_uris=input_uris,
        dataset_name=dataset_name,
    )

print("Processing import...")
# synchronous check of operation status.
print(f"Data imported. {response.result()}")

다음 단계