使用Tensorflow 1.3.1
我已经创建了一个神经网络并对其进行了训练,现在我想使用tf.saved_model.simple_save(sess, export_dir, inputs, outputs)
保存它,以便可以使用它进行预测。因此,我需要找到模型的'inputs'变量。
我的模型定义如下:
def __call__(self, obs, reuse=False):
with tf.variable_scope(self.name) as scope:
if reuse:
scope.reuse_variables()
x = obs
x = tf.layers.dense(x, self.nb_units)
if self.layer_norm:
x = tc.layers.layer_norm(x, center=True, scale=True)
x = tf.nn.relu(x)
x = tf.layers.dense(x, self.nb_units)
if self.layer_norm:
x = tc.layers.layer_norm(x, center=True, scale=True)
x = tf.nn.relu(x)
x = tf.layers.dense(x, self.nb_actions,
kernel_initializer=tf.random_uniform_initializer(minval=-3e-3, maxval=3e-3))
x = tf.nn.tanh(x)
return x
当我查看范围内的变量时(使用):
for i in tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='actor'):
print(i.name + ':\t', end=''); print(i)
我得到:
actor/dense/kernel:0: <tf.Variable 'actor/dense/kernel:0' shape=(270, 512) dtype=float32_ref>
actor/dense/bias:0: <tf.Variable 'actor/dense/bias:0' shape=(512,) dtype=float32_ref>
actor/LayerNorm/beta:0: <tf.Variable 'actor/LayerNorm/beta:0' shape=(512,) dtype=float32_ref>
actor/LayerNorm/gamma:0: <tf.Variable 'actor/LayerNorm/gamma:0' shape=(512,) dtype=float32_ref>
actor/dense_1/kernel:0: <tf.Variable 'actor/dense_1/kernel:0' shape=(512, 512) dtype=float32_ref>
actor/dense_1/bias:0: <tf.Variable 'actor/dense_1/bias:0' shape=(512,) dtype=float32_ref>
actor/LayerNorm_1/beta:0: <tf.Variable 'actor/LayerNorm_1/beta:0' shape=(512,) dtype=float32_ref>
actor/LayerNorm_1/gamma:0: <tf.Variable 'actor/LayerNorm_1/gamma:0' shape=(512,) dtype=float32_ref>
actor/dense_2/kernel:0: <tf.Variable 'actor/dense_2/kernel:0' shape=(512, 10) dtype=float32_ref>
actor/dense_2/bias:0: <tf.Variable 'actor/dense_2/bias:0' shape=(10,) dtype=float32_ref>
我尝试保存它
x = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='actor/dense/kernel:0')[0]
y = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='actor/dense_2/bias:0')[0]
tf.saved_model.simple_save(sess, model_save_name, inputs={"state": x}, outputs={"action": y})
然后用
加载predict_fn = predictor.from_saved_model(load_dir)
predictions = predict_fn({"state": np.zeros(270)})
但是我得到了错误
ValueError: Cannot feed value of shape (270,) for Tensor 'actor/dense/kernel:0', which has shape '(270, 512)'
我尚未为输入数据定义占位符。这是否意味着我无法保存然后通过simple_save
方法加载它?
答案 0 :(得分:1)
除非我弄错了,否则这不是您在predictions = predict_fn({"state": np.zeros(270)})
中使用模型的方式。
首先,您需要构建模型:这包括每个图层的类型和形状,还包括输入图层(占位符)
然后,您可以通过喂入占位符来进行训练/预测。
在您的示例中,我觉得您每次调用模型时都会重新构建模型。
但是我认为您的错误来自grepl("^[[:alnum:]]+_[[:digit:]]+_[[:digit:]]+\\.{0,1}[[:digit:]]+$", "lkas32kj_123_3.21")
。您正在为模型提供一个numpy数组,但是您的模型没有用于放入数据的占位符。