tensorflow(深度学习框架)详细讲解及实战

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

tensorflow(深度学习框架)详细讲解及实战
还未完全写完,本⼈会⼀直持续更新!~
各⼤深度学习框架总结和⽐较
各个开源框架在GitHub上的数据统计,如下表:
主流深度学习框架在各个维度的评分,如下表:
Caffe可能是第⼀个主流的⼯业级深度学习⼯具,它开始于2013年底,具有出⾊的卷积神经⽹络实现。

在计算机视觉领域Caffe依然是最流⾏的⼯具包,它有很多扩展,但是由于⼀些遗留的架构问题,它对递归⽹络和语⾔建模的⽀持很差。

此外,在Caffe中图层需要使⽤C++定义,⽽⽹络则使⽤Protobuf定义。

CNTK由深度学习热潮的发起演讲⼈创建,⽬前已经发展成⼀个通⽤的、平台独⽴的深度学习系统。

在CNTK中,⽹络会被指定为向量运算的符号图,运算的组合会形成层。

CNTK通过细粒度的构件块让⽤户不需要使⽤低层次的语⾔就能创建新的、复杂的层类型。

TensorFlow是⼀个理想的RNN(递归神经⽹络) API的实现,TensorFlow使⽤了向量运算的符号图⽅法,使得新⽹络的指定变得相当容易,但TensorFlow并不⽀持双向RNN和3D卷积,同时公共版本的图定义也不⽀持循环和条件控制,这使得RNN的实现并不理想,因为必须要使⽤Python循环且⽆法进⾏图编译优化。

Theano⽀持⼤部分先进的⽹络,现在的很多研究想法都来源于Theano,它引领了符号图在编程⽹络中使⽤的趋势。

Theano的符号API⽀持循环控制,让RNN的实现更加容易且⾼效。

Torch对卷积⽹络的⽀持⾮常好。

在TensorFlow和Theano中时域卷积可以通过conv2d来实现,但这样做有点取巧;Torch通过时域卷积的本地接⼝使得它的使⽤⾮常直观。

Torch通过很多⾮官⽅的扩展⽀持⼤量的RNN,同时⽹络的定义⽅法也有很多种。

但Torch本质上是以图层的⽅式定义⽹络的,这种粗粒度的⽅式使得它对新图层类型的扩展缺乏⾜够的⽀持。

与Caffe相⽐,在Torch中定义新图层⾮常容易,不需要使⽤C++编程,图层和⽹络定义⽅式之间的区别最⼩。

学会⽤conda管理环境
Linux系统下conda命令(光速浏览熟悉):
查看当前conda版本:
conda --v
查看当前环境下安装的包:
conda list
查看系统中存在的所有由conda创建的python环境:
conda env list
创建环境:
conda create -n (新环境名) python=2/3(指定python版本) package(要安装的包)
删除环境:
conda remove -n (已存在的环境名)
切换到已存在的指定环境:
source activate (已存在的环境名)
退出当前环境:
source deactivate (已存在的环境名)
在当前环境中安装包:
pip install package(要安装的包)
更改conda源(光速安装tensorflow)
conda config --add channels
conda config --add channels
conda config --set show_channel_urls yes
conda install tensorflow
解决Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA问题
前期基础概念
反向传播算法(backpropagation algorithm)
梯度下降算法(gradient descent algorithm)
损失(loss)/成本(cost)函数
交叉熵(cross-entropy)
均值归⼀化
softmax函数
充分理解数据流图,并⽤tensorflow实现之
tensorflow基础定义:它是⼀个采⽤数据流图(Data Flow Graph)⽤于数值计算的开源软件。

它由Google⼤拿2015年开源出来的。

数据流图(⽤结点和边的有向图来描述数学计算)由两部分组成:
结点(node):⼀般代表了对数据所做的运算或某种操作。

但也可以表⽰数据输⼊(feed in)的起点/输出(push out)的终点,或者是读取/写⼊持久变量(persistent variable)的终点。

