TensorFlow入门

原文地址

开始学习TensorFlow(入门)

TensorFlow 提供了很多API。其中底层的API --TensorFlowCore—可以用来完全的控制计算过程。意思就是底层的API封装性不强,难以使用,不过可以随用户的定义来实现特定功能。底层的API一般是提供给ML的研究者使用的。顶层的API是基于TensorFlow Core,比底层的API易用。另外,高级别的API使得不同用户的重复任务更加简单一致。高级别API比如tf.contrib.learn可以帮助我们管理data sets,estimators,training,inference。不过需要注意的是,凡是带有contrib的API,都处于开发阶段。所以在以后的版本中contrib方法可能会改变或者废弃。

Tensors(张量)

         TensorFlow的主要数据单元就是tensor,一个tensor可以理解为一个多维的数组。tensor的rank(矩阵的秩)就是它的维度。下面是一些tensor的例子:

3# a rank 0 tensor; this is a scalar with shape []
[1.,2.,3.]# a rank 1 tensor; this is a vector with shape [3]
[[1.,2.,3.],[4.,5.,6.]]# a rank 2 tensor; a matrix with shape [2, 3]
[[[1.,2.,3.]],[[7.,8.,9.]]]# a rank 3 tensor with shape [2, 1, 3]

TensorFlow指南

导入TensorFlow模块

import tensorflow as tf

这样python就可以使用TensorFlow的classes、methods和symbols。(当然前提是已经安装了TensorFlow)

The Computational Graph(计算图)

TensorFlow Core编程可以简单理解为下面两个步骤:

1)      构建计算图

2)      运行计算图

 

计算图包含了一系列的TensorFlow操作,这些操作可以看成一个个node。一个node可以没有输入或者是有任意的tensor作为输入,然后产生一个tensor作为输出。常见的node有常数。它没有输入,输出的值是它存储的常数值。下面是一些Tensor的例子:

node1 = tf.constant(3.0, tf.float32)
node2 = tf.constant(4.0)# also tf.float32 implicitly
print(node1, node2)

