python學習日記8 tensor operator 圖
#試用區分tensor和operator,操作圖
import tensorflow as tf
import numpy as np
tf.reset_default_graph()
c=tf.constant(0.0)
print('cgraph: ',c.graph)
g=tf.Graph()
with g.as_default():
c1=tf.constant(0.0)
print('c1: ',c1)
print('c1graph: ',c1.graph)
print('g: ',g)
g2=tf.get_default_graph()
print('g2: ',g2)
tf.reset_default_graph()
g3=tf.get_default_graph()
print('g3: ',g3)
print('c1 name: ',c1.name)
t= g.get_tensor_by_name(name = “Const:0”)
print('t(if=c1 or not): ',t)
print('tgraph: ',t.graph)
a=tf.constant([[1.0,2.0]])
b=tf.constant([[1.0],[3.0]])
tensor1=tf.matmul(a,b,name=‘example_op’)
print('tensor1: ',
print('tensor1.op.name: ',tensor1.op.name)
test_tensor=g3.get_tensor_by_name(‘example_op:0’)
print('test_tensor: ',test_tensor)
print('test_tensor.op.name: ',test_tensor.op.name)
test_op=g3.get_operation_by_name(“example_op”)
#print('test_op: ',test_op)
with tf.Session() as sess:
test=sess.run(test_tensor)
print('test(sess.run): ',test)
test = tf.get_default_graph().get_tensor_by_name(
“example_op:0”)
print('test(get tensor by name): ',test)
tt=g.get_operations()
print('tt(graph g): ',tt)
tt2=g3.get_operations()
print('tt2(graph g3): ',tt2)
tt3=g.as_graph_element(c1)
print('tt3(graph g c1): ',tt3)
附加
#本程式做tf.Variable和tf.get_Variable的對比
#tf.Variable每次生成新的var,並在名字後面加序號-1 -2 -3…
#tf.get_Variable對一個變數名只能用一次,第二次會報錯
import tensorflow as tf
tf.reset_default_graph()
var1 = tf.Variable(1.0,name=‘firstvar’)
print(“var1:”,var1.name)
var1 = tf.Variable(2.0,name=‘firstvar’)#secondvar
print(“var1:”,var1.name)
var2=tf.Variable(3.0)
print(“var2:”,var2.name)
var2=tf.Variable(4.0)
print(“var2:”,var2.name)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(“var1=”,var1.eval())
print(“var2=”,var2.eval())
get_varl =tf.get_variable(“firstvar”,[1],initializer =
tf.constant_initializer(0.3))
print(“get_varl:”,get_varl.name)
get_varl =tf.get_variable(“firstvar1”,[1],initializer =
tf.constant_initializer(0.4))
print(“get_varl:”,get_varl.name)
get_var2 =tf.get_variable(“firstvar”,[1],initializer =
tf.constant_initializer(0.3))#這行報錯
print(“get_var2:”,get_var2.name)