メインコンテンツまでスキップ

ML 多次元配列モジュール

MLMultiArray は、CoreML で最も一般的なテンソル型です。
このページでは、coreml モジュールに含まれる MLMultiArray 関連のモジュールレベル関数とオブジェクトメソッドについてまとめて説明します。対象は次のとおりです。

  • テンソルの作成
  • Lua / 画像 / OpenCV データからテンソルへの変換
  • MLMultiArray と ORT tensor の相互変換
  • 一般的な数学演算、リダクション、ソート、結合
  • 検出 / OBB / mask / keypoint / tracker などの後処理ヘルパー

Lua 層で分類、Embedding、テキストモデル、検出モデル、その他の汎用 CoreML モデルをラップする場合、このページで説明する機能が主な基盤になります。

このモジュールは 20260319 以降のバージョンで使用できます

作成と変換

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

多次元配列オブジェクト, エラー情報 = coreml.new_multi_array({
shape = 形状配列,
data_type = データ型,
})

空の CoreML 多次元配列オブジェクトを作成します。後からモデル入力や中間テンソルとして使用する場合に適しています。

  • shape は目的の形状です。たとえば {1, 3, 224, 224} を指定します
  • 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 = 形状配列,
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_widthcontent_heightborder_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_widthcontent_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 モジュールへ追加されます
  • 変換処理は native 層でコピーされ、Lua table は経由しません
  • 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 の併用に対応し、ブロードキャスト規則に従って結果を生成します
  • 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_widthdecode_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() は検出結果の配列を返し、各要素に scorepointsbox が含まれます。meta / image_meta には、画像のテンソル化で返されたメタデータをそのまま再利用できます
  • tracker() はトラッカーオブジェクトを返し、:update():reset():state():close() に対応します
  • ctc_greedy_decode() の入力は [T, C] または [N, T, C] に対応します
  • ctc_greedy_decode()blank_indexmerge_repeatedapply_softmaxreturn_probabilitiescharset に対応します
  • ctc_greedy_decode() は常に indices を返します。charset を渡した場合にのみ text が含まれ、apply_softmax または return_probabilities を有効にした場合にのみ confidence が含まれます。return_probabilities を有効にした場合にのみ、さらに probabilitiesprobability_confidence が含まれます
  • sample_logits()argmaxtemperaturetop_ktop_pmin_pseed に対応します
  • 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 へ追加されます。

型と形状の変換

  • 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() に軸を渡さない場合は、配列全体の最大値の 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())