首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >TensorFlow应用实战 | TensorFlow基础知识

TensorFlow应用实战 | TensorFlow基础知识

作者头像
用户1332428
发布2018-07-30 15:25:46
9220
发布2018-07-30 15:25:46
举报
文章被收录于专栏:人工智能LeadAI人工智能LeadAI

从helloworld开始

mkdir 1.helloworld

cd 1.helloworldvim

helloworld.py

代码:

# -*- coding: UTF-8 -*-

# 引入 TensorFlow 库

import tensorflow as tf

# 设置了gpu加速提示信息太多了,设置日志等级屏蔽一些

import os

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

# 创建一个常量 Operation (操作)

hw = tf.constant("Hello World! Mtianyan love TensorFlow!")

# 启动一个 TensorFlow 的 Session (会话)

sess = tf.Session()

# 运行 Graph (计算图)

print (sess.run(hw))

# 关闭 Session(会话)

sess.close()

TensorFlow的编程模式

命令式编程

容易理解,命令语句基本没优化: C,java, C++, Python

符号式编程

涉及较多的嵌入和优化,运行速度有同比提升

计算流图。c和d是可以共用内存的。有一定优化。

# -*- coding: UTF-8 -*-

# 引入 TensorFlow 库

import tensorflow as tf

# 设置了gpu加速提示信息太多了,设置日志等级屏蔽一些

import os os.environ['TF_CPP_MIN_LOG_LEVEL']='3'a = tf.constant(2) b = tf.constant(3) c = tf.multiply(a,b)

d = tf.add(c, 1)

with tf.Session() as sess:

print (sess.run(d))

TensorFlow的计算流图,符号式编程的范式。有节点有边,边是计算结果在节点中流动。

TensorFlow的基础结构

Tensor 在 计算流图中流动(flow)

这张图简化一下,取其中一部分。

边就是Tensor(张量)在流动

节点就是一个operation操作,数学计算或后面的激励函数等的操作。

节点的输入与输出都是Tensor张量。

边和节点共同构成了Graph 也就是数据流图。

数据流图会被放进session会话中进行运行。会话可以在不同的设备上去运行,比如cpu和GPU。

图的基本构成

数据流图:

  • Tensor (张量) 边里流动的数据
  • Operation(操作)

Tensor 会作为operation的输入,operation输出的依然是Tensor。

TensorFlow的基础模型

数据模型 - Tensor(张量)

张量是TensorFlow中最重要的结构。

计算模型 - Graph(图)

运行模型 - Session(会话)

图与会话

计算流图,也是TensorFlow的基本架构,表明了图正在运行的状态。

黑色的线不断流动, 其中流动的就是Tensor,一个一个的节点就是它的操作。

数据流图的结构

烧杯中进行的化学反应就是操作,其中流动的就是张量。

什么是会话

火狐打开一个浏览器就是打开了一个会话。

使用x,y,z三行构建了一个图,构建了一个实验仪器。

TensorFlow使用了客户端和服务端的经典架构。

客户端是我们编写的程序,程序请求服务端(C++)的运行时。

创建一个会话,使用会话中的run方法。

session的作用

静态的图。数据流图。如何让某一部分动起来?需要点燃酒精灯。

要让这一部分运行起来。就得run

TensorFlow程序的流程

  1. 定义算法的计算图(Graph)的结构 静态
  2. 使用会话(Session) 执行计算

Python常用库numpy

TensorFlow和numpy有一定联系,有很多类似的概念和api

介绍Tensor时,有很多api名称很相似

numpy官网,科学计算。n阶数组对象。

numpy速度是非常快的,比原生快很多。

因为numpy的许多函数是用c语言来实现的。还使用了一些优化,甚至比你自己用c实现快很多.

scipy 是一个开源软件。Matplotlib。pandas。jupyter notebook

numpy的操作对象是一个多维的数组。类似Tensor

ndarray ndim shape size dtype(同一类型元素).

import numpy as np vector = np.array([1,2,3]) vector.shape vector.size vector.ndim type(vector)# 创建二维数组(矩阵)matrix = np.array([[1, 2],[3, 4]]) matrix.shape matrix.size matrix.ndim

type(matrix)

对于矩阵进行转置

one = np.arange(12)# 0 - 11one.reshape((3,4)) two = one.reshape((3,4)) two.shape two.size

two.ndim

什么是Tensor(张量)

不断流动的东西就是张量。节点就是operation计算:

TensorFlow里的数据都是Tensor,所以它可以说是一个张量的流图

