python tensorflow库_Al.BASE-win10环境下TensorFlow的python代码练习

0.概要

0.1 基础架构

功能

组件

视图层

计算图可视化

TensorBoard

工作流层

数据集准备,存储,加载

keras/TF Slim

计算图层

计算图构造与优化 前向计算/后向传播

TensorFlow Core

0.2 计算图(Data Flow Graph)

计算图(有向图|数据流图)描述了张量数据(Tensor)的计算流程,负责维护和更新状态,一旦输入端的所有张量准备好,节点将被异步并行执行运算。

1.入门

1.1 安装

cmd中利用pip安装numpy

pip install numpy-1.11.1+mkl-cp35-cp35m-win32.whl

PowerShell(管理员)下利用pip安装tensorflow

pip install tensorflow

1.2 计算图的构造流程

tensorflow 有个重要的数据类型 叫tensor(张量),在python中是多维列表,形如[[0,1],[0,2]]。

tf的代码 主要分4步:inference loss train evaluate

图是由多个op(运算节点)构成的网络。

op负责接收tensor,运算后输出tensor。(第一层源op不需要任何输入)

import tensorflow as tf

import numpy as np

#使用numpy生成假数据。共100个点

x_data=np.float32(np.radom.rand(2,100))

y_data=np.dot(0.100,0.200)+0.300

#构造一个线性模型

b=tf.Variable(tf.zero([1]))

W=tf.Variable(tf.radom_uniform([1,2],-1.0,1.0))

y=tf.matmul(W,x_data)+b

#最小化方差

loss=tf.reduce_mean(tf.square(y-y_data))

optimizer=tf.train.GradientDescentOptimizer(0.5)

图1.2计算图

1.3 计算图创建深入

1.3.0 Tensor运算操作节点(op)

运算类型

示例

标量

add,sub,mul,div,exp,log,greater,less,equal

向量

concat,slice,split,constant,rank,shape,shuffle

矩阵

matnul,matrixInverse.matrixDeterminant

状态

Variable,Assign,AssignAdd

组件

softmax,sigmod,relu,convolution2D,maxPooling

存储

save,restore

队列与同步

enqueue,dequeue,mutexAcquire,MutexRelease

控制流

Merge,Switch,Enter,Leave,Nextlteration

pythonproduct = tf.matmul(matrix1, matrix2)#矩阵相乘

intermed = tf.add(input2, input3)#相加

mul = tf.mul(input1, intermed)#相乘

1.3.1 变量(Variable)

创建

当创建一个变量时,你将一个张量作为初始值传入构造函数Variable()。TensorFlow提供一系列操作初始化张量,初始值是常量或随机值。

weight = tf.Variable(tf.random_normal([784,200],stddev=0.35),name="weight")

biases=tf.Variabke(tf.zeros([200]),name="biases")

一个初始化op将变量设置为初始值。这事实上是一个tf.assign操作

update = tf.assign(state, new_value)#state=new_value

初始化

启动图之前需要初始化

init=tf.initialize_all_vaiavles()#初始化变量

sess=tf.Session()#启动图

sess.run(init)#执行init节点

由另一个变量初始化

weights=tf.Variable(tf.random_normal([784,200],stddev=0.35),name="weights")

w2=tf.Variable(weights.initilized_value(),name="w2")

w_twice=tf.Variable(weights.initilized_value()+0.2,name="w_twice")

保存

使用tf.train.Saver。数据主要包含从变量名到tensor的映射关系。

v1=tf.Variable(tf.zeros([200]),name="v1")

v2=tf.Variable(tf.zeros([200]),name="v2")

init_op=tf.initialize_all_variables()

saver=tf.train.Saver()

with tf.Session() as sess:

sess.run(init_op)

save_path=saver.save(sess,"tfsave/model.ckpt")

print ("Model saved in file:",save_path)

部分保存

saver=tf.train.Saver({"my_v2",v2})

恢复

v1=tf.Variable(tf.zeros([200]),name="v1")

v2=tf.Variable(tf.zeros([200]),name="v2")

init_op=tf.initialize_all_variables()

saver=tf.train.Saver()

with tf.Session() as sess:

