其中的TF_CPP_MIN_LOG_LEVEL据说是为了忽略警告,但是我这里没有意义(numpy的一些警告)
import tensorflow as tf
import os
os.environ["TF_CPP_MIN_LOG_LEVEL"]='3'
其中,log_device_placement参数配置到回话Session中,可以在运行时显示使用的是哪部分的资源(CPU,gpu)
hello=tf.constant('Hello')
cfig=tf.ConfigProto(log_device_placement=True)
sess=tf.Session(config=cfig)
dss=sess.run(hello)
print(dss)
sess.close()
sess=tf.Session()
a=tf.constant([1,2,3,4,5,6],shape=[2,3],name='a')
b=tf.constant([1,2,3,4,5,6],shape=[3,2],name='b')
c=tf.matmul(a,b)
xss=sess.run(c)
print(xss)
sess.close()
tf.add可以这里使用a+b的形式,name自动取得
sess=tf.Session()
a=tf.constant(1,name='ta')
b=tf.constant(2,name='tb')
#c=a+b
c=tf.add(a,b,name='tc')
sess=tf.Session()
xss=sess.run(c)
print(xss)
保存图的过程中,提供相应的路径,然后保存sess.graph,是所有运行过的图。
xsum=tf.summary.FileWriter(".",sess.graph)
保存后,打开tensorboard:使用类型cmd命令:打开服务,然后浏览graph项
tensorboard --logdir="."
tensorboard还可以看到其它如直方图,结构图,分布图等部分。
gg=tf.get_default_graph()
op1=gg.get_operations()
print(op1)
print(op1[1].node_def)
原始信息:(因为之前有一个字符串常量运行过,所以这里会记录第一个是Const)之前进行过矩阵运算,第一个a为矩阵,其信息则通过op[1].node_def显示出来了
变量计算需要使用tf.global_variables_initializer()进行初始化变量,否则可能报错。
x=tf.constant(1.0,name='input')
w=tf.Variable(0.8,name='weight')
y=tf.multiply(w,x,name='output')
sess=tf.Session()
sess.run(tf.global_variables_initializer())
ans=sess.run(y)
xsum=tf.summary.FileWriter('.',sess.graph)
print(ans)
sess.close()
对应图:
定义好变量后,通过字典格式输入数据,获取结果并打印出来。
x=tf.placeholder(tf.float32,name='x')
y=tf.placeholder(tf.float32,name='y')
z=tf.add(x,y,name='z')
ss=tf.Session()
xsum=tf.summary.FileWriter('.',ss.graph)
xss=ss.run(z,feed_dict={x:1,y:2})
print(xss)
对应图:
输出d为12
dss='10+2'
d=eval(dss)
d