文章目录
前言代码自己运行,可以观察到规律,这里不做截图。
1 编程模型 2 Session操作import tensorflow as tf
hello=tf.constant("hello tf!")
sess=tf.Session()
print(sess.run(hello))
sess.close()
a=tf.constant(3)
b=tf.constant(4)
with tf.Session() as sess:
print("相加:",sess.run(a+b))
#注入示例
c=tf.placeholder(tf.int16)
d=tf.placeholder(tf.int16)
add=tf.add(c,d)
mul=tf.multiply(c,d)
with tf.Session() as sess2:
print("相乘:",sess2.run(mul,feed_dict={c:3,d:4}))
print(sess2.run([add,mul],feed_dict={c:3,d:4}))
3 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')
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_var1=tf.get_variable("firstvar",[1],initializer=tf.constant_initializer(0.1))
print("get_var1",get_var1.name)
get_var1=tf.get_variable("firstvar1",[1],initializer=tf.constant_initializer(0.2))
print("get_var1",get_var1.name)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print("get_var1:",get_var1.eval())
3.1 variable_scope和get_variable
3.2 作用域和操作(name_scope)
4 图的基本操作
import tensorflow as tf
c=tf.constant(0.0)
g=tf.Graph()
with g.as_default():
c1=tf.constant(0.0)
print(c1.graph)
print(g)
print(c.graph)
g2=tf.get_default_graph()
print(g2)
tf.reset_default_graph()
g3=tf.get_default_graph()
print(g3)
#获取张量
print(c1.name)
t=g.get_tensor_by_name(name='Const:0')
print(t)
#获取节点操作op
a=tf.constant([[1.0,2.0]])
print('a.shape',a.shape)
b=tf.constant([[1.0],[2.0]])
print('b.shape',b.shape)
tensor1=tf.matmul(a,b,name='exampleop')
print(tensor1.name,tensor1)
test=g3.get_tensor_by_name('exampleop:0')
print(test)
print('tensor1.op.name',tensor1.op.name)
testop=g3.get_operation_by_name("exampleop")
print('testop',testop)
tt2=g.get_operations()
print(tt2)
tt3=g.as_graph_element(c1)
print(tt3)
5 注意tensorboard的使用