본문으로 건너뛰기

ML 다차원 배열 모듈

MLMultiArray는 CoreML에서 가장 일반적으로 사용하는 텐서 유형입니다.
이 페이지에서는 coreml 모듈의 MLMultiArray 관련 모듈 수준 함수와 객체 메서드를 다음과 같이 설명합니다.

  • 텐서 생성
  • Lua / 이미지 / OpenCV 데이터를 텐서로 변환
  • MLMultiArray와 ORT tensor 간 변환
  • 일반적인 수학 연산, 축약, 정렬 및 결합
  • detection / OBB / mask / keypoint / tracker 등의 후처리 도구

Lua 계층에서 분류, Embedding, 텍스트 모델, 탐지 모델 또는 기타 범용 CoreML 모델을 래핑하려면 이 페이지의 기능이 주요 기반이 됩니다.

이 모듈은 20260319 이후 버전에서 사용할 수 있습니다.

생성 및 변환

coreml.new_multi_array(opts) / coreml.tensor(opts)

다차원 배열 객체, 오류 정보 = coreml.new_multi_array({
shape = shape 배열,
data_type = 데이터 유형,
})

빈 CoreML 다차원 배열 객체를 생성하며 이후 모델 입력이나 중간 텐서로 사용하기 적합합니다.

  • shape{1, 3, 224, 224}와 같은 목표 shape입니다.
  • data_type"int32", "float32", "float16", "double" 중 선택할 수 있으며 "float64""double"의 별칭으로 사용할 수 있습니다.
  • coreml.tensor(opts)는 같은 의미의 별칭입니다.

coreml.multi_array_from_table(data, opts) / coreml.tensor_from_table(data, opts)

다차원 배열 객체, 오류 정보 = coreml.multi_array_from_table(데이터 테이블, {
shape = shape 배열,
data_type = 데이터 유형,
})

Lua 테이블의 데이터를 명시적으로 MLMultiArray로 변환합니다.

  • shape은 전체 데이터 수와 일치해야 합니다.
  • data_type 규칙은 new_multi_array()와 같습니다.
  • coreml.tensor_from_table(...)은 같은 의미의 별칭입니다.

coreml.tensor_from_image(image[, opts])

다차원 배열 객체, 메타데이터 = coreml.tensor_from_image(이미지, 설정)

이미지 객체를 명시적 구성에 따라 CoreML에서 사용할 수 있는 텐서로 변환합니다.

일반적으로 사용하는 구성 필드는 다음과 같습니다.

  • width / height
  • layout: "nchw", "nhwc"만 지원
  • channel_order: "rgb", "bgr", "gray", "grey" 또는 "grayscale"
  • data_type
  • scale
  • mean
  • std
  • resize_mode: "stretch", "letterbox", "center_crop"
  • letterbox_mode: "center", "top_left"를 지원하며 "topleft""top_left"로 처리
  • pad_color
  • interpolation: "bilinear", "nearest"
  • alpha_mode: "ignore", "white", "black", "premultiply"
  • crop = {x, y, width, height}

설명:

  • 이 함수는 명시적 구성에 따른 이미지 텐서화만 담당하며 특정 모델의 전처리 규칙을 암묵적으로 연결하지 않습니다.
  • 성공하면 두 번째 반환값은 전처리 메타데이터 테이블이며, 실패하면 nil, 오류 정보를 반환합니다.
  • 일반적인 메타데이터 필드는 다음과 같습니다. src_widthsrc_heightcrop_xcrop_ycrop_widthcrop_heightdst_widthdst_heightresized_widthresized_heightscale_xscale_yratiopad_leftpad_toppad_rightpad_bottomresize_modeoffset_xoffset_yletterbox_mode

coreml.tensor_from_images(images[, opts])

배치 텐서, 배치 메타데이터 = coreml.tensor_from_images({img1, img2}, {
width = 640,
height = 640,
layout = "nchw",
})

여러 이미지를 한 번에 MLMultiArray로 변환합니다.

  • 원본 이미지 크기는 서로 달라도 됩니다.
  • 각 이미지의 처리 후 출력 shape과 data_type이 같으면 batch로 결합할 수 있습니다.
  • 두 번째 반환값은 입력 순서에 대응하는 메타데이터 배열입니다.

coreml.image_from_tensor(tensor[, opts])

이미지 객체, 오류 정보 = coreml.image_from_tensor(텐서, opts)

2D / 3D / 4D MLMultiArray를 이미지 객체로 복원하며 모델의 입출력을 디버깅하는 데 적합합니다.

일반적으로 사용하는 구성 필드는 다음과 같습니다.

  • layout
  • channel_order
  • batch_index: 1-based이며 기본값은 1번째 batch
  • scale
  • mean
  • std
  • clamp
  • value_range: "0_255" 또는 "0_1"

