Tensorflow编程学习笔记(1)_Session、Variable、Fetch和Feed

来源:互联网 发布:重庆市行知学校 编辑:程序博客网 时间:2024/06/15 15:43
  • 该系列是笔者在Tensorflow编程学习过程中记录的笔记,仅供参考。
  • 所有涉及的代码都来自课堂学习纯手打记录。

Test1 常量、变量、Fetch、Feed、Session

在tensorflow中,常量通过constant函数来定义。
在tensorflow中,变量通过Variable函数来定义,注意:只要用到变量,就一定要run一下initialize_all_variables()来初始化变量。
Session在tensorflow中就像指针一样,指向需要运行的代码。
Session运行结束后,需要关闭。
Fetch对多个操作节点取值。
Feed给占位符赋值。

import tensorflow as tfa = tf.constant(3.0)            #定义常量(赋值)b = tf.Variable(1.0)            #定义变量(赋值)c = tf.placeholder(tf.float32)  #定义占位符(位数)d1 = tf.add(a,b)    #a+bd2 = tf.sub(a,b)    #a-bbd3 = tf.mul(a,b)    #a*bd4 = tf.div(a,b)    #a/be1 = tf.mod(a,b)    #a%be2 = tf.abs(c)      #|c|e3 = tf.sqrt(c)     #平方根e4 = tf.pow(a,b)    #a^bf1 = tf.maximum(a,b)f2 = tf.minimum(a,b)m1 = tf.constant([[3,3]])m2 = tf.constant([[2],[3]])g = tf.matmul(m1,m2)            #矩阵乘法[2*3+3*3]=[15]with tf.Session() as sess:    sess.run(tf.global_variables_initializer())    #变量初始化    result = sess.run([d1,d2,d3,d4,e1,e4,f1,f2,g]) #Fetch    print(result)    print (sess.run(e2, feed_dict={c: -3}))        #Feed    print (sess.run(e3, feed_dict={c: 4}))    print(g)    print(sess.run(g))    print(sess.run([g]))

运行结果:

[4.0, 2.0, 3.0, 3.0, 0.0, 3.0, 3.0, 1.0, array([[15]])]3.02.0Tensor("MatMul:0", shape=(1, 1), dtype=int32)[[15]][array([[15]])]

Test2 循环

import tensorflow as tf#创建一个op变量,初始化为0state = tf.Variable(0)#创建一个op,作用是使state+1new_state = tf.add(state,1)#赋值op: state = new_value即把new_state的值赋值给state。在执行Session时,会根据定义的运算逻辑,逐个向上查找。因为在update里用到了new_state,所以会执行new_state定义的内容。update =tf.assign(state,new_state)with tf.Session() as sess:    sess.run(tf.global_variables_initializer())    print(sess.run(state))        #循环5次    for _ in range(5):        sess.run(update)        print(sess.run(state))

运行结果:

012345

Test3 简单实例

import tensorflow as tfimport numpy as np#使用numpy生产100个随机点x_data = np.random.rand(100)#一条斜率为0.1、偏移是0.2的直线y_data = x_data*0.1+0.2#构造一个线性模型b = tf.Variable(0.)k = tf.Variable(0.)#斜率k,偏移b,变量x_datay = k*x_data + b#优化变量k、b使线性模型接近于上面样本点的分布#定义二次代价(或者叫目标/损失)函数# reduce_mean()求平均值、square()求平方# y_data是真实值,y是预测值loss = tf.reduce_mean(tf.square(y_data-y))#定义一个梯度下降法来进行训练的优化器# GradientDescentOptimizer()梯度下降法优化器(括号内给定学习率)optimizer = tf.train.GradientDescentOptimizer(0.2)#最小化代价(或者叫目标/损失)函数train = optimizer.minimize(loss)#初始化变量init = tf.global_variables_initializer()with tf.Session() as sess:    sess.run(init)    #迭代201次    for step in range(201):        sess.run(train)        #每训练20次打印一次        if step%20 == 0:            print(step,sess.run([k,b]))

运行结果:

0 [0.047159102, 0.097865961]20 [0.098292276, 0.20082079]40 [0.099039868, 0.2004616]60 [0.099460147, 0.20025954]80 [0.099696465, 0.20014593]100 [0.099829316, 0.20008205]120 [0.099904031, 0.20004614]140 [0.099946037, 0.20002595]160 [0.09996964, 0.20001459]180 [0.099982917, 0.20000821]200 [0.099990398, 0.20000462]

可以看到k接近0.1、b接近0.2
关于reduce_mean()的博文:
tensorflow学习之常用函数总结:tensorflow官方例子中的诸如tf.reduce_mean()这类函数


Test4 线性回归

import tensorflow as tfimport numpy as npimport matplotlib.pyplot as plt#使用numpy从[-0.5,0.5]区间内生成均匀分布的200个随机点#[:,np.newaxis]增加维度,200行1列的数据x_data = np.linspace(-0.5, 0.5, 200)[:,np.newaxis]#生成干扰项,随机值noise = np.random.normal(0,0.02,x_data.shape)#U型曲线y_data = np.square(x_data) + noise#定义两个占位符placeholder,n行1列[None,1]x = tf.placeholder(tf.float32, [None,1])y = tf.placeholder(tf.float32, [None,1])#layer1#定义神经网络中间层#权重变量,1行10列,随机初始化Weights_L1 = tf.Variable(tf.random_normal([1,10]))#偏移量,1行10列,初始化为0biases_L1 = tf.Variable(tf.zeros([1,10]))#矩阵乘法Wx_plus_b_L1 = tf.matmul(x, Weights_L1) +biases_L1#中间层的输出,双曲正切函数作为激活函数L1 = tf.nn.tanh(Wx_plus_b_L1)#layer2#定义神经网络输出层Weights_L2 = tf.Variable(tf.random_normal([10,1]))biases_L2 = tf.Variable(tf.zeros([1,1]))Wx_plus_b_L2 = tf.matmul(L1,Weights_L2) + biases_L2#预测结果:prediction = tf.nn.tanh(Wx_plus_b_L2)#二次代价函数loss = tf.reduce_mean(tf.square(y-prediction))#使用梯度下降法train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)with tf.Session() as sess:    #变量初始化    sess.run(tf.global_variables_initializer())    #迭代2000次    for _ in range(2000):        sess.run(train_step, feed_dict={x:x_data, y:y_data})    #获得预测值    prediction_value = sess.run(prediction, feed_dict={x:x_data})    #画图    plt.figure()    plt.scatter(x_data, y_data)    #'r-':画一条红色实线    plt.plot(x_data,prediction_value,'r-',lw=5)    plt.show()

运行结果:
这里写图片描述

原创粉丝点击