DeepLearn_TensorFlow入门练习1-1

1. Implement Logistic Regression with Mini-batch Gradient Descent using TensorFlow. Train it and evaluate it on the moons dataset .Try adding all the bells and whistles:

A. Define the graph within a logistic_regression() function that can be reused easily. (submit python file)

B. Save checkpoints using a Saver at regular intervals during training, and save the final model at the end of training. (submit both python file and the saved model)

C. Restore the last checkpoint upon startup if training was interrupted. (submit python file)

D. Define the graph using nice scopes so the graph looks good in TensorBoard. (submit python file)

E. Add summaries to visualize the learning curves in TensorBoard. (submit python file)

F. Try tweaking hyperparameters, including the learning rate and the mini- batch size and display the shape of the learning curve. (submit screenshot)



A.使用Tensorlow实现小批量梯度下降(Mini-Batch)的逻辑回归

import tensorflowas tf
from sklearn.datasetsimport make_moons
# trainnumber 训练集的大小
# x_train 输入
# y_train 输出
# weight 权重
# bia 偏量
# itert 迭代次数
# learnrate 学习率
# batchsize 一个mini-batch大小
#传入上述参数返回 weight与bia
def getWegihtBia(trainnumber, x_train, y_train, weight, bia, itert, learnrate, batchsize, sess):
weight = tf.Variable(weight,dtype=tf.float32,name="weight")
bia = tf.Variable(bia,dtype=tf.float32,name="bia")
x_train = tf.cast(x_train,dtype=tf.float32,name="x_train")
y_train = tf.cast(y_train.reshape([trainnumber,1]),dtype=tf.float32,name="y_train")
input = tf.placeholder(dtype=tf.float32,shape=[None,2],name="input")
output = tf.placeholder(dtype=tf.float32,shape=[None,1],name="output")
y_pred = tf.add(tf.matmul(input, weight), bia)#y=w*x+b 预测值 
mse = tf.reduce_mean(tf.square(y_pred - output))#根据误差调整
init = tf.global_variables_initializer()
sess.run(init)
opt = tf.train.GradientDescentOptimizer(learnrate)#学习率
train_step = opt.minimize(mse)
#此处为实现mini-batch
x_templist = []
y_templist = []
for j in range(itert):
        for i in range(trainnumber):
                 if i % batchsize ==0 and i !=0:
                       sess.run(train_step,feed_dict={input: x_templist, output: y_templist})
                        x_templist.clear()
                        y_templist.clear()
                        x_templist.append(x_train.eval(session=sess)[i])
                        y_templist.append(y_train.eval(session=sess)[i])
                else:
                        x_templist.append(x_train.eval(session=sess)[i])
                        y_templist.append(y_train.eval(session=sess)[i])
return weight, bia

def accuracy(testnumber, x_test, y_test, weight, bia):
y_test = y_test.reshape([testnumber,1])
right =0
    for iin range(testnumber):
            y_out = x_test[i][0] * weight[0][0] + x_test[i][1] * weight[1][0] + bia[0][0]
            y_outvalue = sess.run(y_out)
            y_pred =0
            if y_outvalue >=0.5:
                y_pred =1
            if y_pred == y_test[i][0]:
                right = right +1
print("accuracy is " +str(right / testnumber))testnumber =100
#参数
trainnumber =500
batchsize =50
itert =500
learnrate =0.01
x_train, y_train = make_moons(trainnumber)
x_test,  y_test =  make_moons(testnumber)
weight = tf.Variable(tf.random_normal(shape=[2,1]))
bia = tf.Variable(tf.random_normal(shape=[1,1]))
sess = tf.Session()
weight,bia = getWegihtBia(trainnumber, x_train, y_train, weight, bia, itert, learnrate, batchsize, sess)
accuracy(testnumber, x_test, y_test, weight, bia)
sess.close()
#从make_moons中产生的数据集合为
x:[[xx,xx][xx,xx][xx,xx]...]
y:[x,x,x...]因此此处需调整为[[x],[x],[x]..] 即getWegihtBia中的y_train.reshape([trainnumber,1]) (即转换为trainnumber维度,1维的数据集合)


B.保存参数

#训练途中或者训练完成保存模型,会有对应4个文件:
#checkpoint
#Logistic Regression_Moon.ckpt.data-00000-of-00001
#Logistic Regression_Moon.ckpt.index
#Logistic Regression_Moon.ckpt.meta
for j in range(itert):
    saver.save(sess, os.getcwd() +"/tmp/Logistic Regression_Moon.ckpt")
    for i in range(trainnumber): 
        if i % batchsize ==0 and i !=0:
            sess.run(train_step,feed_dict={input: x_templist, output: y_templist})
            saver.save(sess, os.getcwd() +"/tmp/Logistic Regression_Moon.ckpt")
            x_templist.clear()
            y_templist.clear()
            x_templist.append(x_train.eval(session=sess)[i])
            y_templist.append(y_train.eval(session=sess)[i])
        else:
            x_templist.append(x_train.eval(session=sess)[i])
            y_templist.append(y_train.eval(session=sess)[i])
    saver.save(sess, os.getcwd() +"/tmp/Logistic Regression_Moon.ckpt")


C.中断的过程中恢复训练