张量的维度(秩):rank/order dimension

维度是0的话,是一个标量(Scalar)

vector & Matrix

numpy中的基础要素就是array,和Tensor 差不多的一种表述。

import numpy as np zeros = np.zeros((3,4)) zeros ones = np.ones((5,6))

ones# 对角矩阵: 必须是一个方阵.对角线是1,其他都是0的方阵ident = np.eye(4)

一个张量里面的元素类型都是一样的。

Tensor的属性

因为一个tensor 只能包含一种数据类型。dtype

TensorFlow.datatype list

https://www.tensorflow.org/api_docs/python/tf/DType

TensorFlow数据类型有很多。

其他属性:

https://www.tensorflow.org/api_docs/python/tf/Tensor

可以通过搜索Tensor 查看到它的其他属性。

A Tensor是一个输出的符号句柄 Operation。它不包含该操作输出的值,而是提供了在TensorFlow中计算这些值的方法tf.Session。

device,在哪个设备上被计算出来的。

Graph 这个Tensor 所属的一个图;name 是我们可以给张量起的名字;op 是产生这个Tensor 的一个操作。

几种Tensor

  • Constant
  • Variable
  • Placeholder
  • SparseTensor

constant(常量)

值不能改变的一种Tensor

但取这个Tensor值有可能还是会变

定义在tf.constant类

tf.constant( value, dtype=None, shape=None, name='Const',

verify_shape=False)

数值:标量,向量,矩阵;verify_shape 验证形状

官网例子:

# Constant 1-D Tensor populated with value list.

tensor = tf.constant([1, 2, 3, 4, 5, 6, 7]) => [1 2 3 4 5 6 7]

# Constant 2-D tensor populated with scalar value -1.

tensor = tf.constant(-1.0, shape=[2, 3]) => [[-1. -1. -1.]

[-1. -1. -1.]]

我们的代码

const = tf.constant(3) const

# 输出const:0 shape=() dtype=int32

run之后才能得到具体的数。与普通的变量常量是不一样的。

variable变量

值可以改变的一种tensor

定义在tf.Variable. 注意这个v是大写的,和constant是不一样的。

属性: initial_value

__init__( initial_value=None, trainable=True, collections=None, validate_shape=True, caching_device=None, name=None, variable_def=None, dtype=None, expected_shape=None, import_scope=None,

constraint=None)

定义一个变量的张量。

var = tf.Variable(3)

var

# 不会输出真实值,只会输出数据类型等特征量

我们可以在创建变量的时候指定好它的数据类型

var1 = tf.Variable(4, dtype=tf.int64) var1# 默认系统给的变量名会自动递增

PlaceHolder(占位符)

先占住一个固定的位置,等着你之后往里面添加值的一种Tensor

mark

例子: 图书馆占座

tf.placeholder

https://www.tensorflow.org/api_docs/python/tf/placeholder

tf.placeholder( dtype, shape=None,

name=None)

属性少。没有值。形状。赋值的机制用到了python中字典的机制

x = tf.placeholder(tf.float32, shape=(1024, 1024))

y = tf.matmul(x, x)

with tf.Session() as sess:

print(sess.run(y)) # ERROR: will fail because x was not fed. rand_array = np.random.rand(1024, 1024)

print(sess.run(y, feed_dict={x: rand_array})) # Will succeed.

feed_dict 真正运行时才通过feed_dict关键字以字典形式向里面传值。

sparse Tensor(稀疏张量)

一种"稀疏"的Tensor,类似线性代数里面的稀疏矩阵的概念

tf.SparseTensor

在矩阵中,若数值为0的元素数目远远多于非0元素的数目,并且非0元素分布没有规律时,则称该矩阵为稀疏矩阵;与之相反,若非0元素数目占大多数时,则称该矩阵为稠密矩阵。 定义非零元素的总数比上矩阵所有元素的总数为矩阵的稠密度。

定义稀疏矩阵,只需要定义非0的数,其他为0的数会自动的填充。

SparseTensor(indices=[[0, 0], [1, 2]], values=[1, 2], dense_shape=[3, 4])

指定坐标,对应坐标的值,以及它的形状。

[[1, 0, 0, 0] [0, 0, 2, 0]

[0, 0, 0, 0]]

Tensor表示法

Tensor("MUL:0", shape=(),dtype=float32)

类型 : tf.Variable 名字: MUL 0表示索引

你是operation产生的第几个张量

shape 就是形状 dtype 数据类型

定义一个有名字的Variable

named_var = tf.Variable([5,6], name="named_var")

