Table of Contents

Class TRIE<T>

Namespace
AiDotNet.Document.GraphBased
Assembly
AiDotNet.dll

TRIE (Text Reading and Information Extraction) for end-to-end document understanding.

public class TRIE<T> : DocumentNeuralNetworkBase<T>, INeuralNetworkModel<T>, INeuralNetwork<T>, IInterpretableModel<T>, IInputGradientComputable<T>, IDisposable, IFormUnderstanding<T>, ITextDetector<T>, IDocumentModel<T>, IFullModel<T, Tensor<T>, Tensor<T>>, IModel<Tensor<T>, Tensor<T>, ModelMetadata<T>>, IModelSerializer, ICheckpointableModel, IParameterizable<T, Tensor<T>, Tensor<T>>, IFeatureAware, IFeatureImportance<T>, ICloneable<IFullModel<T, Tensor<T>, Tensor<T>>>, IGradientComputable<T, Tensor<T>, Tensor<T>>, IJitCompilable<T>

Type Parameters

T

The numeric type used for calculations.

Inheritance
TRIE<T>
Implements
IFullModel<T, Tensor<T>, Tensor<T>>
IModel<Tensor<T>, Tensor<T>, ModelMetadata<T>>
IParameterizable<T, Tensor<T>, Tensor<T>>
ICloneable<IFullModel<T, Tensor<T>, Tensor<T>>>
IGradientComputable<T, Tensor<T>, Tensor<T>>
Inherited Members
Extension Methods

Remarks

TRIE combines text reading (OCR) with information extraction in an end-to-end framework, using graph neural networks to model relationships between text entities and extract structured information.

For Beginners: TRIE does reading and extraction together: 1. Reads text from document images 2. Builds a graph of text entities 3. Extracts key-value pairs and entities 4. Outputs structured information

Key features:

  • End-to-end text reading + extraction
  • Graph-based entity relationship modeling
  • Joint optimization of OCR and IE
  • Strong performance on receipts and forms

Example usage:

var model = new TRIE<float>(architecture);
var result = model.ExtractFormFields(documentImage);

Reference: "TRIE: End-to-End Text Reading and Information Extraction" (ACM MM 2020) https://arxiv.org/abs/2005.13118

Constructors

TRIE(NeuralNetworkArchitecture<T>, int, int, int, int, int, int, IOptimizer<T, Tensor<T>, Tensor<T>>?, ILossFunction<T>?)

Creates a TRIE model using native layers for training and inference.

public TRIE(NeuralNetworkArchitecture<T> architecture, int imageSize = 512, int visualDim = 256, int textDim = 256, int graphDim = 256, int numEntityTypes = 10, int maxEntities = 100, IOptimizer<T, Tensor<T>, Tensor<T>>? optimizer = null, ILossFunction<T>? lossFunction = null)

Parameters

architecture NeuralNetworkArchitecture<T>
imageSize int
visualDim int
textDim int
graphDim int
numEntityTypes int
maxEntities int
optimizer IOptimizer<T, Tensor<T>, Tensor<T>>
lossFunction ILossFunction<T>

Remarks

Default Configuration (TRIE from ACM MM 2020): - Visual encoder: ResNet backbone - Text encoder: BiLSTM - Graph reasoning module - Multi-task extraction heads

TRIE(NeuralNetworkArchitecture<T>, string, int, int, int, int, int, int, IOptimizer<T, Tensor<T>, Tensor<T>>?, ILossFunction<T>?)

Creates a TRIE model using a pre-trained ONNX model for inference.

public TRIE(NeuralNetworkArchitecture<T> architecture, string onnxModelPath, int imageSize = 512, int visualDim = 256, int textDim = 256, int graphDim = 256, int numEntityTypes = 10, int maxEntities = 100, IOptimizer<T, Tensor<T>, Tensor<T>>? optimizer = null, ILossFunction<T>? lossFunction = null)

Parameters

architecture NeuralNetworkArchitecture<T>
onnxModelPath string
imageSize int
visualDim int
textDim int
graphDim int
numEntityTypes int
maxEntities int
optimizer IOptimizer<T, Tensor<T>, Tensor<T>>
lossFunction ILossFunction<T>

Properties

ExpectedImageSize

Gets the expected input image size (assumes square images).

public int ExpectedImageSize { get; }

Property Value

int

Remarks

Common values: 224 (ViT base), 384, 448, 512, 768, 1024. Input images will be resized to [ImageSize x ImageSize] before processing.

MinTextHeight

Gets the minimum detectable text height in pixels.

public int MinTextHeight { get; }

Property Value

int

NumEntityTypes

Gets the number of entity types.

public int NumEntityTypes { get; }