a = tf.placeholder(tf.float32)
b
= tf.placeholder(tf.float32)
adder_node
= a + b  # + provides a shortcut for tf.add(a, b)
node3 = tf.add(node1, node2)
print("node3: ", node3)
print("sess.run(node3): ",sess.run(node3)
a = tf.placeholder(tf.float32)
b
= tf.placeholder(tf.float32)
adder_node
= a + b  # + provides a shortcut for tf.add(a, b)

print语句输出的结果如下:

Tensor("Const:0", shape=(), dtype=float32)Tensor("Const_1:0", shape=(), dtype=float32)
可以看出,这一步并没有输出常量值3.0和4.0。事实上,虽然我们定义他们为常数,但这个常数化的过程其实是一个操作(operation),也就是一个node。因此我们需要运行这个计算图,这样的话才能得到结果。TensorFlow里面使用了Session来运行一个计算图。一个Session封装了TensorFlow的运行控制和状态。

sess = tf.Session()
print(sess.run([node1, node2]))
>>>[3.0,4.0]
我们可以使用operations(operations也是node)将上面的Tensornodes连接成更加复杂的计算,比如使用add操作:

node3 = tf.add(node1, node2)
print("node3: ", node3)
print("sess.run(node3): ",sess.run(node3))
最后两个print语句的输出:

node3:  Tensor("Add_2:0", shape=(), dtype=float32)
sess.run(node3):  7.0
TensorFlow提供一个叫做TensorBoard的功能,可以用来显示计算图(可视化功能):


上面我们定义的是常量值,计算图也可以接受外部输入,在TensorFlow中,使用placeholder来表示外部输入:

a = tf.placeholder(tf.float32)
b = tf.placeholder(tf.float32)
adder_node = a + b  # + provides a shortcut for tf.add(a, b)

在运行该图的时候,我们可以使用feed_dict参数来具体指定为placeholders提供实际值的Tensor:

print(sess.run(adder_node,{a:3, b:4.5}))
print(sess.run(adder_node,{a:[1,3], b:[2,4]}))
结果:

7.5
[ 3.  7.]

在TensorBoard中的表示:


同样的我们也可以添加更加复杂的操作,比如对结果进行加减乘除:

add_and_triple = adder_node *3.
print(sess.run(add_and_triple,{a:3, b:4.5}))
结果:

22.5

可视化计算图:

 

在Machine learning 中,我们需要训练模型,因此我们需要可以定义一个可以改变的图,它接受同样的输入而输出不同的结果。在TensorFlow中,Variables在图中表示可以变化(被训练)的参数。它们一般初始化为特定类型和初始值:

W = tf.Variable([.3], tf.float32)
b = tf.Variable([-.3], tf.float32)
x = tf.placeholder(tf.float32)
linear_model = W * x + b

a = tf.placeholder(tf.float32)
b
= tf.placeholder(tf.float32)
adder_node
= a + b  # + provides a shortcut fo
node3 = tf.add(node1, node2)
print("node3: ", node3)
print("sess.run(node3): ",sess.run(node3

Constants(常量)在tf.constant就不能再改变了。相反的,variables在tf.Variable的时候是没有初始化的。因此在TensorFlow中,我们需要显式的调用一个特定的操作来初始化:

init = tf.global_variables_initializer()
sess.run(init)

上述代码中,init操作是TensorFlow子图的句柄,用来初始化所有的全局variables。在调用sess.run之前,variables仍旧没有初始化。

  x是一个placeholder,对于x的多个值,我们可以同时计算linear_model:

print(sess.run(linear_model, {x:[1,2,3,4]}))
>>>[ 0.          0.30000001  0.60000002  0.90000004]

在上面的代码中,我们创建了一个model,不过我们不知道它的效果怎么样。为了在训练数据上评估这个model,我们需要一个placeholder表示期望值,并且我们需要一个损失函数 loss function。

损失函数用来描述当然model和数据的拟合程度。我们使用了一个标准的loss model来评价线性回归,也就是model的值和训练数据的值的差(delta)的平方和(注意:linear_model-y是一个向量)。调用tf.square来计算deltas的平方,然后我们调用tf.reduce_sum把所有的平方误差加起来作为单个标量来表示误差:

y = tf.placeholder(tf.float32)
squared_deltas = tf.square(linear_model - y)
loss = tf.reduce_sum(squared_deltas)
print(sess.run(loss, {x:[1,2,3,4], y:[0,-1,-2,-3]}))
>>>23.66
我们可以重新分配W 和 b来减小误差。比如把W和b改为-1和1。可以使用tf.assign来重改变variables的值:

fixW = tf.assign(W, [-1.])
fixb = tf.assign(b, [1.])
sess.run([fixW, fixb])
print(sess.run(loss, {x:[1,2,3,4], y:[0,-1,-2,-3]}))
>>>0.0
我们猜出了W和b“最好的”值(官方文档给perfect加了引号,意思就是说虽然在训练数据上拟合的很好,但W和b不一定是最理想的值,可能是过拟合。)上面的猜测过程,就是machine learning要做的事情,ML的主要目的就是要自动的找到正确的模型参数。

tf.train API

         TensorFlow提供了optimizers来缓慢的改变variable,进而最小化lossfunction。最简单的optimizer就是梯度下降。它根据损失函数的导数来修改每个variables。通常情况下,计算损失函数是乏味并且任意出错的。在TensorFlow中,使用函数tf.gradients对model的描述可以用来自动计算导数。为了简单化,optimizer通常自动完成这些事情:

optimizer = tf.train.GradientDescentOptimizer(0.01)
train = optimizer.minimize(loss)
sess.run(init) # reset values to incorrect defaults.
for i in range(1000):
  sess.run(train, {x:[1,2,3,4], y:[0,-1,-2,-3]})
print(sess.run([W, b]))
结果输出了模型的最后参数:

[array([-0.9999969], dtype=float32), array([ 0.99999082],dtype=float32)]
这个过程就是machine learning !!虽然上面的简单线下回归模型没有多少TensorFlow core 代码,更加复杂的模型和喂数据的方法需要更多的代码。因此TensorFlow提供了高层次抽象化的公共模式、结构和方法。在接下来的章节中我们会学习到有关的内容。

 

完整的代码

上述的线下回归模型的训练代码如下:

import numpy as np
import tensorflow as tf

# Model parameters
W = tf.Variable([.3], tf.float32)
b = tf.Variable([-.3], tf.float32)
# Model input and output
x = tf.placeholder(tf.float32)
linear_model = W * x + b
y = tf.placeholder(tf.float32)
# loss
loss = tf.reduce_sum(tf.square(linear_model - y)) # sum of the squares
# optimizer
optimizer = tf.train.GradientDescentOptimizer(0.01)
train = optimizer.minimize(loss)
# training data
x_train = [1,2,3,4]
y_train = [0,-1,-2,-3]
# training loop
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init) # reset values to wrong
for i in range(1000):
  sess.run(train, {x:x_train, y:y_train})

# evaluate training accuracy
curr_W, curr_b, curr_loss  = sess.run([W, b, loss], {x:x_train, y:y_train})
print("W: %s b: %s loss: %s"%(curr_W, curr_b,curr_loss))
结果:

W: [-0.9999969] b: [ 0.99999082] loss: 5.69997e-11
可视化:

 

 

tf.contrib.learn

tf.contrib.learn 是一个high-levelTensorFlow 库,它简化了ML的机制,包括下面几点:

l  循环训练

l  循环评估

l  管理数据集

l  管理数据喂养

tf.contrib.learn定义了很多公共model

基本用法

使用tf.contrib.learn可以简化线性回归模型:

import tensorflow as tf
# NumPy is often used to load, manipulate and preprocess data.
import numpy as np

# Declare list of features. We only have one real-valued feature. Thereare many
# other types of columns that are more complicated and useful.
features = [tf.contrib.layers.real_valued_column("x", dimension=1)]

# An estimator is the front end to invoke training (fitting) andevaluation
# (inference). There are many predefined types like linear regression,
# logistic regression, linear classification, logistic classification, and
# many neural network classifiers and regressors. The following code
# provides an estimator that does linear regression.
estimator = tf.contrib.learn.LinearRegressor(feature_columns=features)

# TensorFlow provides many helper methods to read and set up data sets.
# Here we use `numpy_input_fn`. We have to tell the function how manybatches
# of data (num_epochs) we want and how big each batch should be.
x = np.array([1., 2., 3., 4.])
y = np.array([0., -1., -2., -3.])
input_fn = tf.contrib.learn.io.numpy_input_fn({"x":x}, y, batch_size=4,
                                            num_epochs=1000)

# We can invoke 1000 training steps by invoking the `fit` method andpassing the
# training data set.
estimator.fit(input_fn=input_fn, steps=1000)

# Here we evaluate how well our model did. In a real example, we wouldwant
# to use a separate validation and testing data set to avoid overfitting.
estimator.evaluate(input_fn=input_fn)
运行之后:

{'global_step': 1000, 'loss': 1.9650059e-11}

定制model

tf.contrib.learn不会把你限制在预定义的model中。假设我们要创建一个不存在TensorFlow库中的定制model,我们仍然可以使用tf.contrib.learn高层次抽象化的dataset,feeding,training等。接下来我们会展示如何用低层次的TensorFlowAPI来实现我们同等的线性回归model。

         为了定制model,使其可以用于tf.contrib.learn,我们需要使用tf.contrib.Estimator。tf.contrib.learn.LinearRegressor是tf.contrib.learn.Estimator的子类。我们不采用继承Estimator的方法,而是简单提供给Estimator一个函数model_fn来告知tf.contrib.learn我们的定制model如何计算predictions,trainingsteps,loss。代码如下:

import numpy as np
import tensorflow as tf
# Declare list of features, we only have one real-valued feature
def model(features, labels, mode):
  # Build a linear model and predict values
  W = tf.get_variable("W", [1], dtype=tf.float64)
  b = tf.get_variable("b", [1], dtype=tf.float64)
  y = W*features['x'] + b
  # Loss sub-graph
  loss = tf.reduce_sum(tf.square(y - labels))
  # Training sub-graph
  global_step = tf.train.get_global_step()
  optimizer = tf.train.GradientDescentOptimizer(0.01)
  train = tf.group(optimizer.minimize(loss),
                   tf.assign_add(global_step,1))
  # ModelFnOps connects subgraphs we built to the
  # appropriate functionality.
  return tf.contrib.learn.ModelFnOps(
      mode=mode, predictions=y,
      loss=loss,
      train_op=train)

estimator = tf.contrib.learn.Estimator(model_fn=model)
# define our data set
x = np.array([1., 2., 3., 4.])
y = np.array([0., -1., -2., -3.])
input_fn = tf.contrib.learn.io.numpy_input_fn({"x": x}, y, 4, num_epochs=1000)

# train
estimator.fit(input_fn=input_fn, steps=1000)
# evaluate our model
print(estimator.evaluate(input_fn=input_fn, steps=10))
运行后:

{'loss': 5.9819476e-11, 'global_step': 1000}
可以看出,model()函数和我们之前实现的手动循环训练的模型十分相似。

a = tf.placeholder(tf.float32)
b
= tf.placeholder(tf.float32)
adder_node
= a + b  # + provides a shortcut for tf.add(a, b)
node3 = tf.add(node1, node2)
print("node3: ", node3)
print("sess.run(node3): ",sess.run(node3))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
完整版:https://download.csdn.net/download/qq_27595745/89522468 【课程大纲】 1-1 什么是java 1-2 认识java语言 1-3 java平台的体系结构 1-4 java SE环境安装和配置 2-1 java程序简介 2-2 计算机中的程序 2-3 java程序 2-4 java类库组织结构和文档 2-5 java虚拟机简介 2-6 java的垃圾回收器 2-7 java上机练习 3-1 java语言基础入门 3-2 数据的分类 3-3 标识符、关键字和常量 3-4 运算符 3-5 表达式 3-6 顺序结构和选择结构 3-7 循环语句 3-8 跳转语句 3-9 MyEclipse工具介绍 3-10 java基础知识章节练习 4-1 一维数组 4-2 数组应用 4-3 多维数组 4-4 排序算法 4-5 增强for循环 4-6 数组和排序算法章节练习 5-0 抽象和封装 5-1 面向过程的设计思想 5-2 面向对象的设计思想 5-3 抽象 5-4 封装 5-5 属性 5-6 方法的定义 5-7 this关键字 5-8 javaBean 5-9 包 package 5-10 抽象和封装章节练习 6-0 继承和多态 6-1 继承 6-2 object类 6-3 多态 6-4 访问修饰符 6-5 static修饰符 6-6 final修饰符 6-7 abstract修饰符 6-8 接口 6-9 继承和多态 章节练习 7-1 面向对象的分析与设计简介 7-2 对象模型建立 7-3 类之间的关系 7-4 软件的可维护与复用设计原则 7-5 面向对象的设计与分析 章节练习 8-1 内部类与包装器 8-2 对象包装器 8-3 装箱和拆箱 8-4 练习题 9-1 常用类介绍 9-2 StringBuffer和String Builder类 9-3 Rintime类的使用 9-4 日期类简介 9-5 java程序国际化的实现 9-6 Random类和Math类 9-7 枚举 9-8 练习题 10-1 java异常处理 10-2 认识异常 10-3 使用try和catch捕获异常 10-4 使用throw和throws引发异常 10-5 finally关键字 10-6 getMessage和printStackTrace方法 10-7 异常分类 10-8 自定义异常类 10-9 练习题 11-1 Java集合框架和泛型机制 11-2 Collection接口 11-3 Set接口实现类 11-4 List接口实现类 11-5 Map接口 11-6 Collections类 11-7 泛型概述 11-8 练习题 12-1 多线程 12-2 线程的生命周期 12-3 线程的调度和优先级 12-4 线程的同步 12-5 集合类的同步问题 12-6 用Timer类调度任务 12-7 练习题 13-1 Java IO 13-2 Java IO原理 13-3 流类的结构 13-4 文件流 13-5 缓冲流 13-6 转换流 13-7 数据流 13-8 打印流 13-9 对象流 13-10 随机存取文件流 13-11 zip文件流 13-12 练习题 14-1 图形用户界面设计 14-2 事件处理机制 14-3 AWT常用组件 14-4 swing简介 14-5 可视化开发swing组件 14-6 声音的播放和处理 14-7 2D图形的绘制 14-8 练习题 15-1 反射 15-2 使用Java反射机制 15-3 反射与动态代理 15-4 练习题 16-1 Java标注 16-2 JDK内置的基本标注类型 16-3 自定义标注类型 16-4 对标注进行标注 16-5 利用反射获取标注信息 16-6 练习题 17-1 顶目实战1-单机版五子棋游戏 17-2 总体设计 17-3 代码实现 17-4 程序的运行与发布 17-5 手动生成可执行JAR文件 17-6 练习题 18-1 Java数据库编程 18-2 JDBC类和接口 18-3 JDBC操作SQL 18-4 JDBC基本示例 18-5 JDBC应用示例 18-6 练习题 19-1 。。。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值