named_var

自动生成的会以数据类型为名字。

图和会话原理及案例

Graph(图)的形象比喻

每个节点可以想象成一个仪器,在对我们的实验品进行操作。

仪器中被操作,以及在各个仪器中流动的是tensor。

TensorFlow程序的流程

  1. 定义算法的计算图(Graph)结构

把实验的器材等组装好

  1. 使用会话(Session)执行图的一部分(计算)

开始点燃酒精灯等操作

Graph tf.Graph

https://www.tensorflow.org/api_docs/python/tf/Graph

如果你没有显式的去创建图,它其实已经帮你注册了一个默认的图。

默认Graph总是已注册,并可通过调用访问 tf.get_default_graph。

没有输出值是因为我们还没有用会话运行这一部分。

创建sess对象

我们可以看一下Session这个类

https://www.tensorflow.org/api_docs/python/tf/Session

一个Session对象封装了Operation 执行对象的环境,并对Tensor对象进行评估。例如:

OPeration是图上的节点,输入张量,产生张量。

run( fetches, feed_dict=None, options=None,

run_metadata=None

)

run返回的结果就是一个张量。

>>> tf.get_default_graph() <tensorflow.python.framework.ops.Graph object at 0x000001EC0C5EE160> >>> if c.graph is tf.get_default_graph():... print("The Graph of c is the default graph") ...

The Graph of c is the default graph

可以看到c所属的图确实是默认图。

程序小例子

# -*- coding: UTF-8 -*-

# 引入

tensorflowimport tensorflow as tf

# 设置了gpu加速提示信息太多了,设置日志等级屏蔽一些

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

# 创建两个常量 Tensor.第一个为1行2列,第二个为二行一列。

# 也就是矩阵乘法必须满足,列等于行。

const1 = tf.constant([[2, 2]]) const2 = tf.constant([[4], [4]])

# 矩阵乘法运算matrix mul tf.add()

multiple = tf.matmul(const1, const2)

# 尝试用print输出multiple的值, 不会输出真实值。因为没运行

print(multiple)

# 创建了 Session (会话) 对象

sess = tf.Session()

# 用Session的run方法来实际运行multiple这个矩阵乘法操作

# 并把操作执行的结果赋值给

resultresult = sess.run(multiple)

# 用print打印矩阵乘法的结果

print(result)

if const1.graph is tf.get_default_graph(): print("const1所在的图(Graph)是当前上下文默认的图")

# 关闭已用完的Session(会话)

sess.close()

# 第二种方法来创建和关闭Session,更安全

with tf.Session() as sess: result2 = sess.run(multiple)

print("Multiple的结果是 %s " % result2)

用显示的close和with上下文管理器两种方式实现.

可视化利器Tensorboard

展示构建的计算图和节点等信息在浏览器里。

人工智能的黑盒

输入手写4等相关4的图片。输出这是4

输入狗狗图片,输出可能是狗狗

输入历史的股票曲线,预测出未来这一年的市值。

Tensorboard的作用

打开黑盒,照亮。方便调参等操作。

节点和操作。

上层节点可以打开,看到下层节点。

之后可能会加入debug功能,目前还只是一种展示。

用TensorFlow保存图的信息到日志中

# 第一个参数为指定的保存路径,第二个参数为要保存的图

tf.summary.FileWriter("日志保存路径", sess.graph)

https://www.tensorflow.org/api_docs/python/tf/summary?hl=zh-cn

注意我们这里的summary是小写的summary。

张量摘要用于导出关于模型的信息。

官网的develop 中的get Started 里面有关于TensorBoard的信息。

开源的github源代码。

使用Tensorboard读取并展示日志

tensorboard --logdir=日志所在路径

Tensorflow安装之后,会默认安装有TensorBoard

summary(总结,概览)

上一节的代码中自行添加一行

# 第一个参数为指定的保存路径,第二个参数为要保存的图

tf.summary.FileWriter("./", sess.graph)

  • 用于导出关于模型的精简信息的方法
  • 可以使用TensorBoard等工具访问这些信息

打开浏览器会有一系列菜单。

6006端口打开。

菜单分别是标量,图片,音频,图。

可以点击节点,如果有加号打开节点里面内容。节点含义会列在右边。

distributions 训练的一些分布。histograms 直方图。

对于数字进行分类。

可以分类进行颜色加颜色。

nameEspace(命名空间)

我们刚才点击过的双击图形,节点里面又有子节点。很像一些编程语言(如 c++) 的namespace, 包含嵌套的关系。卷积神经网络下的偏差,adam方法(一种优化方法)。

