Home > other >  How to call an input inside a method and use in Tensorflow
How to call an input inside a method and use in Tensorflow

Time:12-07

I would like to call a method that returns a set of input inside another method and use the current weights of my network to make a prediction. For simplicity, I am trying to just print the input for now.

import tensorflow as tf
import numpy as np

inputs = tf.keras.layers.Input( shape=(10,) )
x= tf.keras.layers.Flatten()(inputs)
x = tf.keras.layers.Dense(2)(inputs)
outputs = tf.keras.layers.Dense(1)(x)
model = tf.keras.Model(inputs, outputs)
model.compile(loss = "mse", 
              optimizer = tf.keras.optimizers.Adam(learning_rate=0.01) )

Suppose I have a method that returns a numpy array.

def firstMethod():
    return np.array([[1.32040024, -1.11483181, 1.01526141, 1.36170304, -0.872175455, 1.23767245, 0.696531296, 1.74229145, -1.10529709, -3.96802974]])

Now, I define another method that takes my model as a parameter and prints the array.

def secondMethod(model):
    tf.print(tf.convert_to_tensor(firstMethod, dtype = tf.float32))
    
secondMethod(model)    

I am receiving an error and was wondering how I can fix this issue.

ValueError: Attempt to convert a value (<function firstMethod at 0x0000019E0C44B4C0>) with an unsupported type (<class 'function'>) to a Tensor.

CodePudding user response:

You didn't call firstMethod(), you passed the function in as a parameter. Add the parentheses to call the function, and it should work. Also, secondMethod() doesn't actually use model. Maybe you meant to do something like this?

def secondMethod(model):
    tf.print(tf.convert_to_tensor(model(firstMethod()), dtype = tf.float32))
  • Related