lab_rat
lab_rat

Reputation: 117

Combine keras functional api with tensorflow

It's possible to combine tensorflow with keras sequential models like this: (source)

from keras.models import Sequential, Model

model = Sequential()
model.add(Dense(32, activation='relu', input_dim=784))
model.add(Dense(10, activation='softmax'))

# this works! 
x = tf.placeholder(tf.float32, shape=(None, 784))
y = model(x)

However, I want to use the functional API like this:

x = tf.placeholder(tf.float32, shape=(None, 784))
y = Dense(10)(x)
model = Model(inputs=x, outputs=y)

but when I try to do this, I get these errors:

TypeError: Input tensors to a Model must be Keras tensors. Found: Tensor("Placeholder_2:0", shape=(?, 784), dtype=float32) (missing Keras metadata).

Upvotes: 1

Views: 1414

Answers (2)

Emil Johansson
Emil Johansson

Reputation: 321

The functional and seqential apis are two different ways to create a model object. But once that object you can treat them the same way. For example calling them whith tensorflow objects.

Here you can find documentation for the functional api

Here is a minimal example of using tensorflow tensors with the functional api.

import tensorflow as tf
from keras.layers import Input, Dense
from keras.models import Model

# Create the keras model.
inputs = Input(shape=(784,))
outputs = Dense(10)(inputs)
model = Model(inputs=inputs, outputs=outputs)

# Now that we have a model we can call it with x.
x = tf.placeholder(tf.float32, shape=(None, 784))
y = model(x)

Upvotes: 1

nuric
nuric

Reputation: 11225

What you are looking for is the tensor argument of Input layer for the functional API.

tensor: Optional existing tensor to wrap into the Input layer. If set, the layer will not create a placeholder tensor.

Upvotes: 0

Related Questions