原文地址
开始学习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 fonode3 = 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,我们需要一个placeholdery 表示期望值,并且我们需要一个损失函数 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))