结合keras功能api和张量流

时间:2018-06-01 22:19:36

标签: tensorflow keras

可以将张量流与keras序列模型结合起来,如下所示:(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)

但是,我想使用这样的功能API:

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

但是当我尝试这样做时,我得到了这些错误:

TypeError:模型的输入张量必须是Keras张量。找到:Tensor(“Placeholder_2:0”,shape =(?,784),dtype = float32)(缺少Keras元数据)。

2 个答案:

答案 0 :(得分:0)

您正在寻找的是功能API的Input layer tensor参数。

  

tensor:包含在Input图层中的可选现有张量。               如果设置,图层将不会创建占位符张量。

答案 1 :(得分:0)

功能和顺序api是创建模型对象的两种不同方式。但是一旦找到该对象,您就可以以相同的方式对待它们。例如,称它们为tensorflow对象。

在这里您可以找到documentation for the functional api

这是将tensorflow张量与功能性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)