Home > Software design >  Pydantic: Type hinting tensorflow tensor
Pydantic: Type hinting tensorflow tensor

Time:05-10

any idea of how to type-hint tf tensors using pydantic??. Tried default tf.Tensor

RuntimeError: no validator found for <class 'tensorflow.python.framework.ops.Tensor'>, see `arbitrary_types_allowed` in Config

and tf.flaot32

RuntimeError: error checking inheritance of tf.float32 (type: DType)

Looking at documentation in pydantic, i believe something like this arbitrary class need to be defined...

class Tensor:
    def __init__(self, Tensor):

        self.Tensor = Union[
            tensorflow.python.framework.ops.Tensor,
            tensorflow.python.framework.sparse_tensor.SparseTensor,
            tensorflow.python.ops.ragged.ragged_tensor.RaggedTensor,
            tensorflow.python.framework.ops.EagerTensor,
        ]

with following in main..

 class Main(BaseModel):
     tensor : Tensor


 class Config:
    arbitary_types_allowed = True

CodePudding user response:

I would try this as a minimal example:

from pydantic import BaseModel
import tensorflow as tf


class MyTensor(BaseModel):

    tensor: tf.Tensor

    class Config:
        arbitrary_types_allowed = True

Note that the Config class is actually a subclass inside MyTensor.

CodePudding user response:

working code:

from pydantic import BaseModel
import tensorflow as tf


class MyTensor(BaseModel):

    tensor: tf.Variable

    class Config:
        arbitrary_types_allowed = True
  • Related