import tensorflow as tf
import os
os.environ['TF_CPP_LOG_LEVEL']='2'
def demo():
a=tf.constant(2)
b=tf.constant(3)
c=a+b
print(c)
# 开启会话
# 查看默认图两种方法
# 1.调用方法
default_g=tf.get_default_graph()
print(default_g)
# 2.查看属性
print(b.graph)
print(c.graph)
# 如果不知道a_ph和b_ph的数值可以用placeholder占位
a_ph=tf.placeholder(tf.float32)
b_ph=tf.placeholder(tf.float32)
c_ph=tf.add(a_ph,b_ph)
with tf.Session() as sess:
c_value_ph=sess.run(c_ph,feed_dict={a_ph:3.4,b_ph:5.7})
print(c_value_ph)
c_value=sess.run(c)
print(sess.graph)
print(c_value)
# 将图写入本地生成event文件
tf.summary.FileWriter("C:/logfile",graph=sess.graph)
# 自定义图
new_g=tf.Graph()
# 在自己图中定义数据和操作
with new_g.as_default(): # 借助上下文管理器
a_new=tf.constant(3)
b_new=tf.constant(7)
c_new=a_new+b_new
with tf.Session(graph=new_g) as new_sess:
c_new_defult=new_sess.run(c_new)
print(c_new_defult)
def linear_regression():
# 准备数据
with tf.variable_scope("prepare_data"):
x=tf.random_normal(shape=[100,1],name="Feature")
y_true=tf.matmul(x,[[0.8]])+0.7
with tf.variable_scope("create_model"):
# 构造模型
# 定义模型参数用变量
weights=tf.Variable(initial_value=tf.random_normal(shape=[1,1],name="Weight"))
bias=tf.Variable(initial_value=tf.random_normal(shape=[1,1],name="Bias"))
y_predict=tf.matmul(x,weights)+bias
with tf.variable_scope("loss_function"):
# 构造损失函数
error=tf.reduce_mean(tf.square(y_predict-y_true)) # 平方再平均
# 优化损失
with tf.variable_scope("optimizer"):
optimizer=tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(error)
# 收集变量
tf.summary.scalar("error",error)
tf.summary.histogram("bias",bias)
tf.summary.histogram("weights",weights)
# 合并变量
merged=tf.summary.merge_all()
saver=tf.train.Saver()
# 显示初始化变量
init=tf.global_variables_initializer()
# 开启会话
with tf.Session() as sess:
sess.run(init)
# 创建事件文件
file_writer=tf.summary.FileWriter("C:/logfile", graph=sess.graph)
# 查看初始化模型参数的值
print("训练前的参数为:权重%f,偏置%f,损失%f"% (weights.eval(), bias.eval(), error.eval()))
# 开始训练
for i in range(10):
sess.run(optimizer)
print("训练第%d的参数为:权重%f,偏置%f,损失%f" % (i+1,weights.eval(), bias.eval(), error.eval()))
# 运行合并变量操作
summary=sess.run(merged)
# 将每次迭代后的变量写入事件文件
file_writer.add_summary(summary,i+1)
# 保存模型
if i % 10 ==0:
saver.save(sess,path)
if os.path.exists(""): # 判断文件是否存在
saver.restore(sess,path)
return None
linear_regression()
网友评论