符号的含义

一般的操作不会改变输入的Tensor,如果是一条黄线,表示操作节点可以改变输入的Tensor。

使用Tensorboard展示图代码示例

# -*- coding: UTF-8 -*-
# 引入tensorflow
import tensorflow as tf
# 设置了gpu加速提示信息太多了,设置日志等级屏蔽一些
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='3'
# 构造图(Graph)的结构
# 用一个线性方程的例子 y = W * x + b
# 梯度下降法求w和b
W = tf.Variable(2.0, dtype=tf.float32, name="Weight") # 权重
b = tf.Variable(1.0, dtype=tf.float32, name="Bias") # 偏差
x = tf.placeholder(dtype=tf.float32, name="Input") # 输入
with tf.name_scope("Output"):      # 输出的命名空间
   y = W * x + b    # 输出
#const = tf.constant(2.0) # 常量,不需要初始化
# 定义保存日志的路径
path = "./log"
# 创建用于初始化所有变量 (Variable) 的操作
init = tf.global_variables_initializer()
# 创建Session(会话)
with tf.Session() as sess:
   sess.run(init) # 初始化变量
   # 写入日志文件
   writer = tf.summary.FileWriter(path, sess.graph)    
# 因为x是一个placeholder,需要进行值的填充
   result = sess.run(y, {x: 3.0})

   print("y = %s" % result) # 打印 y = W * x + b 的值,就是 7

使用tensorBoard

tensorboard --logdir=./log

6006类似于GOOGle的goog

不像之前的例子有很多菜单,只打开了一个graph菜单。

之后的图有可能很复杂,查看损失函数,优化计算流图。

酷炫模拟游乐场playground

生活中所见的游乐园。

展示了基本的神经网络结构

  • JavaScript编写的网页应用
  • 通过浏览器就可以训练简单的神经网络
  • 训练过程可视化,高度定制化

https://playground.tensorflow.org/

不用担心运行复杂的神经网络而搞垮。

数据集 - 特征 - 隐藏层(深度: 很多层) - 输出

测试的损失。训练的损失。越接近0越好。

epoch是完整的运行过程。

黄色越黄越接近-1

点亮输入。选择激励函数。问题类型分类还是回归。

游乐场对神经网络有更形象的认识。

常用的Python绘图库matplotlib

一个极其强大的python绘图库:

https://matplotlib.org/

官网有很多例子。

scipy下的一个组件。

  • 很少的代码即可绘制2d 3d 静态动态等各种图形
  • 一般常用的是它的子包: pyplot 提供类似matlab的绘图框架

Matplotlib的一般绘图流程

sudo pip install matplotlib

代码:

# -*- coding: UTF-8 -*-
# 引入 Matplotlib 的分模块 
pyplotimport matplotlib.pyplot as plt
# 引入 numpy
import numpy as np
# 创建数据
# Linespace创建一定范围内的图线。-2到2之间等分100个点
x = np.linspace(-2, 2, 100)
#y = 3 * x + 4
y1 = 3 * x + 4
y2 = x ** 3
# 创建图像
#plt.plot(x, y)
plt.plot(x, y1)

plt.plot(x, y2)
# 显示图像
plt.show()

mark

蓝色的为y1.从-2到2的一条直线。

代码示例2:

# -*- coding: UTF-8 -*-
import matplotlib.pyplot as plt
import numpy as np
# 创建数据
x = np.linspace(-4, 4, 50)
y1 = 3 * x + 2
y2 = x ** 2
# 第一张图
# 指定图的大小
plt.figure(num=1, figsize=(7, 6))
# 第一张图两个线
plt.plot(x, y1)
plt.plot(x, y2, color="red", linewidth=3.0, linestyle="--")
# 第二张图
plt.figure(num=2)

plt.plot(x, y2, color="green")
# 显示所有图像
plt.show()

代码示例3:

