In Keras 作为 TensorFlow 的简化接口:教程他们描述了如何在 TensorFlow 张量上调用 Keras 模型。
from keras.models import Sequential
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)
他们还说:
注意:通过调用 Keras 模型,您可以重用其架构和权重。当您在张量上调用模型时,您将在输入张量之上创建新的 TF 操作,并且这些操作将重用模型中已存在的 TF 变量实例。
我将其解释为模型的权重在y
如模型中所示。然而,对我来说,生成的 Tensorflow 节点中的权重似乎已重新初始化。下面是一个最小的例子:
import numpy as np
from keras.models import Sequential
from keras.layers import Dense
# Create model with weight initialized to 1
model = Sequential()
model.add(Dense(1, input_dim=1, kernel_initializer='ones',
bias_initializer='zeros'))
model.compile(loss='binary_crossentropy', optimizer='adam',
metrics=['accuracy'])
# Save the weights
model.save_weights('file')
# Create another identical model except with weight initialized to 0
model2 = Sequential()
model2.add(Dense(1, input_dim=1, kernel_initializer='zeros',
bias_initializer='zeros'))
model2.compile(loss='binary_crossentropy', optimizer='adam',
metrics=['accuracy'])
# Load the weight from the first model
model2.load_weights('file')
# Call model with Tensorflow tensor
v = tf.Variable([[1, ], ], dtype=tf.float32)
node = model2(v)
sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)
print(sess.run(node), model2.predict(np.array([[1, ], ])))
# Prints (array([[ 0.]], dtype=float32), array([[ 1.]], dtype=float32))
为什么我要这样做:
我想在另一个最小化方案中使用经过训练的网络,网络“惩罚”搜索空间中不允许的位置。因此,如果您有不涉及这种特定方法的想法,我们也非常感激。