1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| import tensorflow as tf import os
tf.app.flags.DEFINE_integer("max_step",100,"模型訓練的步數") tf.app.flags.DEFINE_float("learning_rate",0.1,"學習率") tf.app.flags.DEFINE_string("ckpt_path"," ","模型文件加載路徑")
FLAGS = tf.app.flags.FLAGS
def LinearRegression(): with tf.variable_scope("data_preparation"): X = tf.random_normal([100,1],mean=1.75,stddev=0.5, name="x_data") y_true = tf.matmul(X,[[0.7]]) + 0.8
with tf.variable_scope("LinearRegression_model_build"): weight = tf.Variable(tf.random_normal([1,1],mean=0.0,stddev=1.0),name="w") bias = tf.Variable(0.0,name="bias") y_predict = tf.matmul(X,weight) + bias
with tf.variable_scope("loss_calculate"): loss = tf.reduce_mean(tf.square(y_true - y_predict))
with tf.variable_scope("optimize"): train_op = tf.train.GradientDescentOptimizer(FLAGS.learning_rate).minimize(loss)
tf.summary.scalar("Loss",loss)
tf.summary.histogram("Weight",weight) tf.summary.scalar("Bias",bias)
merged = tf.summary.merge_all()
init_var_op = tf.global_variables_initializer()
Saver = tf.train.Saver()
with tf.Session() as sess: sess.run(init_var_op) print("起始初始化權重:%f, 初始化偏置:%f"%(weight.eval(),bias.eval()))
FileWriter = tf.summary.FileWriter("./summary/",graph=sess.graph)
if os.path.exists("/Volumes/MacData/MEGA/pythonwork/ML_study/tensorflow_tutorial/checkpoint_document/checkpoint"): Saver.restore(sess,FLAGS.ckpt_path) print("加載模型後 權重:%f, 偏置:%f" % (weight.eval(), bias.eval()))
for i in range(FLAGS.max_step): sess.run(train_op)
summary = sess.run(merged)
FileWriter.add_summary(summary,i)
if i%50 == 0: print("優化%d次後 權重:%f, 優化偏置:%f" % (i,weight.eval(), bias.eval()))
else: Saver.save(sess, "/Volumes/MacData/MEGA/pythonwork/ML_study/tensorflow_tutorial/checkpoint_document/LinearRegressionModel")
if __name__ == '__main__': LinearRegression()
|