tensorflow随笔-新的计算图
生活随笔
收集整理的這篇文章主要介紹了
tensorflow随笔-新的计算图
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
生成新的計算圖,并完成常量初始化,在新的計算 圖中完成加法計算
import tensorflow as tfg1=tf.Graph()with g1.as_default():value=[1.,2.,3.,4.,5.,6.]init = tf.constant_initializer(value)x=tf.get_variable("x",initializer=init,shape=[2,3])y=tf.get_variable("y",shape=[2,3],initializer=tf.ones_initializer())result=tf.add(x,y,name="myadd")with tf.Session(graph=g1) as sess:tf.global_variables_initializer().run()with tf.variable_scope("",reuse=True):print(sess.run(tf.get_variable("x")))print(sess.run(tf.get_variable("y")))print(sess.run(result))A)tf.Graph.as_default()會創(chuàng)建一個新圖,這個圖成為當前線程的默認圖。
B)在相同進程中創(chuàng)建多個計算圖使用tf.Graph.as_default()。如果不創(chuàng)建新的計算圖,默認的計算圖將被自動創(chuàng)建。
C)如果創(chuàng)建一個新線程,想使用該線程的默認計算圖,使用tf.Graph.as_default(),這個函數(shù)返回一個上下文管理器( context manager),它能夠在這個上下文里面覆蓋默認的計算圖。在代碼務(wù)必使用with。
# -*- coding: utf-8 -*-"""Spyder Editor生成新的計算圖,并完成常量初始化[代碼1]myhaspl@myhaspl.com"""import tensorflow as tfg = tf.Graph()with g.as_default():c = tf.constant(5.0)assert c.graph is gprint "ok"[代碼2]
# -*- coding: utf-8 -*-"""Spyder Editor生成新的計算圖,并完成常量初始化myhaspl@myhaspl.com"""import tensorflow as tfwith tf.Graph().as_default() as g:c = tf.constant(5.0)assert c.graph is gprint "ok" [代碼3]# -*- coding: utf-8 -*-"""Spyder Editor生成新的計算圖,并完成常量初始化myhaspl@myhaspl.com4"""import tensorflow as tfwith tf.Graph().as_default() as g:c = tf.constant(5.0)assert c.graph is gprint "ok"sess=tf.Session(graph=g)print sess.run(c)sess.close()[代碼4]
# -*- coding: utf-8 -*-"""Spyder Editor生成新的計算圖,并完成常量初始化myhaspl@myhaspl.com"""import tensorflow as tfg=tf.get_default_graph()#默認計算圖會自動注冊c = tf.constant(4.0)result=c*cassert result.graph is g#驗證是否result操作屬于g這個計算圖print "ok1"with tf.Graph().as_default() as g1:c = tf.constant(5.0)assert c.graph is g1print "ok2"assert c.graph is gprint "ok3"sess=tf.Session(graph=g1)print sess.run(c)sess.close() 運行:輸出驗證失敗
ok1
ok2
…
assert c.graph is g
AssertionError
…
[代碼5]
# -*- coding: utf-8 -*-"""Spyder Editor生成新的計算圖,并完成常量初始化,在新的計算 圖中完成加法計算myhaspl@myhaspl.com"""import tensorflow as tfg1=tf.Graph()with g1.as_default():value=[1.,2.,3.,4.,5.,6.]init = tf.constant_initializer(value)x=tf.get_variable("x",initializer=init,shape=[2,3])y=tf.get_variable("y",shape=[2,3],initializer=tf.ones_initializer())result=tf.add(x,y,name="myadd")assert result.graph is g1#驗證是否result操作屬于g1這個計算圖print "ok"with tf.Session(graph=g1) as sess:tf.global_variables_initializer().run()with tf.variable_scope("",reuse=True):print(sess.run(tf.get_variable("x")))print(sess.run(tf.get_variable("y")))print(sess.run(result))總結(jié)
以上是生活随笔為你收集整理的tensorflow随笔-新的计算图的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux如何挂载nfs目录,linux
- 下一篇: linux下利用nohup后台运行jar