边(edge):表⽰“节点”之间的输⼊/输出关系。

这些“边”可以输运“size可动态调整”的多维数据数组,即“张量”(tensor),因为tensor是在图⾥⾯flow(流动),所以可以说tensorflow这个词再形象不过了。

Tensors常量值函数:
tf.zeros(shape, dtype=tf.float32, name=None)
tf.zeros_like(tensor, dtype=None, name=None)
tf.ones(shape, dtype=tf.float32, name=None)
tf.ones_like(tensor, dtype=None, name=None)
tf.fill(dims, value, name=None)
tf.constant(value, dtype=None, shape=None, name='Const')
tensorflow中四个重要概念及五⼤重要属性
1. Tensor
2. Variable
3. placeholder
4. Session
使⽤图 (graph) 来表⽰计算任务
在被称之为会话 (Session) 的上下⽂ (context) 中执⾏图
使⽤ tensor 表⽰数据
通过变量 (Variable) 维护状态
使⽤ feed 和 fetch 可以为任意的操作(arbitrary operation) 赋值或者从其中获取数据
tensorflow两个主要过程
构建抽象模型
实际训练
tensorflow中mnist数字识别代码(简单单层softmax神经⽹络)
import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
# 读⼊数据
mnist = input_data.read_data_sets('MINIST_data/', one_hot = True)
def Mnist_Simple_Tesorflow():
mnist = input_data.read_data_sets('MINIST_data/', one_hot = True)
# 构建抽象模型
x = tf.placeholder('float', [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(x, W) + b)
# 训练模型
y_ = tf.placeholder('float', [None, 10])
cross_entropy = -tf.reduce_sum(y_ * tf.log(y))
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
# 初始化
init = tf.global_variables_initializer()
# ⽤Session启动模型
sess = tf.Session()
sess.run(init)
# 训练1000次!
for step in range(1000):
# 采⽤随机训练(stochastic training),即随机抓取训练数据中的100个批处理数据点,然后我们⽤这些数据点作为参数替换之前的占位符来运⾏train_step。

batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict = {x : batch_xs, y_ : batch_ys})
# 评估模型
correct_pre = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_pre, 'float'))
print(sess.run(accuracy, feed_dict = {x : mnist.test.images, y_ : bels}))
if __name__ == '__main__':
Mnist_Tesorflow()
上述代码的输出结果约为91%左右(运⾏后可能会出现许多警告,你可以暂时先不⽤管它~)
tensorflow中mnist数字识别代码(复杂多层卷积神经⽹络)
import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
# 读⼊数据
mnist = input_data.read_data_sets('MINIST_data/', one_hot = True)
# 权重初始化
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)
# 卷积
def conv2d(x, W):
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
# 池化
def max_pool_2x2(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
def Mnist_Complex_Tensorflow():
# 构建抽象模型
x = tf.placeholder('float', [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y_ = tf.placeholder('float', [None, 10])
# 第⼀层卷积
W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])
x_image = tf.reshape(x, [-1, 28, 28, 1])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)
# 第⼆层卷积
W_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)
# 密集连接层
W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])
h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
# Dropout
keep_prob = tf.placeholder("float")
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
# 输出层
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
# 训练和模型评估
cross_entropy = -tf.reduce_sum(y_ * tf.log(y_conv))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
for i in range(20000):
batch = mnist.train.next_batch(50)
if i % 100 == 0:
train_accuracy = accuracy.eval(feed_dict={x: batch[0], y_: batch[1], keep_prob: 1.0})
print("step %d, training accuracy %g" % (i, train_accuracy))
train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})
print("test accuracy %g" % accuracy.eval(feed_dict={x: mnist.test.images, y_: bels, keep_prob: 1.0})) if __name__ == '__main__':
Mnist_Complex_Tensorflow()
上述代码执⾏结果约为99.2%,还是不错的,不过执⾏起来可能需要⼀些时间。

相关文档
最新文档