설명:

  • 2D / 3D / 4D 텐서만 지원합니다.
  • 채널 수는 1 또는 3만 지원합니다.

coreml.image_to_multi_array(image[, opts])

이전 인터페이스 이름이며 현재는 coreml.tensor_from_image(...)의 호환 별칭입니다. 새 코드에서는 tensor_from_image()를 사용하는 것이 좋습니다.

coreml.tensor_from_cv_mat(mat[, opts]) / coreml.multi_array_from_cv_mat(mat[, opts])

cv.matMLMultiArray로 변환합니다.

  • 먼저 require("image.cv")를 호출해야 합니다.
  • 두 이름은 같은 의미의 별칭입니다.

coreml.tensor_from_quad(mat, quad[, opts]) / coreml.multi_array_from_quad(mat, quad[, opts])

다차원 배열 객체, 오류 정보 = coreml.tensor_from_quad(mat, {
{x = 0, y = 0},
{x = 100, y = 0},
{x = 100, y = 32},
{x = 0, y = 32},
}, {
width = 100,
height = 32,
layout = "hwc",
channel_order = "rgb",
data_type = "float32",
})

cv.mat에서 사각형 영역을 따라 원근 자르기를 수행한 뒤 바로 MLMultiArray를 얻습니다.

  • 먼저 require("image.cv")를 호출해야 합니다.
  • quad에는 점 네 개를 직접 전달하거나 points 필드가 있는 테이블을 전달할 수 있습니다.
  • 일반적인 optstensor_from_image()와 거의 같고, 추가로 자주 쓰는 필드는 content_width, content_height, border_type입니다.
  • OCR 인식 전에 단일 상자를 바로잡아 텐서화하는 데 적합합니다.

coreml.tensor_from_quads(mat, quads[, opts]) / coreml.multi_array_from_quads(mat, quads[, opts])

배치 텐서, 오류 정보 = coreml.tensor_from_quads(mat, {
{
points = quad1,
content_width = 96,
content_height = 32,
},
{
points = quad2,
content_width = 80,
content_height = 32,
},
}, {
width = 96,
height = 32,
resize_mode = "top_left_letterbox",
border_type = "replicate",
})

여러 사각형을 일괄로 잘라 자동으로 batch 텐서로 결합합니다.

  • 먼저 require("image.cv")를 호출해야 합니다.
  • quads는 비어 있지 않은 배열이어야 하며 각 항목에 points를 포함할 수 있습니다.
  • 각 항목의 content_width, content_height는 전역 opts의 같은 이름 필드를 재정의합니다.
  • 반환값은 결과 rank에 따라 자동으로 stack() 또는 concat()을 사용해 batch로 결합하므로 OCR 다중 상자 일괄 처리에 적합합니다.

coreml.multi_array_from_ort_tensor(tensor[, data_type])

다차원 배열 객체, 오류 정보 = coreml.multi_array_from_ort_tensor(ORT 텐서[, "float32"])

onnxruntime.tensor를 네이티브 방식으로 복사하여 MLMultiArray로 변환합니다.

  • 이 함수는 기본적으로 존재하지 않습니다. require("onnxruntime")를 실행한 뒤에만 내장 coreml 모듈에 주입됩니다.
  • 변환 과정은 Lua table을 거치지 않고 native 계층에서 복사합니다.
  • string tensor는 MLMultiArray로 변환할 수 없습니다.

유형 확인 및 별칭

coreml.is_multi_array(value) / coreml.is_tensor(value)

다차원 배열 여부 = coreml.is_multi_array(확인할 값)

값이 coreml_multi_array_object인지 확인합니다. is_tensor()는 같은 의미의 별칭입니다.

모듈 수준 도우미 함수

기본 텐서 도우미

  • coreml.concat(arrays, axis)
  • coreml.stack(arrays, axis)
  • coreml.gather(array, dim, indices)
  • coreml.take(array, indices[, dim])
  • coreml.gather_rows(array, indices)
  • coreml.clamp(array, min, max)
  • coreml.sigmoid(array)
  • coreml.exp(array)
  • coreml.where(condition, x, y)
  • coreml.matmul(lhs, rhs)

설명:

  • take()는 기본적으로 1번째 차원을 따라 값을 가져옵니다.
  • gather_rows()take(array, indices, 1)의 편의 별칭입니다.
  • where()는 스칼라와 MLMultiArray를 함께 사용할 수 있으며 broadcasting 규칙에 따라 결과를 생성합니다.
  • matmul()은 현재 rank-1 / rank-2 입력 조합을 지원합니다.