Property Value

int

RequiresOCR

Gets whether this model requires OCR preprocessing.

public override bool RequiresOCR { get; }

Property Value

bool

Remarks

Layout-aware models (LayoutLM, etc.) require OCR to provide text and bounding boxes. OCR-free models (Donut, Pix2Struct) process raw pixels directly.

SupportedDocumentTypes

Gets the supported document types for this model.

public override DocumentType SupportedDocumentTypes { get; }

Property Value

DocumentType

SupportsPolygonOutput

Gets whether this detector outputs polygon bounding boxes (vs axis-aligned rectangles).

public bool SupportsPolygonOutput { get; }

Property Value

bool

SupportsRotatedText

Gets whether this detector supports rotated text detection.

public bool SupportsRotatedText { get; }

Property Value

bool

Methods

ApplyDefaultPostprocessing(Tensor<T>)

Applies TRIE's industry-standard postprocessing: pass-through (entity extraction outputs are already final).

protected override Tensor<T> ApplyDefaultPostprocessing(Tensor<T> modelOutput)

Parameters

modelOutput Tensor<T>

Returns

Tensor<T>

ApplyDefaultPreprocessing(Tensor<T>)

Applies TRIE's industry-standard preprocessing: ImageNet normalization.

protected override Tensor<T> ApplyDefaultPreprocessing(Tensor<T> rawImage)

Parameters

rawImage Tensor<T>

Returns

Tensor<T>

Remarks

TRIE (Text Reading in-the-wild for Extraction) uses ImageNet normalization with mean=[0.485, 0.456, 0.406] and std=[0.229, 0.224, 0.225].

CreateNewInstance()

Creates a new instance of the same type as this neural network.

protected override IFullModel<T, Tensor<T>, Tensor<T>> CreateNewInstance()

Returns

IFullModel<T, Tensor<T>, Tensor<T>>

A new instance of the same neural network type.

Remarks

For Beginners: This creates a blank version of the same type of neural network.

It's used internally by methods like DeepCopy and Clone to create the right type of network before copying the data into it.

DeserializeNetworkSpecificData(BinaryReader)

Deserializes network-specific data that was not covered by the general deserialization process.

protected override void DeserializeNetworkSpecificData(BinaryReader reader)

Parameters

reader BinaryReader

The BinaryReader to read the data from.

Remarks

This method is called at the end of the general deserialization process to allow derived classes to read any additional data specific to their implementation.

For Beginners: Continuing the suitcase analogy, this is like unpacking that special compartment. After the main deserialization method has unpacked the common items (layers, parameters), this method allows each specific type of neural network to unpack its own unique items that were stored during serialization.

DetectCheckboxes(Tensor<T>)

Detects checkboxes and their states in a document.

public IEnumerable<CheckboxResult<T>> DetectCheckboxes(Tensor<T> documentImage)

Parameters

documentImage Tensor<T>

The document image tensor.

Returns

IEnumerable<CheckboxResult<T>>

Collection of detected checkboxes.

DetectSignatures(Tensor<T>)

Detects signatures in a document.

public IEnumerable<SignatureResult<T>> DetectSignatures(Tensor<T> documentImage)

Parameters

documentImage Tensor<T>

The document image tensor.

Returns

IEnumerable<SignatureResult<T>>

Collection of detected signatures.

DetectText(Tensor<T>)

Detects text regions in an image.

public TextDetectionResult<T> DetectText(Tensor<T> documentImage)

Parameters

documentImage Tensor<T>

Returns

TextDetectionResult<T>

Detection result with text region locations.

DetectText(Tensor<T>, double)

Detects text regions with a custom confidence threshold.

public TextDetectionResult<T> DetectText(Tensor<T> documentImage, double confidenceThreshold)

Parameters

documentImage Tensor<T>
confidenceThreshold double

Minimum confidence for a detection (0-1).

Returns

TextDetectionResult<T>

Detection result with text region locations.

DetectTextBatch(IEnumerable<Tensor<T>>)

public IEnumerable<TextDetectionResult<T>> DetectTextBatch(IEnumerable<Tensor<T>> documentImages)

Parameters

documentImages IEnumerable<Tensor<T>>

Returns

IEnumerable<TextDetectionResult<T>>

Dispose(bool)

Disposes of resources used by this model.

protected override void Dispose(bool disposing)

Parameters

disposing bool

True if disposing managed resources.

EncodeDocument(Tensor<T>)

Processes a document image and returns encoded features.

public Tensor<T> EncodeDocument(Tensor<T> documentImage)

Parameters

documentImage Tensor<T>

The document image tensor [batch, channels, height, width] or [channels, height, width].

Returns

Tensor<T>