saver.restore(sess,"tfsave/model.ckpt")

print ("Model restored")

1.3.2会话(Session)

创建

方法1:全局可见

sess=tf.Session()

方法2:局部执行

with tf.Session() as sess:

运行

sess.run(init)

循环训练

for step in xrange(0,201):

sess.run(train)

if step &20==0:

print(step,sess.run(W),sess.run(b))

1.4 HelloWorld

1.4.1 helloworld

import os

import tensorflow as tf

os.environ['TF_CPP_MIN_LOG_LEVEL']='2'

hello=tf.constant("HelloWorld")

sess=tf.Session()

print(sess.run(hello))

1.4.2 常量操作

import os

import tensorflow as tf

os.environ['TF_CPP_MIN_LOG_LEVEL']='2'

a=tf.constant(2)

b=tf.constant(3)

with tf.Session() as sess:

print("a=2,b=3")

print("常量节点相加: %i" % sess.run(a+b))

print("常量节点相乘: %i" % sess.run(a*b))

1.4.3 变量操作

import os

import tensorflow as tf

os.environ['TF_CPP_MIN_LOG_LEVEL']='2'

a=tf.placeholder(tf.int16)

b=tf.placeholder(tf.int16)

add=tf.add(a,b)

mul= tf.multiply(a,b)

with tf.Session() as sess:

print("变量节点相加: %i" % sess.run(add,feed_dict={a:2,b:3}))

print("变量节点相乘: %i" % sess.run(mul,feed_dict={a:2,b:3}))

1.4.3 矩阵操作(保存计算图)

import os

import tensorflow as tf

os.environ['TF_CPP_MIN_LOG_LEVEL']='2'

matrix1=tf.constant([[3.,3.]])

matrix2=tf.constant([[2.],[2.]])

product=tf.matmul(matrix1,matrix2)

with tf.Session() as sess:

print("变量节点相乘: %i" % sess.run(product))

#保存计算图

writer=tf.summary.FileWriter(logdir='logs',graph=tf.get_default_graph())

writer.flush()

cmd 执行tensorboard进行可视化查看

tensorboard --logdir=C:\workplace\py\tf\logs

浏览器打开127.0.0.1:6006可看到结果

1.5 TensorBoard

1.5.1 理论

TensorBoard源码基于nodejs,该面板能看到可视化的序列化数据集。包括标量(scalars),图片(images),音频(audio),计算图(graph),数据分布(distributions),直方图(histograms)和嵌入式向量(emmbedings)。

TensorBoard前台呈现的数据是tensorflow程序执行过程中,将一些summary类型的数据写入到日志目录的evenet文件中。

summary_op包括 summart.scalar,summary.histogram,summary.image等操作,这些操作输出是各种summary protobuf,最后通过summary.writer写入到event文件中。

图1.5.1 tensorboard内部原理

标量

tf.summary.scalar(tags,values,collections=None,name=None)

图像

tf.summary.image(tag,tensor,max_images=33,collections=None,name=None)

tensor必须四维,形如[batch-size,height,width,channels]

TensorBoard中看到的image summary永远是最后一个global step的

音频

tf.summary.audio(tag,tensor,ssample_rate,max_outputs=3,collections=None,name=None)

直方图

记录变量的直方图,输出带直方图的汇总protobuf

tf.summary.histogram(tag,values,collections=None,name=None)

values可以是任意形状的

1.5.2 实践

执行py

import os

import tensorflow as tf

import math

os.environ['TF_CPP_MIN_LOG_LEVEL']='2'

IMAGE_PIXELS=10

images=tf.placeholder(tf.float32,shape=(None,IMAGE_PIXELS))

#hidden 1: y1=relu(W*x1+b1)

hidden1_units=20

with tf.name_scope('hidden1'):

weights=tf.Variable(tf.truncated_normal([IMAGE_PIXELS,hidden1_units],stddev=1.0/math.sqrt(float(IMAGE_PIXELS))),name='weights')

biases=tf.Variable(tf.zeros([hidden1_units]),name='biases')

hidden1=tf.nn.relu(tf.matmul(images,weights)+biases)