기하 및 탐지 도우미

  • coreml.nms(boxes, scores[, opts])
  • coreml.box_points(rotated_boxes)
  • coreml.xywh_to_xyxy(boxes)
  • coreml.xyxy_to_xywh(boxes)
  • coreml.rotated_iou(lhs, rhs)
  • coreml.rotated_nms(boxes, scores[, opts])

설명:

  • nms()boxes[N, 4], scores[N] 또는 [N, C]여야 합니다.
  • rotated_nms()boxes[N, 5]여야 하며, 현재 scores에는 Lua 숫자 배열을 사용합니다.
  • 두 함수 모두 1-based 인덱스를 저장한 MLMultiArray를 반환합니다.

디코딩 및 record 도우미

  • coreml.create_decoder(schema)
  • coreml.decode_yolo(output[, opts])
  • coreml.decode_yolo_obb(output[, opts])
  • coreml.decode_matrix_candidates(output, schema[, opts])
  • coreml.decode_dense_detection(output, opts)
  • coreml.records_from_boxes(boxes, scores, class_ids[, keep_indices])
  • coreml.obb_records_from_rows(rows, scores, class_ids[, angles[, keep_indices[, opts]]])
  • coreml.points_to_records(points[, opts])

설명:

  • create_decoder()는 decoder 객체를 반환하며 :decode(), :task(), :schema()를 지원합니다.
  • decode_dense_detection(){ boxes, scores, labels }를 반환하며 입력이 batch이면 batch 결과 배열을 반환합니다.
  • decode_dense_detection()opts.strides는 필수이며 비어 있지 않은 양의 정수 배열이어야 합니다.
  • decode_dense_detection()에는 decode_width, decode_height도 필요하며 현재 box_encoding = "grid_center_log_wh"만 지원합니다.
  • records_from_boxes(), obb_records_from_rows(), points_to_records()는 텐서 결과를 Lua에서 사용하기 편한 record table로 정리합니다.

마스크, 키포인트 및 추적 도우미

  • coreml.threshold_masks(masks, threshold)
  • coreml.crop_masks_by_boxes(masks, boxes)
  • coreml.resize_masks(masks, width, height[, opts])
  • coreml.mask_iou(lhs_mask, rhs_mask)
  • coreml.mask_to_polygon(mask[, opts])
  • coreml.proto_masks(proto, coeffs, boxes, image_width, image_height[, opts])
  • coreml.project_masks(proto, coeffs, boxes, image_width, image_height[, opts])
  • coreml.db_postprocess(score_map[, opts])
  • coreml.tracker([opts])
  • coreml.reshape_keypoints(points[, keypoint_count[, keypoint_dim|opts]])
  • coreml.scale_boxes(boxes, transform)
  • coreml.clip_boxes(boxes, clip_width, clip_height)
  • coreml.scale_points(points, transform[, opts])
  • coreml.scale_keypoints(points, transform[, opts])
  • coreml.clip_keypoints(points, clip_width, clip_height[, opts])
  • coreml.ctc_greedy_decode(logits[, opts])
  • coreml.sample_logits(logits[, opts])

설명:

  • project_masks()proto_masks()의 별칭입니다.
  • mask_iou()는 두 mask의 IoU를 직접 계산합니다.
  • mask_iou()는 세 번째 매개변수 opts도 지원합니다. compare_size = true를 전달하거나 정렬 후 비교 크기로 width / height를 명시할 수 있습니다.
  • db_postprocess()는 DB / DBNet 계열 텍스트 탐지 후처리에 적합하며 [H, W], [C, H, W] 또는 [N, C, H, W] 입력을 지원합니다.
  • db_postprocess()는 탐지 배열을 반환하고 각 항목에 score, points, box가 포함됩니다. meta / image_meta에는 이미지 텐서화가 반환한 메타데이터를 그대로 재사용할 수 있습니다.
  • tracker()는 추적기 객체를 반환하며 :update(), :reset(), :state(), :close()를 지원합니다.
  • ctc_greedy_decode()[T, C] 또는 [N, T, C] 입력을 지원합니다.
  • ctc_greedy_decode()blank_index, merge_repeated, apply_softmax, return_probabilities, charset을 지원합니다.
  • ctc_greedy_decode()는 항상 indices를 반환합니다. charset을 전달해야 text가 포함되고, apply_softmax 또는 return_probabilities를 활성화해야 confidence가 포함되며, return_probabilities를 활성화해야 probabilitiesprobability_confidence도 포함됩니다.
  • sample_logits()argmax, temperature, top_k, top_p, min_p, seed를 지원합니다.
  • sample_logits()는 1D logits에 대해 단일 1-based 인덱스를 반환하고, batched logits에 대해서는 인덱스 MLMultiArray를 반환합니다.

