我想还原模型而无需手动构建图形。我只想将预测变量用于新数据样本。
所以我发现这是通常的方式:
model_path = "my_saved_model"
inference_graph = tf.Graph()
with tf.Session(graph= inference_graph) as sess:
# Load the graph with the trained states
loader = tf.train.import_meta_graph(model_path+'.meta')
loader.restore(sess, model_path)
获取tnesors(这是我的问题)
pred = inference_graph.get_tensor_by_name('predictions?:0')
_x = inference_graph get_tensor_by_name('x1:0')
_y = inference_graph.get_tensor_by_name('x2:0')
然后执行sess.run(_accuracy,feed_dict = {_ x:...,_y:...}
因此,您需要从模型(从元文件)中获得所需结果的名称
但是我不知道我的预测用哪个名字。这是我的模型:
self.x1 = tf.placeholder(dtype=tf.int32, shape=[None, max_sequence_len],name="x1")
self.x2 = tf.placeholder(dtype=tf.int32, shape=[None, max_sequence_len],name="x2")
self.is_training = tf.placeholder(dtype=tf.bool)
self.labels = tf.placeholder(dtype=tf.int32, shape=[None, 1])
self.sentences_lengths = tf.placeholder(dtype=tf.int32, shape=[None])
self.debug = None
self.embedding_size = main_cfg['PARAMS'].getint('embedding_size')
self.learning_rate = main_cfg['TRAINING'].getfloat('learning_rate')
self.embedding_mat=embedding_mat
with tf.variable_scope('embeddings'):
word_embeddings = tf.constant(self.embedding_mat, dtype=tf.float32, name="embedding")
self.embedded_x1 = tf.nn.embedding_lookup(word_embeddings, self.x1)
self.embedded_x2 = tf.nn.embedding_lookup(word_embeddings, self.x2)
# word_embeddings = tf.get_variable('word_embeddings', [vocabulary_size, self.embedding_size])
#self.embedded_x1 = tf.gather(word_embeddings, self.x1)
#self.embedded_x2 = tf.gather(word_embeddings, self.x2)
with tf.variable_scope('siamese'):
self.predictions = self.siamese_layer(max_sequence_len, model_cfg)
with tf.variable_scope('loss'):
self.loss = loss_function(self.labels, self.predictions)
self.opt = optimize(self.loss, self.learning_rate)
with tf.variable_scope('metrics'):
self.temp_sim = tf.rint(self.predictions)
self.correct_predictions = tf.equal(self.temp_sim, tf.to_float(self.labels))
self.accuracy = tf.reduce_mean(tf.to_float(self.correct_predictions))
with tf.variable_scope('summary'):
tf.summary.scalar("loss", self.loss)
tf.summary.scalar("accuracy", self.accuracy)
self.summary_op = tf.summary.merge_all()
def siamese_layer(self, sequence_len, model_cfg):
num_filters = parse_list(model_cfg['PARAMS']['num_filters'])
filter_sizes = parse_list(model_cfg['PARAMS']['filter_sizes'])
# print(self.embedded_x1)
embedded_x1=self.embedded_x1
out1 = cnn_layers(self.embedded_x1,
sequence_len,
num_filters=num_filters,
filter_sizes=filter_sizes)
out2 = cnn_layers(self.embedded_x2,
sequence_len,
num_filters=num_filters,
filter_sizes=filter_sizes,
reuse=True)
out1 = dropout(out1, self.is_training)
out2 = dropout(out2, self.is_training)
return manhattan_similarity(out1, out2)
因此,对于新的预测,我只需要输入两个名称分别为x1和x2的sel.prediction即可。但是如何从上面的代码示例中按名称来命名呢?