#hidden 2:y2=relu(W*x2+b2)

hidden2_units=10

with tf.name_scope('hidden2'):

weights=tf.Variable(tf.truncated_normal([hidden1_units,hidden2_units],stddev=1.0/math.sqrt(float(hidden1_units))),name='weights')

biases=tf.Variable(tf.zeros([hidden2_units]),name='biases')

hidden2=tf.nn.relu(tf.matmul(hidden1,weights)+biases)

#存储计算图

writer=tf.summary.FileWriter("logs/test_tensorboard",tf.get_default_graph())

writer.close()

执行cmd

tensorboard --logdir=C:\workplace\py\tf\logs

图1.5.2-2 tensorboard浏览器查看

1.6一元线性回归

1.6.1 理论

回归模型:给定一组一维随机变量x和y变化的数据点{[x1,y1],[x2,y2],...,[xn,yn]},求函数y=wx+b

优化模型:

优化器:梯度下降 Gradient Descent

梯度下降法Gradient Descent是一种常用的一阶(first-order)优化方法,是求解无约束优化问题最简单、最经典的方法之一。考虑无约束优化问题$min_xf(x)$,其中$f(x)$为连续可微函数。如果能构造出一个序列$x^0,x^1,...,x^t$满足:

$$

f(x^{t+1}) < f(x^t),t=0,1,2...

$$

则不断执行该过程即可以收敛到局部极小点。而根据泰勒展示我们可以知道:

$$

f(x+\Delta x) \simeq f(x) + \Delta x^T \nabla f(x)

$$

于是,如果要满足$f(x+\Delta x) < f(x)$,可以选择:

$$

\Delta x = -{step} \nabla f(x)

$$

其中$step$是一个小常数,表示步长。以求解目标函数最小化为例,梯度下降算法可能存在一下几种情况:

当目标函数为凸函数时,局部极小点就对应着函数全局最小值时,这种方法可以快速的找到最优解;

当目标函数存在多个局部最小值时,可能会陷入局部最优解。因此需要从多个随机的起点开始解的搜索。

当目标函数不存在最小值点,则可能陷入无限循环。因此,有必要设置最大迭代次数。

1.6.2 实践

import os

import tensorflow as tf

os.environ['TF_CPP_MIN_LOG_LEVEL']='2'

with tf.Graph().as_default():

with tf.name_scope('Input'):

X=tf.placeholder(tf.float32,name='X')

Y_true=tf.placeholder(tf.float32,name='Y_true')

with tf.name_scope('Inference'):

W=tf.Variable(tf.zeros([1]),name='Weight')

b=tf.Variable(tf.zeros([1]),name='Bias')

Y_pred=tf.add(tf.multiply(X,W),b)

with tf.name_scope('Loss'):

#添加损失

Train_loss=tf.reduce_mean(tf.pow((Y_true-Y_pred),2))/2

#梯度下降优化器

with tf.name_scope('Train'):

Optimizer=tf.train.GradientDescentOptimizer(learning_rate=0.1)

#训练节点

TrainOp=Optimizer.minimize(Train_loss)

with tf.name_scope('Eval'):

#评估节点

EvalLoss=tf.reduce_mean(tf.pow((Y_true-Y_pred),2))/2

writer=tf.summary.FileWriter("logs/test_tensorboard",tf.get_default_graph())

writer.close()

执行py,tensorboard

先删除logs文件夹在执行tensorboard

图1.6.2-1 一元线性回归TensorBoard

数据图示版

import os

import tensorflow as tf

os.environ['TF_CPP_MIN_LOG_LEVEL']='2'

import numpy as np

from matplotlib import pylab as plt

#指定默认字体

plt.rcParams['font.sans-serif'] = ['SimHei']

plt.rcParams['font.family']='sans-serif'

#解决负号'-'显示为方块的问题

plt.rcParams['axes.unicode_minus'] = False

#产生训练数据集

train_X=np.asarray([3.3,4.4,5.5,6.71,6.93,4.168,9.779,6.182,7.59,2.167,7.042,10.791,5.313,7.997,5.654,9.27,3.1])

train_Y=np.asarray([1.7,2.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值