【发布时间】:2020-01-12 19:15:23
【问题描述】:
我有一个带有占位符操作作为输入的张量流图(存储在一个 protobuffer 文件中)。我想将此图包装为 keras 层或模型。
这是一个例子:
with tf.Graph().as_default() as gf:
x = tf.placeholder(tf.float32, shape=(None, 123), name='x')
c = tf.constant(100, dtype=tf.float32, name='C')
y = tf.multiply(x, c, name='y')
with tf.gfile.GFile("test_graph/y.pb", "wb") as f:
raw = gf.as_graph_def().SerializeToString()
f.write(raw)
加载回张量流图:
persisted_sess = tf.Session()
with persisted_sess.as_default():
with gfile.FastGFile("./test_graph/y.pb",'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
persisted_sess.graph.as_default()
tf.import_graph_def(graph_def, name='')
for i, op in enumerate(persisted_sess.graph.get_operations()):
tensor = persisted_sess.graph.get_tensor_by_name(op.name + ':0')
print(i, '\t', op.name, op.type, tensor)
x_tensor = persisted_sess.graph.get_tensor_by_name('x:0')
y_tensor = persisted_sess.graph.get_tensor_by_name('y:0')
我们可以看到x 和y 操作和张量:
0 x Placeholder Tensor("x:0", shape=(?, 123), dtype=float32)
1 C Const Tensor("C:0", shape=(), dtype=float32)
2 y Mul Tensor("y:0", shape=(?, 123), dtype=float32)
然后我尝试使用不同的方法将其包装到 keras 模型中:
方法一:
output_layer = Lambda(lambda x: y_tensor, name='output_y')(x_tensor)
model = Model(inputs=[x_tensor], outputs=[output_layer]) # ERROR!
这已经产生错误InvalidArgumentError: You must feed a value for placeholder tensor 'x' with dtype float and shape [?,123] [[{{node x}}]]
方法二:
input_x = Input(name='x', shape=(123,), dtype='float32')
output_layer = Lambda(lambda x: y_tensor, name='output_y')(input_x)
model = Model(inputs=[input_x], outputs=[output_layer]) # OK
model.predict({'x': np.ones((3, 123), dtype=np.float32)}) # ERROR!
这会在predict 调用中导致同样的错误。
我能找到的与我的问题相关的最接近的信息是this,但它没有解决占位符的处理问题。这样做的正确方法是什么?
【问题讨论】:
标签: tensorflow keras tf.keras