객체 기본 메서드

기본 조회

  • array:shape()
  • array:data_type()
  • array:count()
  • array:strides()
  • array:to_table()
  • array:to_cv_mat([opts])

설명:

  • data_type()"int32", "float32", "float16" 또는 "double"을 반환합니다.
  • to_cv_mat()을 사용하려면 먼저 require("image.cv")를 호출해야 합니다.

ORT 연동

  • array:to_ort_tensor([data_type])

이 메서드는 기본적으로 존재하지 않습니다. require("onnxruntime")를 실행한 뒤에만 coreml_multi_array_object에 주입됩니다.

유형 및 shape 변환

  • array:astype(data_type)
  • array:clone()
  • array:reshape(shape)
  • array:transpose(axes)
  • array:slice(dim, start, stop[, step])
  • array:select(dim, index)
  • array:squeeze([dim])
  • array:unsqueeze(dim)
  • array:flatten([start_dim[, end_dim]])

설명:

  • reshape(), transpose(), squeeze(), unsqueeze(), flatten()은 기본적으로 view를 반환하며 기반 데이터를 복사하지 않습니다.
  • reshape() / flatten()은 비연속 레이아웃에서 오류를 냅니다. 이때 먼저 clone()을 호출할 수 있습니다.
  • slice()select()는 view가 아닌 새로운 연속 텐서를 반환합니다.
  • slice() / select() / gather() / take()의 인덱스 의미는 ONNX 페이지와 동일하게 1-based입니다.

수치 및 인덱스 메서드

  • array:gather(dim, indices)
  • array:take(indices[, dim])
  • array:l2_norm()
  • array:dot(other)
  • array:max([axis])
  • array:min([axis])
  • array:add(other)
  • array:sub(other)
  • array:mul(other)
  • array:div(other)
  • array:clamp(min, max)
  • array:sigmoid()
  • array:exp()
  • array:matmul(other)
  • array:scale(number)

설명:

  • add/sub/mul/div는 스칼라와 제한적인 broadcasting을 지원합니다.
  • sigmoid(), exp(), matmul()의 결과는 부동소수점 출력으로 승격됩니다.

축약, 정렬 및 선택

  • array:sum([axis])
  • array:mean([axis])
  • array:softmax([axis])
  • array:normalize([axis])
  • array:argmax([axis])
  • array:topk(k[, axis])
  • array:sort([axis[, descending]])

설명:

  • argmax()에 axis를 전달하지 않으면 전체 배열 최댓값의 1-based 선형 인덱스를 반환합니다.
  • argmax(axis)는 인덱스를 저장한 MLMultiArray를 반환합니다.
  • topk(){ values = 텐서, indices = 텐서 }를 반환합니다.
  • sort()는 정렬된 새 MLMultiArray를 반환하며 인덱스 테이블을 추가로 반환하지 않습니다.

기하 및 후처리 객체 메서드

  • array:clip_boxes(clip_width, clip_height)
  • array:xywh_to_xyxy()
  • array:xyxy_to_xywh()
  • array:reshape_keypoints([keypoint_count[, keypoint_dim|opts]])
  • array:scale_points(transform[, opts])
  • array:clip_keypoints(clip_width, clip_height[, opts])

이 메서드들은 같은 이름의 모듈 수준 함수와 동일한 기반 구현을 공유하며, 현재 배열을 첫 번째 매개변수로 전달한다는 점만 다릅니다.

사용 권장 사항

  • 새 범용 CoreML 인터페이스에서 MLMultiArray는 기본 일급 데이터 유형이므로 너무 일찍 Lua 테이블로 변환하지 않는 것이 좋습니다.
  • 대부분의 일괄 연산은 가능한 한 텐서 객체에서 완료하고, 디버깅, 소량 데이터 출력 또는 기존 코드 호환이 필요할 때만 to_table()을 호출하십시오.
  • 이미지 전처리 규칙은 tensor_from_image()의 매개변수로 명시하여 특정 모델의 전처리를 범용 흐름에 하드 코딩하지 않도록 하십시오.
  • 독립된 복사본이 필요하거나 비연속 레이아웃을 연속 텐서로 정리하려면 clone()을 명시적으로 호출하십시오.

예제

local arr = assert(coreml.tensor({
shape = {2, 3},
data_type = "float32",
}))

local filled = assert(coreml.tensor_from_table({
{1, 2, 3},
{4, 5, 6},
}, {
shape = {2, 3},
data_type = "float32",
}))

local merged = assert(coreml.concat({filled, filled}, 1))
print(coreml.is_tensor(merged))
print(merged:shape())