我正在尝试协调来自 TF“图形和 session ”指南以及 TF“Keras”指南和 TF Estimators 指南的信息。现在在前者中它说 tf.Session 使计算图能够访问物理硬件以执行图和训练模型。就像关于学习 TF 的初始教程要求您使用 Session 来运行任何东西:变量指南、Tensors 指南等。但是,在 TF Keras 指南中,这些示例似乎在没有任何显式调用 tf 的情况下运行.Session 或通常的 with tf.Session() as sess: Keras 模型也没有使用急切执行。 Estimators API 也是如此。
我有几个代码示例。其中一些使用对 session 的调用,而另一些则不使用。我希望有人可以阐明将 tf.Session 与 Keras 层或 Estimator 一起使用的要求规则是什么。我的意思是,您似乎可以为 keras 估计器或标准 TF.estimator 设置诸如 run_configs 之类的东西,并为多 gpu 等设置设置。
这是函数式 API 的 TF Keras 指南中的示例。请注意,没有对 session 进行调用:
inputs = tf.keras.Input(shape=(32,)) # Returns a placeholder tensor
# A layer instance is callable on a tensor, and returns a tensor.
x = layers.Dense(64, activation='relu')(inputs)
x = layers.Dense(64, activation='relu')(x)
predictions = layers.Dense(10, activation='softmax')(x)
model = tf.keras.Model(inputs=inputs, outputs=predictions)
# The compile step specifies the training configuration.
model.compile(optimizer=tf.train.RMSPropOptimizer(0.001),
loss='categorical_crossentropy',
metrics=['accuracy'])
# Trains for 5 epochs
model.fit(data, labels, batch_size=32, epochs=100)
感谢您提供任何信息或说明。
请您参考如下方法:
仅使用 Keras 时,无需调用 tf.Session()。这是在使用tensorflow后端时调用的,可以看出here .这仅在使用 tensorflow 后端时调用,而不是 theano 或 CNTK。
关于通过 tf.Session() 调用使用 Tensorflow 接口(interface),对此进行了解释 here ,它只是使用 tf.Session() 作为 Keras 和 pure-TensorFlow 张量和/或函数之间的桥梁。
您可以看到一个使用 tf.Session() 和 Keras 的例子,使用 set_session() 后端函数:
session_conf = tf.ConfigProto(intra_op_parallelism_threads=1, inter_op_parallelism_threads=1)
from keras import backend as K
sess = tf.Session(graph=tf.get_default_graph(), config=session_conf)
K.set_session(sess)