Encoded document features suitable for downstream tasks.

Remarks

For Beginners: This method converts a document image into a numerical representation (feature vector) that captures the document's content and structure. These features can then be used for tasks like classification, QA, or information extraction.

ExtractFormFields(Tensor<T>)

Extracts form fields from a document image.

public FormFieldResult<T> ExtractFormFields(Tensor<T> documentImage)

Parameters

documentImage Tensor<T>

The document image tensor.

Returns

FormFieldResult<T>

Form field extraction result.

ExtractFormFields(Tensor<T>, double)

Extracts form fields with a custom confidence threshold.

public FormFieldResult<T> ExtractFormFields(Tensor<T> documentImage, double confidenceThreshold)

Parameters

documentImage Tensor<T>

The document image tensor.

confidenceThreshold double

Minimum confidence for field extraction (0-1).

Returns

FormFieldResult<T>

Form field extraction result.

ExtractKeyValuePairs(Tensor<T>)

Extracts key-value pairs from a document.

public Dictionary<string, string> ExtractKeyValuePairs(Tensor<T> documentImage)

Parameters

documentImage Tensor<T>

The document image tensor.

Returns

Dictionary<string, string>

Dictionary of field names to values.

GetHeatmap()

public Tensor<T> GetHeatmap()

Returns

Tensor<T>

GetModelMetadata()

Gets the metadata for this neural network model.

public override ModelMetadata<T> GetModelMetadata()

Returns

ModelMetadata<T>

A ModelMetaData object containing information about the model.

GetModelSummary()

Gets a summary of the model architecture.

public string GetModelSummary()

Returns

string

A string describing the model's architecture, parameters, and capabilities.

GetProbabilityMap(Tensor<T>)

Gets the probability map showing text likelihood at each pixel.

public Tensor<T> GetProbabilityMap(Tensor<T> image)

Parameters

image Tensor<T>

The input image tensor.

Returns

Tensor<T>

Probability map tensor with same spatial dimensions as input.

InitializeLayers()

Initializes the layers of the neural network based on the architecture.

protected override void InitializeLayers()

Remarks

For Beginners: This method sets up all the layers in your neural network according to the architecture you've defined. It's like assembling the parts of your network before you can use it.

Predict(Tensor<T>)

Makes a prediction using the neural network.

public override Tensor<T> Predict(Tensor<T> input)

Parameters

input Tensor<T>

The input data to process.

Returns

Tensor<T>

The network's prediction.

Remarks

For Beginners: This is the main method you'll use to get results from your trained neural network. You provide some input data (like an image or text), and the network processes it through all its layers to produce an output (like a classification or prediction).

SerializeNetworkSpecificData(BinaryWriter)

Serializes network-specific data that is not covered by the general serialization process.

protected override void SerializeNetworkSpecificData(BinaryWriter writer)

Parameters

writer BinaryWriter

The BinaryWriter to write the data to.

Remarks

This method is called at the end of the general serialization process to allow derived classes to write any additional data specific to their implementation.

For Beginners: Think of this as packing a special compartment in your suitcase. While the main serialization method packs the common items (layers, parameters), this method allows each specific type of neural network to pack its own unique items that other networks might not have.

Train(Tensor<T>, Tensor<T>)

Trains the neural network on a single input-output pair.

public override void Train(Tensor<T> input, Tensor<T> expectedOutput)

Parameters

input Tensor<T>

The input data.

expectedOutput Tensor<T>

The expected output for the given input.

Remarks

This method performs one training step on the neural network using the provided input and expected output. It updates the network's parameters to reduce the error between the network's prediction and the expected output.

For Beginners: This is how your neural network learns. You provide: - An input (what the network should process) - The expected output (what the correct answer should be)

The network then:

  1. Makes a prediction based on the input
  2. Compares its prediction to the expected output
  3. Calculates how wrong it was (the loss)
  4. Adjusts its internal values to do better next time

After training, you can get the loss value using the GetLastLoss() method to see how well the network is learning.

UpdateParameters(Vector<T>)

Updates the network's parameters with new values.

public override void UpdateParameters(Vector<T> gradients)

Parameters

gradients Vector<T>

Remarks

For Beginners: During training, a neural network's internal values (parameters) get adjusted to improve its performance. This method allows you to update all those values at once by providing a complete set of new parameters.

This is typically used by optimization algorithms that calculate better parameter values based on training data.

ValidateInputShape(Tensor<T>)

Validates that an input tensor has the correct shape for this model.

public void ValidateInputShape(Tensor<T> documentImage)

Parameters

documentImage Tensor<T>

The tensor to validate.

Exceptions

ArgumentException

Thrown if the tensor shape is invalid.