子图的绘制

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import NullFormatter  
# useful for `logit` scale# Fixing random state for reproducibility
# 为了重现结果,设置随机种子
np.random.seed(19680801)
# make up some data in the interval ]0, 1[
y = np.random.normal(loc=0.5, scale=0.4, size=1000)
y = y[(y > 0) & (y < 1)]
y.sort()
x = np.arange(len(y))
# plot with various axes scales
plt.figure(1)
# linear
# 两行两列子图中第一个
plt.subplot(221)
plt.plot(x, y)
plt.yscale('linear')
plt.title('linear')
plt.grid(True)
# log
plt.subplot(222)
plt.plot(x, y)
plt.yscale('log')
plt.title('log')
plt.grid(True)
# symmetric log
plt.subplot(223)
plt.plot(x, y - y.mean())
plt.yscale('symlog', linthreshy=0.01)
plt.title('symlog')
plt.grid(True)
# logit
plt.subplot(224)
plt.plot(x, y)
plt.yscale('logit')
plt.title('logit')
plt.grid(True)
# Format the minor tick labels of the y-axis into empty strings with
# `NullFormatter`, to avoid cumbering the axis with too many labels.
plt.gca().yaxis.set_minor_formatter(NullFormatter())
# Adjust the subplot layout, because the logit one may take more space
# than usual, due to y-tick labels like "1 - 10^{-3}"
plt.subplots_adjust(top=0.92, bottom=0.08, left=0.10, right=0.95, hspace=0.25,
                   wspace=0.35)

plt.show()

mark

绘制一个像碗一样的图像。

from mpl_toolkits.mplot3d.axes3d 
import Axes3Dimport matplotlib.pyplot as plt
import numpy as np

fig, ax1 = plt.subplots(figsize=(8, 5),
                       subplot_kw={'projection': '3d'})

alpha = 0.8
r = np.linspace(-alpha,alpha,100)
X,Y= np.meshgrid(r,r)
l = 1./(1+np.exp(-(X**2+Y**2)))

ax1.plot_wireframe(X,Y,l)
ax1.plot_surface(X,Y,l, cmap=plt.get_cmap("rainbow"))
ax1.set_title("Bowl shape")


plt.show()

mark

制作静态图像,制作动态图像。

示例5:

import numpy as np
from matplotlib import cm
import matplotlib.pyplot as pltimport mpl_toolkits.mplot3d.axes3d as p3
import matplotlib.animation as animation
def cost_function(x):
   return x[0]**2 + x[1]**2
def gradient_cost_function(x):
   return np.array([2*x[0], 2*x[1]])

nb_steps = 20
x0 = np.array([0.8, 0.8])
learning_rate = 0.1
def gen_line():
   x = x0.copy()
   data = np.empty((3, nb_steps+1))
   data[:, 0] = np.concatenate((x, [cost_function(x)]))    
for t in range(1, nb_steps+1):
       grad = gradient_cost_function(x)
       x -= learning_rate * grad
       data[:, t] = np.concatenate((x, [cost_function(x)]))    
return data
def update_line(num, data, line):
   # NOTE: there is no .set_data() for 3 dim data...
   line.set_data(data[:2, :num])
   line.set_3d_properties(data[2, :num])    
return line
# Attaching 3D axis to the figure
fig = plt.figure()
ax = p3.Axes3D(fig)
# Plot cost surface
X = np.arange(-0.5, 1, 0.1)
Y = np.arange(-1, 1, 0.1)
X, Y = np.meshgrid(X, Y)
Z = cost_function((X, Y))

surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False)
# Optimize
data = gen_line()
# Creating line objects
# NOTE: Can't pass empty arrays into 3d version of plot()
line = ax.plot(data[0, 0:1], data[0, 0:1], data[0, 0:1], 'rx-', linewidth=2)[0]
# Setting the axes propertiesax.view_init(30, -160)

ax.set_xlim3d([-1.0, 1.0])
ax.set_xlabel('X')

ax.set_ylim3d([-1.0, 1.0])
ax.set_ylabel('Y')

ax.set_zlim3d([0.0, 2.0])
ax.set_zlabel('Z')
# Creating the Animation object
line_ani = animation.FuncAnimation(fig, update_line, nb_steps+1, fargs=(data, line), \

   interval=200, blit=False)
# line_ani.save('gradient_descent.gif', dpi=80, writer='imagemagick')
plt.show()

演示了梯度下降的示例。

TensorFlow-mnist-tutorial的代码示例

代码下载地址:

https://github.com/martin-gorner/tensorflow-mnist-tutorial

注意错误:

ImportError: No module named 'tensorflowvisu'

是因为这个tensorflowvisu.py的文件得位于同一级目录。

mark

可以看到精度在不断上升。损失在不断降低。可以看到他训练了哪些数字。

weights,权重。Biases,偏差。 测试的手写数字。

这个例子是用TensorFlow结合Matplotlib来绘制一个实时的动图。

原文链接:https://www.jianshu.com/p/945dfcda4f28

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2018-04-17,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 人工智能LeadAI 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 几种Tensor
  • PlaceHolder(占位符)
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档