Transformers 文档
TextNet
并获得增强的文档体验
开始使用
该模型于 2021-11-03 发布,并于 2025-01-08 添加到 Hugging Face Transformers。
TextNet
概述
TextNet 模型由 Zhe Chen, Jiahao Wang, Wenhai Wang, Guo Chen, Enze Xie, Ping Luo, Tong Lu 在 FAST: Faster Arbitrarily-Shaped Text Detector with Minimalist Kernel Representation 中提出。TextNet 是一个适用于文本检测任务的视觉骨干网络。它是通过神经架构搜索 (NAS) 在骨干网络上进行搜索得到的,其奖励函数是文本检测任务(为文本检测提供强大的特征)。
TextNet 骨干网络是 FAST 的一部分。摘自 原始论文。该模型由 Raghavan、jadechoghari 和 nielsr 贡献。
使用技巧
TextNet 主要用作文本检测的架构搜索的骨干网络。骨干网络的每个阶段都包含一个步长为 2 的卷积和可搜索的块。具体来说,我们提出了一组层级候选集,定义为 {conv3×3, conv1×3, conv3×1, identity}。由于 1×3 和 3×1 卷积具有非对称核和定向结构先验,它们可能有助于捕捉极端宽高比和旋转文本行的特征。
TextNet 是 Fast 的骨干,但也可以用作高效的文本/图像分类。我们添加了一个 TextNetForImageClassification,以便用户可以在预训练的 TextNet 权重之上训练图像分类器。
TextNetConfig
class transformers.TextNetConfig
< 源 >( stem_kernel_size = 3 stem_stride = 2 stem_num_channels = 3 stem_out_channels = 64 stem_act_func = 'relu' image_size = [640, 640] conv_layer_kernel_sizes = None conv_layer_strides = None hidden_sizes = [64, 64, 128, 256, 512] batch_norm_eps = 1e-05 initializer_range = 0.02 out_features = None out_indices = None **kwargs )
参数
- stem_kernel_size (
int, optional, defaults to 3) — 初始卷积层的核大小。 - stem_stride (
int, optional, defaults to 2) — 初始卷积层的步长。 - stem_num_channels (
int, optional, defaults to 3) — 初始卷积层的输入通道数。 - stem_out_channels (
int, optional, defaults to 64) — 初始卷积层的输出通道数。 - stem_act_func (
str, optional, defaults to"relu") — 初始卷积层的激活函数。 - image_size (
tuple[int, int], optional, defaults to[640, 640]) — 每张图片的尺寸(分辨率)。 - conv_layer_kernel_sizes (
list[list[list[int]]], optional) — 阶段式核大小列表。如果为None,则默认为:[[[3, 3], [3, 3], [3, 3]], [[3, 3], [1, 3], [3, 3], [3, 1]], [[3, 3], [3, 3], [3, 1], [1, 3]], [[3, 3], [3, 1], [1, 3], [3, 3]]]。 - conv_layer_strides (
list[list[int]], optional) — 阶段式步长列表。如果为None,则默认为:[[1, 2, 1], [2, 1, 1, 1], [2, 1, 1, 1], [2, 1, 1, 1]]。 - hidden_sizes (
list[int], optional, defaults to[64, 64, 128, 256, 512]) — 每个阶段的维度(隐藏大小)。 - batch_norm_eps (
float, 可选, 默认为 1e-05) — 批归一化层使用的 epsilon。 - initializer_range (
float, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - out_features (
list[str], 可选) — 如果用作骨干网络,则输出的特征列表。可以是"stem"、"stage1"、"stage2"等(取决于模型有多少个阶段)。如果未设置且out_indices已设置,则默认为相应的阶段。如果未设置且out_indices未设置,则默认为最后一个阶段。 - out_indices (
list[int], 可选) — 如果用作骨干网络,则输出的特征索引列表。可以是 0、1、2 等(取决于模型有多少个阶段)。如果未设置且out_features已设置,则默认为相应的阶段。如果未设置且out_features未设置,则默认为最后一个阶段。
这是用于存储 TextNextModel 配置的配置类。它用于根据指定的参数实例化 TextNext 模型,定义模型架构。使用默认值实例化配置将产生与 czczup/textnet-base 类似的配置。配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请阅读 PreTrainedConfig 的文档。
TextNetImageProcessor
class transformers.TextNetImageProcessor
< source >( do_resize: bool = True size: dict[str, int] | None = None size_divisor: int = 32 resample: Resampling = <Resampling.BILINEAR: 2> do_center_crop: bool = False crop_size: dict[str, int] | None = None do_rescale: bool = True rescale_factor: int | float = 0.00392156862745098 do_normalize: bool = True image_mean: float | list[float] | None = [0.485, 0.456, 0.406] image_std: float | list[float] | None = [0.229, 0.224, 0.225] do_convert_rgb: bool = True **kwargs )
参数
- do_resize (
bool, 可选, 默认为True) — 是否调整图像的(高度,宽度)尺寸到指定的size。可以通过preprocess方法中的do_resize参数覆盖。 - size (
dict[str, int], 可选, 默认为{"shortest_edge" -- 640}): 调整后的图像尺寸。图像的较短边将被调整到 size[“shortest_edge”],较长边将被调整以保持输入纵横比。可以通过preprocess方法中的size参数覆盖。 - size_divisor (
int, 可选, 默认为 32) — 确保调整尺寸后的高度和宽度是该值的倍数。 - resample (
PILImageResampling, 可选, 默认为Resampling.BILINEAR) — 调整图像大小时使用的重采样过滤器。可以通过preprocess方法中的resample参数覆盖。 - do_center_crop (
bool, 可选, 默认为False) — 是否将图像中心裁剪到指定的crop_size。可以通过preprocess方法中的do_center_crop参数覆盖。 - crop_size (
dict[str, int], 可选, 默认为 224) — 应用center_crop后的输出图像尺寸。可以通过preprocess方法中的crop_size参数覆盖。 - do_rescale (
bool, 可选, 默认为True) — 是否通过指定的比例rescale_factor来缩放图像。可以通过preprocess方法中的do_rescale参数覆盖。 - rescale_factor (
int或float, 可选, 默认为1/255) — 缩放图像时使用的比例因子。可以通过preprocess方法中的rescale_factor参数覆盖。 - do_normalize (
bool, 可选, 默认为True) — 是否对图像进行归一化。可以通过preprocess方法中的do_normalize参数覆盖。 - image_mean (
float或list[float], 可选, 默认为[0.485, 0.456, 0.406]) — 归一化图像时使用的均值。这是一个浮点数或浮点数列表,长度等于图像通道数。可以通过preprocess方法中的image_mean参数覆盖。 - image_std (
float或list[float], 可选, 默认为[0.229, 0.224, 0.225]) — 归一化图像时使用的标准差。这是一个浮点数或浮点数列表,长度等于图像通道数。可以通过preprocess方法中的image_std参数覆盖。可以通过preprocess方法中的image_std参数覆盖。 - do_convert_rgb (
bool, 可选, 默认为True) — 是否将图像转换为 RGB。
构造一个 TextNet 图像处理器。
preprocess
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] do_resize: bool | None = None size: dict[str, int] | None = None size_divisor: int | None = None resample: PIL.Image.Resampling | None = None do_center_crop: bool | None = None crop_size: int | None = None do_rescale: bool | None = None rescale_factor: float | None = None do_normalize: bool | None = None image_mean: float | list[float] | None = None image_std: float | list[float] | None = None do_convert_rgb: bool | None = None return_tensors: str | transformers.utils.generic.TensorType | None = None data_format: transformers.image_utils.ChannelDimension | None = <ChannelDimension.FIRST: 'channels_first'> input_data_format: str | transformers.image_utils.ChannelDimension | None = None **kwargs )
参数
- images (
ImageInput) — 要预处理的图像。期望一个或一批像素值范围为 0 到 255 的图像。如果传入像素值在 0 到 1 之间的图像,请将do_rescale设置为False。 - do_resize (
bool, 可选, 默认为self.do_resize) — 是否调整图像大小。 - size (
dict[str, int], 可选, 默认为self.size) — 调整后的图像尺寸。图像的较短边将被调整到 size[“shortest_edge”],较长边将被调整以保持输入纵横比。 - size_divisor (
int, 可选, 默认为 32) — 确保调整尺寸后的高度和宽度是该值的倍数。 - resample (
int, 可选, 默认为self.resample) — 调整图像大小时使用的重采样过滤器。可以是PILImageResampling枚举中的一个。仅当do_resize设置为True时才生效。 - do_center_crop (
bool, 可选, 默认为self.do_center_crop) — 是否进行中心裁剪。 - crop_size (
dict[str, int], 可选, 默认为self.crop_size) — 中心裁剪的大小。仅当do_center_crop设置为True时生效。 - do_rescale (
bool, 可选, 默认为self.do_rescale) — 是否进行重缩放。 - rescale_factor (
float, 可选, 默认为self.rescale_factor) — 如果do_rescale设置为True,则用于重缩放图像的因子。 - do_normalize (
bool, 可选, 默认为self.do_normalize) — 是否进行归一化。 - image_mean (
float或list[float], 可选, 默认为self.image_mean) — 用于归一化的图像均值。仅当do_normalize设置为True时生效。 - image_std (
float或list[float], 可选, 默认为self.image_std) — 用于归一化的图像标准差。仅当do_normalize设置为True时生效。 - do_convert_rgb (
bool, 可选, 默认为self.do_convert_rgb) — 是否将图像转换为 RGB。 - return_tensors (
str或TensorType, 可选) — 返回的张量类型。可以是以下之一:- 未设置:返回
np.ndarray列表。 TensorType.PYTORCH或'pt':返回torch.Tensor类型的批次。TensorType.NUMPY或'np':返回np.ndarray类型的批次。
- 未设置:返回
- data_format (
ChannelDimension或str, 可选, 默认为ChannelDimension.FIRST) — 输出图像的通道维度格式。可以是以下之一:"channels_first"或ChannelDimension.FIRST:图像格式为 (num_channels, height, width)。"channels_last"或ChannelDimension.LAST:图像格式为 (height, width, num_channels)。- 未设置:使用输入图像的通道维度格式。
- input_data_format (
ChannelDimension或str, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像推断通道维度格式。可以是以下之一:"channels_first"或ChannelDimension.FIRST:图像格式为 (num_channels, height, width)。"channels_last"或ChannelDimension.LAST:图像格式为 (height, width, num_channels)。"none"或ChannelDimension.NONE:图像格式为 (height, width)。
预处理一张或一批图像。
TextNetImageProcessorFast
class transformers.TextNetImageProcessorFast
< 源代码 >( **kwargs: typing_extensions.Unpack[transformers.models.textnet.image_processing_textnet.TextNetImageProcessorKwargs] )
构造一个快速的Textnet图像处理器。
preprocess
< 源代码 >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] **kwargs: typing_extensions.Unpack[transformers.models.textnet.image_processing_textnet.TextNetImageProcessorKwargs] ) → <class 'transformers.image_processing_base.BatchFeature'>
参数
- images (
Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list, list, list]) — 要预处理的图像。期望是像素值在 0 到 255 之间的单个或批次的图像。如果传入的图像像素值在 0 到 1 之间,请设置do_rescale=False。 - do_convert_rgb (
bool | None.do_convert_rgb) — 是否将图像转换为 RGB。 - do_resize (
bool | None.do_resize) — 是否对图像进行缩放。 - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]) — 描述模型最大输入尺寸。 - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]) — 应用center_crop后的输出图像大小。 - resample (
Annotated[Union[PILImageResampling, int, NoneType], None]) — 如果调整图像大小,则使用的重采样滤波器。可以是枚举值PILImageResampling之一。仅当do_resize设置为True时生效。 - do_rescale (
bool | None.do_rescale) — 是否进行重缩放。 - rescale_factor (
float | None.rescale_factor) — 如果do_rescale设置为True,则用于重缩放图像的因子。 - do_normalize (
bool | None.do_normalize) — 是否进行归一化。 - image_mean (
float | list[float] | tuple[float, ...] | None.image_mean) — 用于归一化的图像均值。仅当do_normalize设置为True时生效。 - image_std (
float | list[float] | tuple[float, ...] | None.image_std) — 用于归一化的图像标准差。仅当do_normalize设置为True时生效。 - do_pad (
bool | None.do_pad) — 是否对图像进行填充。填充是根据批次中的最大尺寸或每张固定方形尺寸进行的。确切的填充策略取决于模型。 - pad_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]) — 要将图像填充到的大小({"height": int, "width" int})。必须大于预处理时提供的任何图像尺寸。如果未提供pad_size,图像将填充到批次中的最大高度和宽度。仅在do_pad=True时应用。 - do_center_crop (
bool | None.do_center_crop) — 是否进行中心裁剪。 - data_format (
str | ~image_utils.ChannelDimension | None.data_format) — 仅支持ChannelDimension.FIRST。为了与慢速处理器兼容而添加。 - input_data_format (
str | ~image_utils.ChannelDimension | None.input_data_format) — 输入图像的通道维度格式。如果未设置,则从输入图像推断通道维度格式。可以是以下之一:"channels_first"或ChannelDimension.FIRST:图像格式为 (num_channels, height, width)。"channels_last"或ChannelDimension.LAST:图像格式为 (height, width, num_channels)。"none"或ChannelDimension.NONE:图像格式为 (height, width)。
- device (
Annotated[Union[str, torch.device, NoneType], None]) — 要处理图像的设备。如果未设置,则从输入图像推断设备。 - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None]) — 如果设置为 `pt`,则返回堆叠的张量,否则返回张量列表。 - disable_grouping (
bool | None.disable_grouping) — 是否禁用按大小对图像进行分组,以便单独处理而不是批量处理。如果为 None,则如果图像在 CPU 上,则设置为 True,否则设置为 False。此选择基于经验观察,如下文所述: https://github.com/huggingface/transformers/pull/38157 - image_seq_length (
int | None.image_seq_length) — 用于输入中每张图像的图像 token 数量。为向后兼容而添加,但将来模型应将此设置为主处理器属性。 - size_divisor (
<class 'int'>.size_divisor) — 确保高度和宽度都可以被整除的大小。
返回
<class 'transformers.image_processing_base.BatchFeature'>
- data (
dict) — 由 call 方法返回的列表/数组/张量字典(“pixel_values”等)。 - tensor_type (
Union[None, str, TensorType], optional) — 您可以在此处提供 tensor_type 以在初始化时将整数列表转换为 PyTorch/Numpy 张量。
TextNetModel
class transformers.TextNetModel
< source >( config model_args: ~utils.generic.ModelArgs | None = None adapter_args: ~utils.generic.AdapterArgs | None = None lora_args: ~utils.generic.LoRAArgs | None = None tokenizer_args: ~utils.generic.TokenizerArgs | None = None dataset_args: ~utils.generic.DatasetArgs | None = None data_args: ~utils.generic.DataArgs | None = None training_args: ~utils.generic.TrainingArgs | None = None generation_args: ~utils.generic.GenerationArgs | None = None vision_tower_args: ~utils.generic.VisionTowerArgs | None = None qlora_args: ~utils.generic.QLoRAArgs | None = None vision_tower_template_args: ~utils.generic.VisionTowerTemplateArgs | None = None video_tower_args: ~utils.generic.VideoTowerArgs | None = None vision_config: ~utils.generic.VisionConfig | None = None video_config: ~utils.generic.VideoConfig | None = None load_dataset: bool | None = None load_data_collator: bool | None = None load_processor: bool | None = None load_lora_adapter: bool | None = None load_adapter: bool | None = None load_qlora_adapter: bool | None = None **kwargs: typing_extensions.Unpack[transformers.modeling_utils.PreTrainedModelKwargs] )
参数
- config (TextNetModel) — 模型配置类,包含模型的所有参数。使用配置文件初始化不会加载与模型相关的权重,只会加载配置。请查看 from_pretrained() 方法来加载模型权重。
The bare Textnet Model outputting raw hidden-states without any specific head on top.
此模型继承自 PreTrainedModel。查看其父类文档,了解库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头等)。
此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。
forward
< source >( pixel_values: Tensor output_hidden_states: bool | None = None return_dict: bool | None = None **kwargs ) → transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttention or tuple(torch.FloatTensor)
参数
- pixel_values (
torch.Tensor,形状为(batch_size, num_channels, image_size, image_size)) — 对应于输入图像的张量。可以使用 TextNetImageProcessorFast 获取像素值。有关详细信息,请参阅 TextNetImageProcessorFast.call()(processor_class使用 TextNetImageProcessorFast 处理图像)。 - output_hidden_states (
bool, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量下的hidden_states。 - return_dict (
bool, optional) — 是否返回一个 ModelOutput 而不是一个普通元组。
返回
transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttention 或 tuple(torch.FloatTensor)
A transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttention or a tuple of torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration (TextNetConfig) and inputs.
-
last_hidden_state (
torch.FloatTensor, 形状为(batch_size, num_channels, height, width)) — 模型最后一层输出的隐藏状态序列。 -
pooler_output (
torch.FloatTensor, 形状为(batch_size, hidden_size)) — 经过空间维度池化操作后的最后一层隐藏状态。 -
hidden_states (
tuple(torch.FloatTensor), optional, 当传入output_hidden_states=True或config.output_hidden_states=True时返回) —torch.FloatTensor的元组(如果模型有嵌入层,则包含一个嵌入层输出,加上每层的一个输出),形状为(batch_size, num_channels, height, width)。模型在每个层输出的隐藏状态以及可选的初始嵌入输出。
The TextNetModel forward method, overrides the __call__ special method.
虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用
Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
TextNetForImageClassification
class transformers.TextNetForImageClassification
< source >( config model_args: ~utils.generic.ModelArgs | None = None adapter_args: ~utils.generic.AdapterArgs | None = None lora_args: ~utils.generic.LoRAArgs | None = None tokenizer_args: ~utils.generic.TokenizerArgs | None = None dataset_args: ~utils.generic.DatasetArgs | None = None data_args: ~utils.generic.DataArgs | None = None training_args: ~utils.generic.TrainingArgs | None = None generation_args: ~utils.generic.GenerationArgs | None = None vision_tower_args: ~utils.generic.VisionTowerArgs | None = None qlora_args: ~utils.generic.QLoRAArgs | None = None vision_tower_template_args: ~utils.generic.VisionTowerTemplateArgs | None = None video_tower_args: ~utils.generic.VideoTowerArgs | None = None vision_config: ~utils.generic.VisionConfig | None = None video_config: ~utils.generic.VideoConfig | None = None load_dataset: bool | None = None load_data_collator: bool | None = None load_processor: bool | None = None load_lora_adapter: bool | None = None load_adapter: bool | None = None load_qlora_adapter: bool | None = None **kwargs: typing_extensions.Unpack[transformers.modeling_utils.PreTrainedModelKwargs] )
参数
- config (TextNetForImageClassification) — 模型配置类,包含模型的所有参数。使用配置文件初始化不会加载与模型相关的权重,只会加载配置。请查看 from_pretrained() 方法来加载模型权重。
TextNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet.
此模型继承自 PreTrainedModel。查看其父类文档,了解库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头等)。
此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。
forward
< source >( pixel_values: torch.FloatTensor | None = None labels: torch.LongTensor | None = None output_hidden_states: bool | None = None return_dict: bool | None = None **kwargs ) → transformers.modeling_outputs.ImageClassifierOutputWithNoAttention or tuple(torch.FloatTensor)
参数
- pixel_values (
torch.FloatTensor,形状为(batch_size, num_channels, image_size, image_size), optional) — 对应于输入图像的张量。可以使用 TextNetImageProcessorFast 获取像素值。有关详细信息,请参阅 TextNetImageProcessorFast.call()(processor_class使用 TextNetImageProcessorFast 处理图像)。 - labels (
torch.LongTensor,形状为(batch_size,), optional) — 用于计算图像分类/回归损失的标签。索引应在[0, ..., config.num_labels - 1]之间。如果config.num_labels == 1,则计算回归损失(均方损失),如果config.num_labels > 1,则计算分类损失(交叉熵)。 - output_hidden_states (
bool, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量下的hidden_states。 - return_dict (
bool, optional) — 是否返回一个 ModelOutput 而不是一个普通元组。
返回
transformers.modeling_outputs.ImageClassifierOutputWithNoAttention or tuple(torch.FloatTensor)
A transformers.modeling_outputs.ImageClassifierOutputWithNoAttention or a tuple of torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration (TextNetConfig) and inputs.
- loss (形状为
(1,)的torch.FloatTensor,可选,当提供labels时返回) — 分类损失(如果 config.num_labels==1,则为回归损失)。 - logits (形状为
(batch_size, config.num_labels)的torch.FloatTensor) — 分类(如果 config.num_labels==1,则为回归)分数(SoftMax 之前)。 - hidden_states (
tuple(torch.FloatTensor), optional, 当传入output_hidden_states=True或config.output_hidden_states=True时返回) —torch.FloatTensor的元组(如果模型有嵌入层,则包含一个嵌入层输出,加上每阶段的一个输出),形状为(batch_size, num_channels, height, width)。模型在每个阶段输出的隐藏状态(也称为特征图)。
The TextNetForImageClassification forward method, overrides the __call__ special method.
虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用
Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> import torch
>>> import httpx
>>> from io import BytesIO
>>> from transformers import TextNetForImageClassification, TextNetImageProcessor
>>> from PIL import Image
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
... image = Image.open(BytesIO(response.read()))
>>> processor = TextNetImageProcessor.from_pretrained("czczup/textnet-base")
>>> model = TextNetForImageClassification.from_pretrained("czczup/textnet-base")
>>> inputs = processor(images=image, return_tensors="pt")
>>> with torch.no_grad():
... outputs = model(**inputs)
>>> outputs.logits.shape
torch.Size([1, 2])