Transformers documentation
Deformable DETR
このモデルは2020年10月8日にHF papersで公開され、2022年9月14日にHugging Face Transformersに貢献されました。
Deformable DETR
Deformable DETRは、deformable attentionモジュールを用いることで、元のDETRを改善しています。このメカニズムは、参照点の周囲にある少数の主要なサンプリング点に選択的に注意を向けます。これにより、学習速度と精度が向上します。
Deformable DETR architecture. Taken from the original paper. 利用可能な Deformable DETR のチェックポイントはすべて、SenseTime 組織の下で確認できます。
このモデルは nielsr によって提供されました。
右側のサイドバーにある Deformable DETR モデルをクリックすると、Deformable DETR をさまざまな物体検出やセグメンテーションタスクに適用する例をさらに確認できます。
以下の例では、PipelineとAutoModelクラスを使用してオブジェクト検出を実行する方法を示しています。
from transformers import pipeline
pipeline = pipeline(
"object-detection",
model="SenseTime/deformable-detr",
device_map=0
)
pipeline("http://images.cocodataset.org/val2017/000000039769.jpg")import requests
import torch
from PIL import Image
from transformers import AutoImageProcessor, AutoModelForObjectDetection
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
image = Image.open(requests.get(url, stream=True).raw)
image_processor = AutoImageProcessor.from_pretrained("SenseTime/deformable-detr")
model = AutoModelForObjectDetection.from_pretrained("SenseTime/deformable-detr", device_map="auto")
# prepare image for the model
inputs = image_processor(images=image, return_tensors="pt").to(model.device)
with torch.no_grad():
outputs = model(**inputs)
results = image_processor.post_process_object_detection(outputs, target_sizes=torch.tensor([image.size[::-1]]), threshold=0.3)
for result in results:
for score, label_id, box in zip(result["scores"], result["labels"], result["boxes"]):
score, label = score.item(), label_id.item()
box = [round(i, 2) for i in box.tolist()]
print(f"{model.config.id2label[label]}: {score:.2f} {box}")リソース
- カスタムデータセット上でDeformableDetrForObjectDetectionの推論とファインチューニングを行うには、このノートブックのセットを参照してください。
DeformableDetrImageProcessor
クラス transformers.DeformableDetrImageProcessor
< source >( **kwargs: *<class 'transformers.models.deformable_detr.image_processing_deformable_detr.DeformableDetrImageProcessorKwargs'> )
パラメータ
- do_convert_rgb (
bool、kwargs、任意) — 画像を RGB に変換するかどうかを指定します。 - do_resize (
bool、kwargs、任意、デフォルトはTrue) — 画像をリサイズするかどうか。 - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs、デフォルトは{'shortest_edge' -- 800, 'longest_edge': 1333}): モデルへの最大入力サイズを指定します。 - default_to_square (
bool、kwargs、任意、デフォルトはFalse) — size が整数の場合、リサイズ時に正方形の画像をデフォルトとするかどうか。 - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) —center_cropを適用した後の出力画像のサイズ。 - resample (
Annotated[Union[int, PILImageResampling, NoneType], None], kwargs, デフォルトは2) — 画像のリサイズ時に使用するリサンプリングフィルタです。PILImageResamplingの列挙型のいずれかを使用できます。do_resizeがTrueに設定されている場合のみ、効果が現れます。 - do_rescale (
bool、kwargs、任意、デフォルトはTrue) — 画像をリスケールするかどうかを指定します。 - rescale_factor (
float、kwargs、任意、デフォルト値は0.00392156862745098) —do_rescaleがTrueに設定されている場合、画像をリスケールするための係数です。 - do_normalize (
bool、kwargs、optional、デフォルトはTrue) — 画像を正規化するかどうかを指定します。 - image_mean (
Union[float, list[float], tuple[float, ...]]、kwargs、optional、デフォルト値は[0.485, 0.456, 0.406]) — 正規化に使用する画像の平均値。do_normalizeがTrueに設定されている場合のみ有効です。 - image_std (
Union[float, list[float], tuple[float, ...]]、kwargs、optional、デフォルト値は[0.229, 0.224, 0.225]) — 正規化に使用する画像の標準偏差。do_normalizeがTrueに設定されている場合のみ有効です。 - do_pad (
bool、kwargs、optional、デフォルトはTrue) — 画像をパディングするかどうか。パディングは、バッチ内の最大サイズに合わせるか、画像ごとに固定の正方形サイズに合わせるかのいずれかで行われます。具体的なパディング戦略はモデルによって異なります。 - pad_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 画像をパディングする{"height": int, "width" int}のサイズです。前処理に提供されるすべての画像サイズより大きくなければなりません。pad_sizeが指定されない場合、バッチ内の最大の幅と高さにパディングされます。do_pad=True.の場合のみ適用されます。 - do_center_crop (
bool, kwargs, optional) — 画像を中央クロップするかどうかを指定します。 - data_format (
Union[str, ~image_utils.ChannelDimension]、kwargs、任意) — サポートされているのはChannelDimension.FIRSTのみです。slow processors との互換性のために追加されました。 - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 省略可) — 入力画像のチャネル次元の形式です。設定されていない場合、入力画像からチャネル次元の形式が推測されます。次のいずれかになります:"channels_first"またはChannelDimension.FIRST: (num_channels, height, width) 形式の画像。"channels_last"またはChannelDimension.LAST: (高さ, 幅, チャネル数) 形式の画像。"none"またはChannelDimension.NONE: (height, width) 形式の画像。
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — 動画を処理するデバイスです。未設定の場合、入力動画からデバイスが推論されます。 - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) —'pt'に設定されている場合はスタックされたテンソルを返し、それ以外の場合はテンソルのリストを返します。 - disable_grouping (
bool、kwargs、任意) — サイズごとに画像をグループ化してバッチ処理するのではなく、個別に処理するためにグループ化を無効にするかどうか。None の場合、画像が CPU にある場合は True、それ以外の場合は False に設定されます。この選択は、https://github.com/huggingface/transformers/pull/38157 に詳しく記載されている経験則に基づいています。 - image_seq_length (
int、kwargs、任意) — 入力内の各画像に使用される画像トークンの数です。 後方互換性のために追加されましたが、将来のモデルではプロセッサの属性として設定されるべきです。 - format (
str, kwargs, optional, デフォルトはAnnotationFormat.COCO_DETECTION) — アノテーションのデータ形式。“coco_detection” または “coco_panoptic” のいずれかです。 - do_convert_annotations (
bool、kwargs、optional、デフォルトはTrue) — DEFORMABLE_DETR モデルが期待する形式にアノテーションを変換するかどうかを制御します。バウンディングボックスを(center_x, center_y, width, height)の形式に変換し、値の範囲を[0, 1]にします。preprocessメソッドのdo_convert_annotationsパラメータによって上書きできます。
DeformableDetrImageProcessor の画像プロセッサを構築します。
preprocess
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]annotations: dict[str, int | str | list[dict]] | list[dict[str, int | str | list[dict]]] | None = Nonereturn_segmentation_masks: bool | None = Nonemasks_path: str | pathlib.Path | None = None**kwargs: *<class 'transformers.models.deformable_detr.image_processing_deformable_detr.DeformableDetrImageProcessorKwargs'> ) → ~image_processing_base.BatchFeature
パラメータ
- images (
Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]) — 前処理対象の画像です。ピクセル値が 0 から 255 の範囲にある単一の画像またはバッチを想定しています。ピクセル値が 0 から 1 の範囲にある画像を渡す場合は、do_rescale=Falseを設定してください。 - annotations (
AnnotationTypeまたはlist[AnnotationType]、省略可) — 画像に適用されるパディングに従って変換するアノテーション。 - return_segmentation_masks (
bool、省略可、デフォルトはself.return_segmentation_masks) — セグメンテーションマスクを返すかどうかを指定します。 - masks_path (
strまたはpathlib.Path、省略可) — セグメンテーションマスクを含むディレクトリへのパス。 - do_convert_rgb (
bool、kwargs、任意) — 画像を RGB に変換するかどうかを指定します。 - do_resize (
bool、kwargs、optional) — 画像をリサイズするかどうか。 - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — モデルへの最大入力次元を記述します。 - default_to_square (
bool、kwargs、任意) — サイズが整数の場合、リサイズ時に正方形の画像をデフォルトとするかどうか。 - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) —center_cropを適用した後の出力画像のサイズ。 - resample (
Annotated[Union[int, PILImageResampling, NoneType], None], kwargs) — 画像のリサイズ時に使用するリサンプリングフィルタ。PILImageResamplingの列挙型のいずれかを使用できます。do_resizeがTrueに設定されている場合のみ有効です。 - do_rescale (
bool、kwargs、optional) — 画像をリスケールするかどうかを指定します。 - rescale_factor (
float、kwargs、任意) —do_rescaleがTrueに設定されている場合、画像をリスケールするための係数。 - do_normalize (
bool, kwargs, optional) — 画像を正規化するかどうかを指定します。 - image_mean (
Union[float, list[float], tuple[float, ...]]、kwargs、optional) — 正規化に使用する画像の平均値。do_normalizeがTrueに設定されている場合のみ有効です。 - image_std (
Union[float, list[float], tuple[float, ...]], kwargs, optional) — 正規化に使用する画像の標準偏差。do_normalizeがTrueに設定されている場合のみ有効です。 - do_pad (
bool, kwargs, optional) — 画像をパディングするかどうかを指定します。パディングは、バッチ内の最大サイズに合わせるか、画像ごとに固定の正方形サイズに合わせるかのいずれかで行われます。具体的なパディング戦略はモデルによって異なります。 - pad_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 画像をパディングする{"height": int, "width" int}のサイズです。前処理に提供されるすべての画像サイズより大きくなければなりません。pad_sizeが指定されない場合、バッチ内の最大の幅と高さにパディングされます。do_pad=True.の場合のみ適用されます。 - do_center_crop (
bool, kwargs, optional) — 画像を中央クロップするかどうかを指定します。 - data_format (
Union[str, ~image_utils.ChannelDimension]、kwargs、任意) — サポートされているのはChannelDimension.FIRSTのみです。slow processors との互換性のために追加されました。 - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 省略可) — 入力画像のチャネル次元の形式です。設定されていない場合、入力画像からチャネル次元の形式が推測されます。次のいずれかになります:"channels_first"またはChannelDimension.FIRST: (num_channels, height, width) 形式の画像。"channels_last"またはChannelDimension.LAST: (高さ, 幅, チャネル数) 形式の画像。"none"またはChannelDimension.NONE: (height, width) 形式の画像。
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — 動画を処理するデバイスです。未設定の場合、入力動画からデバイスが推論されます。 - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) —'pt'に設定されている場合はスタックされたテンソルを返し、それ以外の場合はテンソルのリストを返します。 - disable_grouping (
bool、kwargs、任意) — サイズごとに画像をグループ化してバッチ処理するのではなく、個別に処理するためにグループ化を無効にするかどうか。None の場合、画像が CPU にある場合は True、それ以外の場合は False に設定されます。この選択は、https://github.com/huggingface/transformers/pull/38157 に詳しく記載されている経験則に基づいています。 - image_seq_length (
int、kwargs、任意) — 入力内の各画像に使用される画像トークンの数です。 後方互換性のために追加されましたが、将来のモデルではプロセッサの属性として設定されるべきです。 - format (
str, kwargs, optional, デフォルトはAnnotationFormat.COCO_DETECTION) — アノテーションのデータ形式。“coco_detection” または “coco_panoptic” のいずれかです。 - do_convert_annotations (
bool、kwargs、optional、デフォルトはTrue) — DEFORMABLE_DETR モデルが期待する形式にアノテーションを変換するかどうかを制御します。バウンディングボックスを(center_x, center_y, width, height)の形式に変換し、値の範囲を[0, 1]にします。preprocessメソッドのdo_convert_annotationsパラメータによって上書きできます。
戻り値
~image_processing_base.BatchFeature
- data (
dict) — call メソッド(‘pixel_values’ など)によって返される、リスト/配列/テンソルの辞書。 - tensor_type (
Union[None, str, TensorType]、省略可) — 初期化時に PyTorch/Numpy の Tensor 内の整数リストを変換するために、ここで tensor_type を指定できます。
post_process_object_detection
< source >( outputsthreshold: float = 0.5target_sizes: transformers.utils.generic.TensorType | list[tuple] = Nonetop_k: int = 100 ) → list[Dict]
パラメータ
- outputs (
DetrObjectDetectionOutput) — モデルの生出力です。 - threshold (
float, 任意) — オブジェクト検出の予測を保持するためのスコアしきい値。 - target_sizes (
torch.Tensorまたはlist[tuple[int, int]]、省略可) — バッチ内の各画像のターゲットサイズ(高さ、幅)を含む、形状が(batch_size, 2)の Tensor またはタプルのリスト(tuple[int, int])。None の場合、予測結果はリサイズされません。 - top_k (
int、任意、デフォルトは 100) — 閾値によるフィルタリングの前に、上位 k 個のバウンディングボックスのみを保持します。
戻り値
list[Dict]
モデルが予測したバッチ内の各画像のスコア、ラベル、ボックスを含む辞書のリスト
DeformableDetrForObjectDetectionの生出力を、(top_left_x, top_left_y, bottom_right_x, bottom_right_y)形式の最終的なバウンディングボックスに変換します。PyTorchのみサポートしています。
DeformableDetrImageProcessorPil
クラス transformers.DeformableDetrImageProcessorPil
< source >( **kwargs: *<class 'transformers.models.deformable_detr.image_processing_pil_deformable_detr.DeformableDetrImageProcessorKwargs'> )
パラメータ
- do_convert_rgb (
bool、kwargs、任意) — 画像を RGB に変換するかどうかを指定します。 - do_resize (
bool、kwargs、任意、デフォルトはTrue) — 画像をリサイズするかどうか。 - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs、デフォルトは{'shortest_edge' -- 800, 'longest_edge': 1333}): モデルへの最大入力サイズを指定します。 - default_to_square (
bool、kwargs、任意、デフォルトはFalse) — size が整数の場合、リサイズ時に正方形の画像をデフォルトとするかどうか。 - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) —center_cropを適用した後の出力画像のサイズ。 - resample (
Annotated[Union[int, PILImageResampling, NoneType], None], kwargs, デフォルトは2) — 画像のリサイズ時に使用するリサンプリングフィルタです。PILImageResamplingの列挙型のいずれかを使用できます。do_resizeがTrueに設定されている場合のみ、効果が現れます。 - do_rescale (
bool、kwargs、任意、デフォルトはTrue) — 画像をリスケールするかどうかを指定します。 - rescale_factor (
float、kwargs、任意、デフォルト値は0.00392156862745098) —do_rescaleがTrueに設定されている場合、画像をリスケールするための係数です。 - do_normalize (
bool、kwargs、optional、デフォルトはTrue) — 画像を正規化するかどうかを指定します。 - image_mean (
Union[float, list[float], tuple[float, ...]]、kwargs、optional、デフォルト値は[0.485, 0.456, 0.406]) — 正規化に使用する画像の平均値。do_normalizeがTrueに設定されている場合のみ有効です。 - image_std (
Union[float, list[float], tuple[float, ...]]、kwargs、optional、デフォルト値は[0.229, 0.224, 0.225]) — 正規化に使用する画像の標準偏差。do_normalizeがTrueに設定されている場合のみ有効です。 - do_pad (
bool、kwargs、optional、デフォルトはTrue) — 画像をパディングするかどうか。パディングは、バッチ内の最大サイズに合わせるか、画像ごとに固定の正方形サイズに合わせるかのいずれかで行われます。具体的なパディング戦略はモデルによって異なります。 - pad_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 画像をパディングする{"height": int, "width" int}のサイズです。前処理に提供されるすべての画像サイズより大きくなければなりません。pad_sizeが指定されない場合、バッチ内の最大の幅と高さにパディングされます。do_pad=True.の場合のみ適用されます。 - do_center_crop (
bool, kwargs, optional) — 画像を中央クロップするかどうかを指定します。 - data_format (
Union[str, ~image_utils.ChannelDimension]、kwargs、任意) — サポートされているのはChannelDimension.FIRSTのみです。slow processors との互換性のために追加されました。 - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 省略可) — 入力画像のチャネル次元の形式です。設定されていない場合、入力画像からチャネル次元の形式が推測されます。次のいずれかになります:"channels_first"またはChannelDimension.FIRST: (num_channels, height, width) 形式の画像。"channels_last"またはChannelDimension.LAST: (高さ, 幅, チャネル数) 形式の画像。"none"またはChannelDimension.NONE: (height, width) 形式の画像。
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — 動画を処理するデバイスです。未設定の場合、入力動画からデバイスが推論されます。 - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) —'pt'に設定されている場合はスタックされたテンソルを返し、それ以外の場合はテンソルのリストを返します。 - disable_grouping (
bool、kwargs、任意) — サイズごとに画像をグループ化してバッチ処理するのではなく、個別に処理するためにグループ化を無効にするかどうか。None の場合、画像が CPU にある場合は True、それ以外の場合は False に設定されます。この選択は、https://github.com/huggingface/transformers/pull/38157 に詳しく記載されている経験則に基づいています。 - image_seq_length (
int、kwargs、任意) — 入力内の各画像に使用される画像トークンの数です。 後方互換性のために追加されましたが、将来のモデルではプロセッサの属性として設定されるべきです。 - format (
str, kwargs, optional, デフォルトはAnnotationFormat.COCO_DETECTION) — アノテーションのデータ形式。“coco_detection” または “coco_panoptic” のいずれかです。 - do_convert_annotations (
bool、kwargs、optional、デフォルトはTrue) — DEFORMABLE_DETR モデルが期待する形式にアノテーションを変換するかどうかを制御します。バウンディングボックスを(center_x, center_y, width, height)の形式に変換し、値の範囲を[0, 1]にします。preprocessメソッドのdo_convert_annotationsパラメータによって上書きできます。
DeformableDetrImageProcessor の画像プロセッサを構築します。
preprocess
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]annotations: dict[str, int | str | list[dict]] | list[dict[str, int | str | list[dict]]] | None = Nonereturn_segmentation_masks: bool | None = Nonemasks_path: str | pathlib.Path | None = None**kwargs: *<class 'transformers.models.deformable_detr.image_processing_pil_deformable_detr.DeformableDetrImageProcessorKwargs'> ) → ~image_processing_base.BatchFeature
パラメータ
- images (
Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]) — 前処理対象の画像です。ピクセル値が 0 から 255 の範囲にある単一の画像またはバッチを想定しています。ピクセル値が 0 から 1 の範囲にある画像を渡す場合は、do_rescale=Falseを設定してください。 - annotations (
AnnotationTypeまたはlist[AnnotationType]、省略可) — 画像に適用されるパディングに従って変換するアノテーション。 - return_segmentation_masks (
bool、省略可、デフォルトはself.return_segmentation_masks) — セグメンテーションマスクを返すかどうかを指定します。 - masks_path (
strまたはpathlib.Path、省略可) — セグメンテーションマスクを含むディレクトリへのパス。 - do_convert_rgb (
bool、kwargs、任意) — 画像を RGB に変換するかどうかを指定します。 - do_resize (
bool、kwargs、optional) — 画像をリサイズするかどうか。 - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — モデルへの最大入力次元を記述します。 - default_to_square (
bool、kwargs、任意) — サイズが整数の場合、リサイズ時に正方形の画像をデフォルトとするかどうか。 - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) —center_cropを適用した後の出力画像のサイズ。 - resample (
Annotated[Union[int, PILImageResampling, NoneType], None], kwargs) — 画像のリサイズ時に使用するリサンプリングフィルタ。PILImageResamplingの列挙型のいずれかを使用できます。do_resizeがTrueに設定されている場合のみ有効です。 - do_rescale (
bool、kwargs、optional) — 画像をリスケールするかどうかを指定します。 - rescale_factor (
float、kwargs、任意) —do_rescaleがTrueに設定されている場合、画像をリスケールするための係数。 - do_normalize (
bool, kwargs, optional) — 画像を正規化するかどうかを指定します。 - image_mean (
Union[float, list[float], tuple[float, ...]]、kwargs、optional) — 正規化に使用する画像の平均値。do_normalizeがTrueに設定されている場合のみ有効です。 - image_std (
Union[float, list[float], tuple[float, ...]], kwargs, optional) — 正規化に使用する画像の標準偏差。do_normalizeがTrueに設定されている場合のみ有効です。 - do_pad (
bool, kwargs, optional) — 画像をパディングするかどうかを指定します。パディングは、バッチ内の最大サイズに合わせるか、画像ごとに固定の正方形サイズに合わせるかのいずれかで行われます。具体的なパディング戦略はモデルによって異なります。 - pad_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 画像をパディングする{"height": int, "width" int}のサイズです。前処理に提供されるすべての画像サイズより大きくなければなりません。pad_sizeが指定されない場合、バッチ内の最大の幅と高さにパディングされます。do_pad=True.の場合のみ適用されます。 - do_center_crop (
bool, kwargs, optional) — 画像を中央クロップするかどうかを指定します。 - data_format (
Union[str, ~image_utils.ChannelDimension]、kwargs、任意) — サポートされているのはChannelDimension.FIRSTのみです。slow processors との互換性のために追加されました。 - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 省略可) — 入力画像のチャネル次元の形式です。設定されていない場合、入力画像からチャネル次元の形式が推測されます。次のいずれかになります:"channels_first"またはChannelDimension.FIRST: (num_channels, height, width) 形式の画像。"channels_last"またはChannelDimension.LAST: (高さ, 幅, チャネル数) 形式の画像。"none"またはChannelDimension.NONE: (height, width) 形式の画像。
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — 動画を処理するデバイスです。未設定の場合、入力動画からデバイスが推論されます。 - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) —'pt'に設定されている場合はスタックされたテンソルを返し、それ以外の場合はテンソルのリストを返します。 - disable_grouping (
bool、kwargs、任意) — サイズごとに画像をグループ化してバッチ処理するのではなく、個別に処理するためにグループ化を無効にするかどうか。None の場合、画像が CPU にある場合は True、それ以外の場合は False に設定されます。この選択は、https://github.com/huggingface/transformers/pull/38157 に詳しく記載されている経験則に基づいています。 - image_seq_length (
int、kwargs、任意) — 入力内の各画像に使用される画像トークンの数です。 後方互換性のために追加されましたが、将来のモデルではプロセッサの属性として設定されるべきです。 - format (
str, kwargs, optional, デフォルトはAnnotationFormat.COCO_DETECTION) — アノテーションのデータ形式。“coco_detection” または “coco_panoptic” のいずれかです。 - do_convert_annotations (
bool、kwargs、optional、デフォルトはTrue) — DEFORMABLE_DETR モデルが期待する形式にアノテーションを変換するかどうかを制御します。バウンディングボックスを(center_x, center_y, width, height)の形式に変換し、値の範囲を[0, 1]にします。preprocessメソッドのdo_convert_annotationsパラメータによって上書きできます。
戻り値
~image_processing_base.BatchFeature
- data (
dict) — call メソッド(‘pixel_values’ など)によって返される、リスト/配列/テンソルの辞書。 - tensor_type (
Union[None, str, TensorType]、省略可) — 初期化時に PyTorch/Numpy の Tensor 内の整数リストを変換するために、ここで tensor_type を指定できます。
post_process_object_detection
< source >( outputsthreshold: float = 0.5target_sizes: transformers.utils.generic.TensorType | list[tuple] = Nonetop_k: int = 100 ) → list[Dict]
パラメータ
- outputs (
DetrObjectDetectionOutput) — モデルの生出力です。 - threshold (
float, 任意) — オブジェクト検出の予測を保持するためのスコアしきい値。 - target_sizes (
torch.Tensorまたはlist[tuple[int, int]]、省略可) — バッチ内の各画像のターゲットサイズ(高さ、幅)を含む、形状が(batch_size, 2)の Tensor またはタプルのリスト(tuple[int, int])。None の場合、予測結果はリサイズされません。 - top_k (
int、任意、デフォルトは 100) — 閾値によるフィルタリングの前に、上位 k 個のバウンディングボックスのみを保持します。
戻り値
list[Dict]
モデルが予測したバッチ内の各画像のスコア、ラベル、ボックスを含む辞書のリスト
DeformableDetrForObjectDetectionの生出力を、(top_left_x, top_left_y, bottom_right_x, bottom_right_y)形式の最終的なバウンディングボックスに変換します。PyTorchのみサポートしています。
DeformableDetrConfig
クラス transformers.DeformableDetrConfig
< source >( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0id2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Noneis_encoder_decoder: bool = Truebackbone_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonenum_channels: int = 3num_queries: int = 300max_position_embeddings: int = 1024encoder_layers: int = 6encoder_ffn_dim: int = 1024encoder_attention_heads: int = 8decoder_layers: int = 6decoder_ffn_dim: int = 1024decoder_attention_heads: int = 8encoder_layerdrop: float | int = 0.0activation_function: str = 'relu'd_model: int = 256dropout: float | int = 0.1attention_dropout: float | int = 0.0activation_dropout: float | int = 0.0init_std: float = 0.02init_xavier_std: float = 1.0return_intermediate: bool = Trueauxiliary_loss: bool = Falseposition_embedding_type: str = 'sine'dilation: bool = Falsenum_feature_levels: int = 4encoder_n_points: int = 4decoder_n_points: int = 4two_stage: bool = Falsetwo_stage_num_proposals: int = 300with_box_refine: bool = Falseclass_cost: int = 1bbox_cost: int = 5giou_cost: int = 2mask_loss_coefficient: int = 1dice_loss_coefficient: int = 1bbox_loss_coefficient: int = 5giou_loss_coefficient: int = 2eos_coefficient: float = 0.1focal_alpha: float = 0.25disable_custom_kernels: bool = Falsetie_word_embeddings: bool = True )
パラメータ
- is_encoder_decoder (
bool、任意、デフォルトはTrue) — モデルがエンコーダー/デコーダーとして使用されるかどうかを示します。 - backbone_config (
Union[dict, ~configuration_utils.PreTrainedConfig], 任意) — バックボーンモデルの設定です。 - num_channels (
int、任意、デフォルトは3) — 入力チャネル数。 - num_queries (
int、任意、デフォルト値は 300) — オブジェクトクエリ数、すなわち検出スロットの数です。これは、DeformableDetrModel が 1 枚の画像内で検出できるオブジェクトの最大数を表します。two_stageがTrueに設定されている場合は、代わりにtwo_stage_num_proposalsが使用されます。 - max_position_embeddings (
int、任意、デフォルトは1024) — このモデルが使用される可能性のある最大シーケンス長です。 - encoder_layers (
int、任意、デフォルトは6) — Transformer エンコーダーの隠れ層の数です。設定されていない場合は、num_layersと同じ値が使用されます。 - encoder_ffn_dim (
int、任意、デフォルトは1024) — エンコーダー内の「中間」層(feed-forward 層と呼ばれることが多い)の次元数。 - encoder_attention_heads (
int、任意、デフォルトは8) — Transformer エンコーダーの各アテンション層におけるアテンションヘッドの数。 - decoder_layers (
int、任意、デフォルトは6) — Transformer デコーダーの隠れ層の数です。設定されていない場合、num_layersと同じ値が使用されます。 - decoder_ffn_dim (
int、任意、デフォルトは1024) — デコーダー内の「中間」層(feed-forward 層と呼ばれることが多い)の次元数。 - decoder_attention_heads (
int、任意、デフォルトは8) — Transformerデコーダーの各アテンション層におけるアテンションヘッドの数。 - encoder_layerdrop (
Union[float, int]、任意、デフォルトは0.0) — エンコーダーの LayerDrop 確率です。詳細は [LayerDrop の論文](https://huggingface.co/papers/1909.11556 を参照)をご覧ください。 - activation_function (
str、任意、デフォルトはrelu) — デコーダーで使用する非線形活性化関数(関数または文字列)。例えば、"gelu"、"relu"、"silu"など。 - d_model (
int、省略可、デフォルトは256) — エンコーダ層とプーラ層のサイズ。 - dropout (
Union[float, int]、任意、デフォルト値は0.1) — すべての dropout レイヤーの比率です。 - attention_dropout (
Union[float, int]、任意、デフォルトは0.0) — アテンション確率のドロップアウト率です。 - activation_dropout (
Union[float, int]、任意、デフォルトは0.0) — 全結合層内の活性化に対する dropout 率です。 - init_std (
float、任意、デフォルトは0.02) — すべての重み行列を初期化するための truncated_normal_initializer の標準偏差です。 - init_xavier_std (
float、任意、デフォルトは1.0) — クロスアテンションの重みの Xavier 初期化に使用されるスケーリング係数です。 - return_intermediate (
bool、省略可、デフォルトは True)— 中間状態を返すかどうか - auxiliary_loss (
bool、任意、デフォルトはFalse) — 補助デコーディング損失(各デコーダ層での損失)を使用するかどうかを指定します。 - position_embedding_type (
str, 任意、デフォルトは"sine") — 画像特徴の上に適用する位置埋め込みの種類。"sine"または"learned"のいずれかです。 - dilation (
bool、任意、デフォルトはFalse) — 最後の畳み込みブロック(DC5)で stride の代わりに dilation を使用するかを指定します。use_timm_backbone=Trueの場合のみサポートされます。 - num_feature_levels (
int、任意、デフォルトは 4) — 入力特徴量のレベル数です。 - encoder_n_points (
int、省略可能、デフォルト値は 4)— エンコーダーの各アテンションヘッドにおいて、各特徴レベルでサンプリングされるキーの数を指定します。 - decoder_n_points (
int、省略可能、デフォルトは 4) — デコーダーの各アテンションヘッドにおいて、各特徴量レベルでサンプリングされるキーの数を指定します。 - two_stage (
bool、省略可、デフォルトはFalse) — 2段階の Deformable DETR を適用するかどうか。この場合、領域提案も Deformable DETR のバリアントによって生成され、それらがデコーダーに渡されてバウンディングボックスの反復的な精緻化が行われます。 - two_stage_num_proposals (
int, 任意、デフォルト値は 300) —two_stageがTrueに設定されている場合、生成される領域提案の数を指定します。 - with_box_refine (
bool、任意、デフォルトはFalse) — 各デコーダ層が前層の予測に基づいてバウンディングボックスを改善する、反復的なバウンディングボックスの精緻化を適用するかどうかを指定します。 - class_cost (
int、省略可能、デフォルトは1) — ハンガリー法によるマッチングコストにおける、分類誤差の相対的な重み。 - bbox_cost (
int、任意、デフォルトは5) — ハンガリー法によるマッチングコストにおける、L1バウンディングボックス誤差の相対的な重みです。 - giou_cost (
int、任意、デフォルト値は2) — ハンガリー法によるマッチングコストにおける、汎化 IoU ロスの相対的な重み。 - mask_loss_coefficient (
int、任意、デフォルトは1) — パノプティックセグメンテーション損失におけるfocal lossの相対的な重み。 - dice_loss_coefficient (
int, 任意、デフォルトは1) — パンノミックセグメンテーション損失における dice loss の相対的な重み。 - bbox_loss_coefficient (
int、任意、デフォルトは5) — パノプティックセグメンテーション損失における L1 バウンディングボックス損失の相対的な重み。 - giou_loss_coefficient (
int、任意、デフォルトは2) — パノラミックセグメンテーション損失における汎化 IoU 損失の相対的な重み。 - eos_coefficient (
float、任意、デフォルトは0.1) — オブジェクト検出の損失における「no-object」クラスの相対的な分類重み。 - focal_alpha (
float、任意、デフォルトは0.25) — focal loss の Alpha パラメータ。 - disable_custom_kernels (
bool、任意、デフォルトはFalse) — カスタム CUDA カーネルおよび CPU カーネルの使用を無効にします。このオプションは ONNX エクスポートに必要であり、カスタムカーネルは PyTorch の ONNX エクスポートではサポートされていないためです。 - tie_word_embeddings (
bool、任意、デフォルトはTrue) — モデルのtied_weights_keysマッピングに従って重み埋め込みを共有するかどうかを指定します。
これはDeformableDetrModelの設定を保存するための設定クラスです。指定された引数に基づいてDeformable Detrモデルをインスタンス化し、モデルのアーキテクチャを定義するために使用されます。デフォルト値で設定をインスタンス化すると、SenseTime/deformable-detrと類似した設定が得られます。
設定オブジェクトはPreTrainedConfigを継承し、モデルの出力を制御するために使用できます。詳細については、PreTrainedConfigのドキュメントを参照してください。
例:
>>> from transformers import DeformableDetrConfig, DeformableDetrModel
>>> # Initializing a Deformable DETR SenseTime/deformable-detr style configuration
>>> configuration = DeformableDetrConfig()
>>> # Initializing a model (with random weights) from the SenseTime/deformable-detr style configuration
>>> model = DeformableDetrModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.configDeformableDetrModel
class transformers.DeformableDetrModel
< source >( config: DeformableDetrConfig )
パラメータ
- config (DeformableDetrConfig) — モデルのパラメータをすべて含むモデル設定クラスです。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、from_pretrained() メソッドを参照してください。
Deformable DETRのベースモデル(backboneとencoder-decoder Transformerで構成)は、特定のヘッドを備えずに生のhidden-statesを出力します。
このモデルは PreTrainedModel を継承しています。すべてのモデルに実装されている汎用的なメソッド(ダウンロードや保存、入力埋め込みのリサイズ、ヘッドのプルーニングなど)については、スーパークラスのドキュメントを参照してください。
このモデルは、PyTorchのtorch.nn.Moduleのサブクラスでもあります。 通常のPyTorch Moduleとして使用し、一般的な使用方法や動作に関する詳細については、PyTorchのドキュメントを参照してください。
forward
< source >( pixel_values: Tensorpixel_mask: typing.Optional[torch.LongTensor] = Nonedecoder_attention_mask: typing.Optional[torch.Tensor] = Noneencoder_outputs: typing.Optional[torch.Tensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonedecoder_inputs_embeds: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → DeformableDetrModelOutput or tuple(torch.Tensor)
パラメータ
- pixel_values (
torch.Tensor、形状(batch_size, num_channels, image_size, image_size)) — 入力画像に対応するテンソルです。ピクセル値はimage_processor_classを使用して取得できます。詳細はimage_processor_class.__call__を参照してください(processor_classは画像の処理にimage_processor_classを使用します)。 - pixel_mask (
torch.LongTensor形状(batch_size, height, width), 省略可) — パディングピクセル値に対するアテンションの適用を回避するためのマスク。マスク値は[0, 1]:- 実在するピクセル(つまり、マスクされていない)に対して1
- padding(つまり、マスクされている)ピクセルは0です。
- decoder_attention_mask (
torch.Tensor、形状(batch_size, num_queries)、任意) — デフォルトでは使用されません。オブジェクトクエリをマスクするために使用できます。 - encoder_outputs (
torch.Tensor, 任意) —last_hidden_state、任意:hidden_states、任意:attentionsのタプルlast_hidden_stateは形状(batch_size, sequence_length, hidden_size)、任意)であり、エンコーダーの最終層の出力における隠れ状態のシーケンスです。デコーダーのクロスアテンションで使用されます。 - inputs_embeds (
torch.Tensor、形状(batch_size, sequence_length, hidden_size)、任意) — フラット化された特徴マップ(バックボーンと投影層の出力)を渡す代わりに、画像のフラット化された表現を直接渡すこともできます。 - decoder_inputs_embeds (
torch.Tensor、形状(batch_size, num_queries, hidden_size)、任意) — クエリをゼロのテンソルで初期化する代わりに、埋め込み表現を直接渡すこともできます。
戻り値
DeformableDetrModelOutput または tuple(torch.Tensor)
DeformableDetrModelOutput または、torch.Tensor のタプル(return_dict=False が渡された場合、または config.return_dict=False の場合)。設定(None)や入力に応じて、さまざまな要素で構成されます。
DeformableDetrModelのforwardメソッドは、__call__特殊メソッドをオーバーライドします。
この関数内でフォワードパスの手順を定義する必要がありますが、その後、この関数ではなく
Moduleインスタンスを呼び出すべきです。前者は前処理と後処理の実行を適切に処理するのに対し、後者はそれらを黙って無視するためです。
init_reference_points (
torch.Tensor、形状(batch_size, num_queries, 4)) — Transformerデコーダーに渡される初期の参照点。last_hidden_state (
torch.Tensor、形状(batch_size, num_queries, hidden_size)) — モデルのデコーダーの最終層の出力における、隠れ状態のシーケンスです。intermediate_hidden_states (
torch.Tensor、形状(batch_size, config.decoder_layers, num_queries, hidden_size)) — 中間隠れ状態のスタック(デコーダーの各層の出力)。intermediate_reference_points (
torch.Tensor、形状(batch_size, config.decoder_layers, num_queries, 4)) — 中間参照点のスタック(デコーダーの各層の参照点)。decoder_hidden_states (
tuple[torch.Tensor]、optional、output_hidden_states=Trueが渡された場合またはconfig.output_hidden_states=Trueの場合に返されます) —torch.Tensorのタプル(埋め込み層を持つモデルの場合、埋め込みの出力が 1 つ、各層の出力がそれぞれ 1 つずつ)で、形状は(batch_size, sequence_length, hidden_size)です。各層の出力および初期埋め込み出力における、デコーダーの隠れ状態。
decoder_attentions (
tuple[torch.Tensor]、optional、output_attentions=Trueが渡された場合またはconfig.output_attentions=Trueの場合に返されます) —torch.Tensorのタプル(各レイヤーごとに1つ)、形状は(batch_size, num_heads, sequence_length, sequence_length)。自己アテンションヘッドにおける加重平均を計算するために使用される、アテンションのsoftmax後のデコーダーのアテンション重み。
cross_attentions (
tuple[torch.Tensor]、optional、output_attentions=Trueが渡された場合またはconfig.output_attentions=Trueの場合に返されます) —torch.Tensorのタプル(各レイヤーごとに1つ)、形状は(batch_size, num_heads, sequence_length, sequence_length)。クロスアテンション層のアテンション重みは、アテンションのsoftmax適用後に計算され、クロスアテンションヘッドにおける加重平均の計算に使用されます。
encoder_last_hidden_state (
torch.Tensor、形状(batch_size, sequence_length, hidden_size)、任意) — モデルのエンコーダーの最終層の出力における隠れ状態のシーケンス。encoder_hidden_states (
tuple[torch.Tensor]、optional、output_hidden_states=Trueが渡された場合またはconfig.output_hidden_states=Trueの場合に返されます) —torch.Tensorのタプル(埋め込み層を持つモデルの場合、埋め込みの出力が 1 つ、各層の出力がそれぞれ 1 つずつ)で、形状は(batch_size, sequence_length, hidden_size)です。各層の出力および初期埋め込み出力におけるエンコーダーの隠れ状態。
encoder_attentions (
tuple[torch.Tensor]、optional、output_attentions=Trueが渡された場合またはconfig.output_attentions=Trueの場合に返されます) —torch.Tensorのタプル(各レイヤーごとに1つ)、形状は(batch_size, num_heads, sequence_length, sequence_length)。アテンションのsoftmaxを適用した後のエンコーダーのアテンション重み。自己アテンションヘッドにおける加重平均の計算に使用されます。
enc_outputs_class (
torch.Tensor、形状(batch_size, sequence_length, config.num_labels)、任意、config.with_box_refine=Trueかつconfig.two_stage=Trueの場合に返されます) — 第1段階でスコア上位のconfig.two_stage_num_proposals個のバウンディングボックスがリージョンプロポーザルとして選択される、予測されたバウンディングボックスのスコアです。バウンディングボックスの二値分類(すなわち、フォアグラウンドとバックグラウンド)の出力です。enc_outputs_coord_logits (
torch.Tensor、形状(batch_size, sequence_length, 4)、任意、config.with_box_refine=Trueかつconfig.two_stage=Trueの場合に返されます) — 第1段階で予測されるバウンディングボックス座標のロジット。
例:
>>> from transformers import AutoImageProcessor, DeformableDetrModel
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
... image = Image.open(BytesIO(response.read()))
>>> image_processor = AutoImageProcessor.from_pretrained("SenseTime/deformable-detr")
>>> model = DeformableDetrModel.from_pretrained("SenseTime/deformable-detr")
>>> inputs = image_processor(images=image, return_tensors="pt")
>>> outputs = model(**inputs)
>>> last_hidden_states = outputs.last_hidden_state
>>> list(last_hidden_states.shape)
[1, 300, 256]DeformableDetrForObjectDetection
クラス transformers.DeformableDetrForObjectDetection
< source >( config: DeformableDetrConfig )
パラメータ
- config (DeformableDetrConfig) — モデルのパラメータをすべて含むモデル設定クラスです。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、from_pretrained() メソッドを参照してください。
COCO検出などのタスク向けに、オブジェクト検出ヘッドを上部に備えたDeformable DETRモデル(バックボーンとエンコーダー・デコーダーのTransformerで構成)。
このモデルは PreTrainedModel を継承しています。すべてのモデルに実装されている汎用的なメソッド(ダウンロードや保存、入力埋め込みのリサイズ、ヘッドのプルーニングなど)については、スーパークラスのドキュメントを参照してください。
このモデルは、PyTorchのtorch.nn.Moduleのサブクラスでもあります。 通常のPyTorch Moduleとして使用し、一般的な使用方法や動作に関する詳細については、PyTorchのドキュメントを参照してください。
forward
< source >( pixel_values: Tensorpixel_mask: typing.Optional[torch.LongTensor] = Nonedecoder_attention_mask: typing.Optional[torch.Tensor] = Noneencoder_outputs: typing.Optional[torch.Tensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonedecoder_inputs_embeds: typing.Optional[torch.Tensor] = Nonelabels: list[dict] | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → DeformableDetrObjectDetectionOutput or tuple(torch.Tensor)
パラメータ
- pixel_values (
torch.Tensor、形状(batch_size, num_channels, image_size, image_size)) — 入力画像に対応するテンソルです。ピクセル値はimage_processor_classを使用して取得できます。詳細はimage_processor_class.__call__を参照してください(processor_classは画像の処理にimage_processor_classを使用します)。 - pixel_mask (
torch.LongTensor形状(batch_size, height, width), 省略可) — パディングピクセル値に対するアテンションの適用を回避するためのマスク。マスク値は[0, 1]:- 実在するピクセル(つまり、マスクされていない)に対して1
- padding(つまり、マスクされている)ピクセルは0です。
- decoder_attention_mask (
torch.Tensor、形状(batch_size, num_queries)、任意) — デフォルトでは使用されません。オブジェクトクエリをマスクするために使用できます。 - encoder_outputs (
torch.Tensor, 任意) —last_hidden_state、任意:hidden_states、任意:attentionsのタプルlast_hidden_stateは形状(batch_size, sequence_length, hidden_size)、任意)であり、エンコーダーの最終層の出力における隠れ状態のシーケンスです。デコーダーのクロスアテンションで使用されます。 - inputs_embeds (
torch.Tensor、形状(batch_size, sequence_length, hidden_size)、任意) — フラット化された特徴マップ(バックボーンと投影層の出力)を渡す代わりに、画像のフラット化された表現を直接渡すこともできます。 - decoder_inputs_embeds (
torch.Tensor、形状(batch_size, num_queries, hidden_size)、任意) — クエリをゼロのテンソルで初期化する代わりに、埋め込み表現を直接渡すこともできます。 - labels (
list[Dict]、長さ(batch_size,)、任意) — 二部マッチング損失を計算するためのラベル。辞書のリストで、各辞書には少なくとも以下の 2 つのキーが含まれます: ‘class_labels’ と ‘boxes’ (それぞれバッチ内の画像のクラスラベルとバウンディングボックス)。クラスラベル自体は長さ(number of bounding boxes in the image,)のtorch.LongTensorであり、ボックスは形状(number of bounding boxes in the image, 4)のtorch.Tensorである必要があります。
戻り値
DeformableDetrObjectDetectionOutput または tuple(torch.Tensor)
DeformableDetrObjectDetectionOutput、またはtorch.Tensorのタプル(return_dict=Falseが渡された場合、またはconfig.return_dict=Falseの場合)。設定(None)や入力に応じて、さまざまな要素で構成されます。
DeformableDetrForObjectDetectionのforwardメソッドは、__call__特殊メソッドをオーバーライドします。
この関数内でフォワードパスの手順を定義する必要がありますが、その後、この関数ではなく
Moduleインスタンスを呼び出すべきです。前者は前処理と後処理の実行を適切に処理するのに対し、後者はそれらを黙って無視するためです。
loss (
torch.Tensor、形状(1,)、任意、labelsが提供された場合に返されます) — クラス予測の負の対数尤度(クロスエントロピー)とバウンディングボックス損失の線形結合による総損失です。後者は、L1損失と汎用スケール不変IoU損失の線形結合として定義されます。loss_dict (
Dict, 任意) — 個別の損失を含む辞書です。ログ出力に便利です。logits (
torch.Tensor、形状(batch_size, num_queries, num_classes + 1)) — すべてのクエリに対する分類 logits(no-object を含む)。pred_boxes (
torch.Tensor、shape(batch_size, num_queries, 4)) — すべてのクエリに対する正規化されたボックス座標です。(center_x, center_y, width, height) で表されます。これらの値は、バッチ内の各画像のサイズに対して [0, 1] の範囲で正規化されています(パディングは考慮されません)。~DeformableDetrProcessor.post_process_object_detectionを使用すると、正規化されていないバウンディングボックスを取得できます。auxiliary_outputs (
list[Dict]、optional) — オプション。補助損失が有効化されている場合(つまりconfig.auxiliary_lossがTrueに設定されている場合)かつラベルが提供されている場合にのみ返されます。各デコーダ層について、上記の2つのキー(logitsとpred_boxes)を含む辞書のリストです。last_hidden_state (
torch.Tensor、形状(batch_size, num_queries, hidden_size)、任意) — モデルのデコーダーの最終層の出力における、隠れ状態のシーケンス。decoder_hidden_states (
tuple[torch.Tensor]、optional、output_hidden_states=Trueが渡された場合またはconfig.output_hidden_states=Trueの場合に返されます) —torch.Tensorのタプル(埋め込み層を持つモデルの場合、埋め込みの出力が 1 つ、各層の出力がそれぞれ 1 つずつ)で、形状は(batch_size, sequence_length, hidden_size)です。各層の出力および初期埋め込み出力における、デコーダーの隠れ状態。
decoder_attentions (
tuple[torch.Tensor]、optional、output_attentions=Trueが渡された場合またはconfig.output_attentions=Trueの場合に返されます) —torch.Tensorのタプル(各レイヤーごとに1つ)、形状は(batch_size, num_heads, sequence_length, sequence_length)。自己アテンションヘッドにおける加重平均を計算するために使用される、アテンションのsoftmax後のデコーダーのアテンション重み。
cross_attentions (
tuple[torch.Tensor]、optional、output_attentions=Trueが渡された場合またはconfig.output_attentions=Trueの場合に返されます) —torch.Tensorのタプル(各レイヤーごとに1つ)、形状は(batch_size, num_heads, sequence_length, sequence_length)。クロスアテンション層のアテンション重みは、アテンションのsoftmax適用後に計算され、クロスアテンションヘッドにおける加重平均の計算に使用されます。
encoder_last_hidden_state (
torch.Tensor、形状(batch_size, sequence_length, hidden_size)、任意) — モデルのエンコーダーの最終層の出力における隠れ状態のシーケンス。encoder_hidden_states (
tuple[torch.Tensor]、optional、output_hidden_states=Trueが渡された場合またはconfig.output_hidden_states=Trueの場合に返されます) —torch.Tensorのタプル(埋め込み層を持つモデルの場合、埋め込みの出力が 1 つ、各層の出力がそれぞれ 1 つずつ)で、形状は(batch_size, sequence_length, hidden_size)です。各層の出力および初期埋め込み出力におけるエンコーダーの隠れ状態。
encoder_attentions (
tuple[torch.Tensor]、optional、output_attentions=Trueが渡された場合またはconfig.output_attentions=Trueの場合に返されます) —torch.Tensorのタプル(各レイヤーごとに1つ)、形状は(batch_size, num_heads, sequence_length, sequence_length)。アテンションのsoftmaxを適用した後のエンコーダーのアテンション重み。自己アテンションヘッドにおける加重平均の計算に使用されます。
init_reference_points (
torch.Tensor、形状(batch_size, num_queries, 4)) — Transformerデコーダーに渡される初期の参照点。intermediate_hidden_states (
torch.Tensor、形状(batch_size, config.decoder_layers, num_queries, hidden_size)) — 中間隠れ状態のスタック(デコーダーの各層の出力)。intermediate_reference_points (
torch.Tensor、形状(batch_size, config.decoder_layers, num_queries, 4)) — 中間参照点のスタック(デコーダーの各層の参照点)。enc_outputs_class (
torch.Tensor、形状(batch_size, sequence_length, config.num_labels)、任意、config.with_box_refine=Trueかつconfig.two_stage=Trueの場合に返されます) — 第1段階でスコア上位のconfig.two_stage_num_proposals個のバウンディングボックスがリージョンプロポーザルとして選択される、予測されたバウンディングボックスのスコアです。バウンディングボックスの二値分類(すなわち、フォアグラウンドとバックグラウンド)の出力です。enc_outputs_coord_logits (
torch.Tensor、形状(batch_size, sequence_length, 4)、任意、config.with_box_refine=Trueかつconfig.two_stage=Trueの場合に返されます) — 第1段階で予測されるバウンディングボックス座標のロジット。
例:
>>> from transformers import AutoImageProcessor, DeformableDetrForObjectDetection
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
... image = Image.open(BytesIO(response.read()))
>>> image_processor = AutoImageProcessor.from_pretrained("SenseTime/deformable-detr")
>>> model = DeformableDetrForObjectDetection.from_pretrained("SenseTime/deformable-detr")
>>> inputs = image_processor(images=image, return_tensors="pt")
>>> outputs = model(**inputs)
>>> # convert outputs (bounding boxes and class logits) to Pascal VOC format (xmin, ymin, xmax, ymax)
>>> target_sizes = torch.tensor([image.size[::-1]])
>>> results = image_processor.post_process_object_detection(outputs, threshold=0.5, target_sizes=target_sizes)[
... 0
... ]
>>> for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
... box = [round(i, 2) for i in box.tolist()]
... print(
... f"Detected {model.config.id2label[label.item()]} with confidence "
... f"{round(score.item(), 3)} at location {box}"
... )
Detected cat with confidence 0.8 at location [16.5, 52.84, 318.25, 470.78]
Detected cat with confidence 0.789 at location [342.19, 24.3, 640.02, 372.25]
Detected remote with confidence 0.633 at location [40.79, 72.78, 176.76, 117.25]