import tensorflow as tf with tf.Session() as session: #创建一个对象包含计算图 x = tf.placeholder(tf.float32, [1], name="x") #利用占位符概念定义变量 y = tf.placeholder(tf.float32, [1], name="y") z = tf.constant(2.0) y = x * z x_in = [100]#该程序可以处理非常大、非常复杂的x值,所以可以创建x_in列表,并使其指向占位符x。 y_output = session.run(y, {x: x_in}) #只有执行session.run()时,程序才会开始处理已定义的图元素 print(y_output)
import tensorflow as tf constant_A=tf.constant([100.0]) constant_B=tf.constant([300.0]) constant_C=tf.constant([3.0]) sum_=tf.add(constant_A,constant_B) mul_=tf.multiply(constant_A,constant_C) with tf.Session() as sess: result=sess.run([sum_,mul_]) print(result)
#接下来 tensorboard for value in [input_value,weight,expected_output,model,loss_function]: tf.summary.scalar(value.op.name,value) summaries=tf.summary.merge_all() #为每个运行的结点添加分析,然后总结 sess=tf.Session() log_path="../Tensorboardlog\og_simple_stats" summary_writer=tf.summary.FileWriter(log_path,sess.graph) #声明路径 sess.run(tf.global_variables_initializer()) for i inrange(100): summary_writer.add_summary(sess.run(summaries),i) #写入信息 sess.run(optimizer)
实例
实例1:从一组看似混乱的数据中找出y=2x的规律
1 2 3 4 5 6 7 8 9 10 11
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt %matplotlib inline train_X=np.linspace(-1,1,100) train_Y=2*train_X+np.random.randn(100)*0.3 #显示模拟数据点 plt.plot(train_X,train_Y,'ro',label='Original data') plt.legend() plt.show()
plotdata['avgloss']=moving_average(plotdata["loss"]) plt.figure(1) plt.subplot(211) plt.plot(plotdata["batchsize"],plotdata["avgloss"],'b--') plt.xlabel('Minibatch number') plt.ylabel('Loss') plt.title('Minibatch run vs. Training loss') plt.show()
#保存模型见上文代码 中saver #载入模型 with tf.Session() as sess2: sess2.run(tf.global_variables_initializer()) saver.restore(sess2,savedir+"linermodel.cpkt") print("x=0.2,z=",sess2.run(z,feed_dict={X:0.2}))
WARNING:tensorflow:From E:\Python\Anaconda\lib\site-packages\tensorflow\python\training\saver.py:1276: checkpoint_exists (from tensorflow.python.training.checkpoint_management) is deprecated and will be removed in a future version.
Instructions for updating:
Use standard file APIs to check for files with this prefix.
INFO:tensorflow:Restoring parameters from log/linermodel.cpkt
x=0.2,z= [0.3858556]
打印模型内容
1 2 3 4
from tensorflow.python.tools.inspect_checkpoint import print_tensors_in_checkpoint_file savedir="log/" print_tensors_in_checkpoint_file(savedir+"linermodel.cpkt",None,True)
tensor_name: bias
[-0.00912086]
tensor_name: weight
[1.9748821]
# Total number of params: 2
plotdata['avgloss']=moving_average(plotdata["loss"]) plt.figure(1) plt.subplot(211) plt.plot(plotdata["batchsize"],plotdata["avgloss"],'b--') plt.xlabel('Minibatch number') plt.ylabel('Loss') plt.title('Minibatch run vs. Training loss') plt.show() #重启session,载入检查点 load_epoch=18 with tf.Session() as sess2: sess2.run(tf.global_variables_initializer()) saver.restore(sess2,savedir+"linermodel.cpkt-"+str(load_epoch)) print("x=0.2,z=",sess2.run(z,feed_dict={X:0.2}))