tensorflow-多计算图多session


#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Thu Sep  6 10:16:37 2018
@author: myhaspl
@email:[email protected]
"""

import tensorflow as tf
g1=tf.Graph()
g2=tf.Graph()

with g1.as_default():
    with tf.name_scope("Scope_A"):
        asub=tf.subtract(1,2,name="A_sub")
        amul=tf.multiply(asub,3,name="B_mul")

    with tf.name_scope("Scope_B"): 
        badd=tf.add(5,3,name="B_add")
        bmul=tf.multiply(badd,3,name="B_div")
    g1res=tf.add(amul,bmul,name="g1result")

with g2.as_default():
    with tf.name_scope("Scope_C"):
        a=tf.placeholder(tf.float32,shape=(),name="input_a")
        b=tf.placeholder(tf.float32,shape=(),name="input_b")
        c=tf.add(a,b)
    g2res=tf.pow(c,2,name="g2result")

with tf.Session(graph=g1) as sess1:  
    print sess1.run(g1res)  
with tf.Session(graph=g2) as sess2:  
    print sess2.run(g2res,feed_dict={a:12,b:22})

#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Thu Sep  6 10:16:37 2018
@author: myhaspl
@email:[email protected]
"""

import tensorflow as tf
g1=tf.Graph()

with g1.as_default():
    y=tf.Variable(0.)
    with tf.name_scope("Scope_C"):

        a=tf.placeholder(tf.float32,shape=(),name="input_a")
        b=tf.placeholder(tf.float32,shape=(),name="input_b")
        with tf.name_scope("Scope_A"):
            asub=tf.subtract(a,b,name="A_sub")
            amul=tf.multiply(asub,3,name="B_mul")

        with tf.name_scope("Scope_B"): 
            badd=tf.add(a,b,name="B_add")
            bmul=tf.multiply(badd,3,name="B_div")
    g1res=tf.add(amul,bmul,name="g1result")
    result=y.assign(y+g1res)

    init=tf.initialize_all_variables()
with tf.Session(graph=g1) as sess1:  
    sess1.run(init)
    print sess1.run(result,feed_dict={a:28,b:9})  
with tf.Session(graph=g1) as sess2:  
    sess2.run(init)
    print sess2.run(result,feed_dict={a:12,b:22})

多个session都独立地对y进行操作

上面程序输出为:

168.0
72.0

猜你喜欢

转载自blog.51cto.com/13959448/2324221
今日推荐