#此处可恢复上次中断的数据,想要恢复的数据需要tf.Variable来设置
#其中值得注意的是多次赋值如:
# A = tf. tf.Variable(8,dtype=tf.int32,name="A")
# A = tf. tf.Variable(9,dtype=tf.int32,name="A")
# 执行上述两次再保存模型获取 根据name=A获取的数据为8,
# 若想获取A = 9 需要根据name=A_1 此处有困惑
weight = tf.Variable(weight,dtype=tf.float32,name="weight")
bia = tf.Variable(bia,dtype=tf.float32,name="bia")
#...此处设置参数
saver = tf.train.Saver()
sess = tf.Session()
init_op = tf.initialize_all_variables()
sess.run(init_op)
saver.restore(sess, os.getcwd() +"/tmp/Logistic Regression_Moon.ckpt")
weight,bia = getWegihtBia(trainnumber, x_train, y_train, weight, bia, itert, learnrate, batchsize, sess)


D.TensorBoard运用scopes使图更好看
E.TensorBoard画学习曲线
F.更改参数(learn rate,mini-batch Size..)

TensorBoard 图1


TensorBoard 图2

通过运用tf.name_scope:这个函数可以是图分割更易于理解
with tf.name_scope("Trian")as Trian:
                weight, bia = getWegihtBia(trainnumber, x_train, y_train, weight, bia,                                         itert, learnrate, batchsize, sess)

画MSE曲线:

mini-batch MSE 图3

          mini-batch梯度下降 训练结果会震荡如图3,mini-batch可以解决资料量巨大时候batch 梯度下降无法读取所有资料的问题。
def getWegihtBia(trainnumber, x_train, y_train, weight, bia, itert, learnrate, batchsize, sess):
with tf.name_scope("WeightBia")as WeightBia:
        weight = tf.Variable(weight,dtype=tf.float32,name="weight")
        bia = tf.Variable(bia,dtype=tf.float32,name="bia")
with tf.name_scope("TrainSet")as TrainSet:
        x_train = tf.Variable(x_train,dtype=tf.float32,name="x_train")
        y_train = tf.Variable(y_train.reshape([trainnumber,1]),dtype=tf.float32,name="y_train")
with tf.name_scope("MSE")as MSE:
        input = tf.placeholder(dtype=tf.float32,shape=[None,2],name="input")
        output = tf.placeholder(dtype=tf.float32,shape=[None,1],name="output")
        y_pred = tf.add(tf.matmul(input, weight), bia)
        mse = tf.reduce_mean(tf.square(y_pred - output))
        opt = tf.train.GradientDescentOptimizer(learnrate)
        train_step = opt.minimize(mse)
init = tf.global_variables_initializer()
saver = tf.train.Saver()
sess.run(init)
mse_summary = tf.summary.scalar('MSE', mse)#记录的mse
now = datetime.utcnow().strftime("%Y%m%d%H%M%S")#获取时间
root_logdir = os.getcwd() +"/tf_logs"#设置路径
logdir ="{}/run-{}/".format(root_logdir, now)#目录以上述路径+时间

file_writer = tf.summary.FileWriter(logdir, tf.get_default_graph())
x_templist = []
y_templist = []
index =0
for j in range(itert):
     for i in range(trainnumber):
            if i % batchsize ==0 and i !=0:
                    summary_str = mse_summary.eval(session=sess,feed_dict={input: x_templist, output: y_templist})#计算mse
                    file_writer.add_summary(summary_str, index)#记录mse
  
                    index +=1
                     sess.run(train_step,feed_dict={input: x_templist, output: y_templist})

                    save_path = saver.save(sess, os.getcwd() +"/tmp/Logistic Regression_Moon.ckpt")
                    x_templist.clear()
                    y_templist.clear()
                    x_templist.append(x_train.eval(session=sess)[i])
                    y_templist.append(y_train.eval(session=sess)[i])
        else:
                x_templist.append(x_train.eval(session=sess)[i])
                y_templist.append(y_train.eval(session=sess)[i])
                file_writer.close()
                save_path = saver.save(sess, os.getcwd() +"/tmp/Logistic Regression_Moon.ckpt")
return weight, bia

运行会在当前目录产生tf_logs/run-20180318124429/events.out.tfevents.1521377069.DESKTOP-9MSI5BD类似的文件,控制台,cd E:\Anaconda3\Scripts目录下,再输入
tensorboard --logdir E:\JetBrains\PycharmProjects\DeepLearnHW1\tf_logs\
其中后者为上述文件所在目录 ,再输入所显示网址即可浏览

TensorBoard开启图4
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,491评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,856评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,745评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,196评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,073评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,112评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,531评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,215评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,485评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,578评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,356评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,215评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,583评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,898评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,497评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,697评论 2 335

推荐阅读更多精彩内容

  • 简单线性回归 import tensorflow as tf import numpy # 创造数据 x_dat...
    CAICAI0阅读 3,534评论 0 49
  • 刨汤、腊拼、古藏肉、苗王鱼、白切鸡、野免肉、青岩豆腐、韭菜根…… 这些都是苗族的传统佳肴,美味飘香,令人陶醉。 你...
    S金色向日葵阅读 189评论 0 0
  • 离别莫问几分疼,且在梦里留倾城。 我怕他年人易变,不如从此不相逢。
    梦在江南外阅读 169评论 0 1
  • 斜雨微湿飞燕子,烟波沆砀,春水随风皱,望极天涯云梦处,也无计潇湘暂住。 拟泛轻舟逐晚晴,水天之际,残照忽而逝,无情...
    莫自在阅读 224评论 0 0
  • 1 这两天,心里颇不太安宁,确切的讲,是有点蠢蠢欲动。 昨天,朋友告知我们目前有个楼盘要内部开盘认筹,如果现在参加...
    Mr_Zhang2O12阅读 242评论 0 1