我用来加载模型的代码:
graph1 = tf.get_default_graph()
with graph1.as_default():
with tf.Session(graph=graph1) as sess:
tf.saved_model.loader.load(sess,[tag_constants.SERVING],'/mnist/mnist_saved_model/')
x = graph1.get_tensor_by_name("x:0")
y = graph1.get_tensor_by_name("y:0")
keep_prob = graph1.get_tensor_by_name("keep_prob:0")
aug_img = graph1.get_tensor_by_name("aug_img:0")
logits = graph1.get_tensor_by_name("logits/BiasAdd:0")
feats = sess.run(logits,feed_dict={x:img,keep_prob:1.0})
print feats
当从sess.run
块中调用时, with tf.Session(graph=graph1) as sess
执行得很好
但是当使用Jupyter Notebook时,当我尝试在上述代码下方的另一个单元格中的另一个图像上分别执行sess.run
时:
with tf.Session(graph=graph1) as sess:
feats = sess.run(logits,feed_dict={x:img,keep_prob:1.0})
然后我遇到了错误
FailedPreconditionError: Attempting to use uninitialized value conv2/kernel
为什么除了第一段代码外,我无法在其他地方执行sess.run
?
如何加载模型并从代码中的任何位置调用它?
答案 0 :(得分:1)
这样做:
public class RouletteSelectionFunction : ISelectionFunction
{
public string Name => "Roulette";
public T Select<T, P>( IEnumerable<T> elements, Expression<Func<T, P>> property )
where T : class
{
var prop = ( PropertyInfo ) ( ( MemberExpression ) property.Body ).Member;
// Sum all fitnesses and normalize negatives
// by shifting range to minimum of 0
double sum = 0.0;
double lowest = 0.0;
for ( var i = 0; i < elements.Count(); i++ )
{
var value = prop.GetValue( elements.ElementAt( i ) );
sum += value;
if ( value < lowest )
lowest = value;
}
lowest = Math.Abs( lowest );
sum += lowest * elements.Count();
// Roll roulette and select victor
double rouletteSum = 0;
double random = RandomGen.NextDouble() * sum; //RandomGen wraps Random() class and NextDouble() returns number between 0 and 1
for( var i = 0; i < elements.Count(); i++ )
{
rouletteSum += prop.GetValue( elements.ElementAt( i ) );
if ( random <= rouletteSum )
return elements.ElementAt( i );
}
throw new SelectionFailedException( "Roulette Selection could not determine victor" );
}
}
// Call via:
// RouletteSelectionFunction.Select( elements, x => x.Score )
然后仅运行以下行:
graph1 = tf.get_default_graph()
sess = tf.Session(graph=graph1)
with graph1.as_default():
tf.saved_model.loader.load(sess,[tag_constants.SERVING],'/mnist/mnist_saved_model/')
x = graph1.get_tensor_by_name("x:0")
y = graph1.get_tensor_by_name("y:0")
keep_prob = graph1.get_tensor_by_name("keep_prob:0")
aug_img = graph1.get_tensor_by_name("aug_img:0")
logits = graph1.get_tensor_by_name("logits/BiasAdd:0")
feats = sess.run(logits,feed_dict={x:img,keep_prob:1.0})
print feats
无需再次执行feats = sess.run(logits,feed_dict={x:img,keep_prob:1.0})
print feats