本教程帮助你使用TensorFlow编程, 开始之前,确保你安装了Tensorflow。使用 TensorFlow,你必须了解:
Tensorflow提供多种API。最底层API——Tensorflow核心——提供了完全的编程控制。我们建议机器学习研究人员以及需要精细控制他们模型的人使用Tensorflow核心。最高层API是建立在Tensorflow核心上的。这些高层API通常比Tensorflow核心易于学习和使用。此外,更高层的API是重复工作在不同使用者间更简单更一致。高层API像是tf.contrib.learn帮助你管理数据集,预测,训练和推理。注意一部分高层Tensorflow API——方法名包含contrib的——仍在开发中。有可能一些contrib方法在随后的版本中会改变或过时。
本教程从Tensorflow核心开始,随后我们会展示如何应用tf.contrib.learn中的一些模型。了解Tensorflow核心的理念有助于你理解Tensorflow内部是如何工作的。
In [1]:
import tensorflow as tf
这使Python可以访问TensorFlow所有的类,方法和符号。 大多数文档假定您已经完成了。
In [2]:
node1 = tf.constant(3.0, tf.float32)
node2 = tf.constant(4.0) # also tf.float32 implicitly
print(node1, node2)
注意到打印出来的节点没有输出数值3.0和4.0。它们在运算时才会相应的输出3.0和4.0。真正计算这些节点,我们要在一个会话(session)中运行计算图。会话包括了Tensorflow运行时的控制和状态。
下面这段代码创建了一个会话,然后调用了其run方法来计算计算图以得出node1和node2。代码如下:
In [3]:
sess = tf.Session()
print(sess.run([node1, node2]))
我们看到了期望的数值3.0和4.0。
我们可以通过操作张量来构建更复杂的计算(操作同样是张量)。举例来说,我们可以将两个常数节点相加来得到一个新的图:
In [4]:
node3 = tf.add(node1, node2)
print("node3: ", node3)
print("sess.run(node3): ",sess.run(node3))
Tensorflow提供了一个叫做Tensorboard的视觉辅助工具来展示计算图。以下展示了Tensorboard如何视觉化计算图的:
这个图并不十分有趣,因为其总是输出常量。一个图可以是参数化的,接受输入,这被称作占位符(placeholders),占位符保证了在计算中会提供值。
In [5]:
a = tf.placeholder(tf.float32)
b = tf.placeholder(tf.float32)
adder_node = a + b # + provides a shortcut for tf.add(a, b)
以上三行有点类似函数或匿名函数(lambda),我们定义了两个参数(a和b)以及对它们的操作。我们可以使用feed_dict参数来指定包含具体值的张量给占位符以进行计算:
In [6]:
print(sess.run(adder_node, {a: 3, b:4.5}))
print(sess.run(adder_node, {a: [1,3], b: [2, 4]}))
在Tensorboard中,计算图如下图说是:
我们可以通过加入其他操作来使计算图更复杂。例如,
In [7]:
add_and_triple = adder_node * 3.
print(sess.run(add_and_triple, {a: 3, b:4.5}))
以上计算图在Tensorboard中显示如下:
In [8]:
W = tf.Variable([.3], tf.float32)
b = tf.Variable([-.3], tf.float32)
x = tf.placeholder(tf.float32)
linear_model = W * x + b
常量当你调用tf.constant时就初始化了,而且它的值永远不会变。不同的是,变量当你调用tf.Variable时不会初始化。初始化Tensorflow程序中所有变量,你需要明确调用该操作:
In [9]:
init = tf.global_variables_initializer()
sess.run(init)
init是Tensorflow初始化所有变量子图的句柄。直到我们调用sess.run之前,变量都没初始化。
x是一个占位符,我们可以同时得出多个x值所对应的linear_model:
In [11]:
print(sess.run(linear_model, {x:[1,2,3,4]}))
我们创建了一个模型,当我们并不知道它有多好。评估训练数据模型,我们需要一个y占位符来提供所需的值,还要写损失函数。
损失函数描述了当前模型与提供的数据有多大偏离。我们使用一个标准的线性回归损失模型——当前模型与提供的数据的变化值的平方和。 linear_model - y创建了一个每个元素都为相应例子的错误变化量的向量。我们调用tf.square计算误差的平方。然后我们使用tf.reduce_sum将误差的平方相加来创建单个数值指代所有例子的误差:
In [12]:
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]}))
我们可以手工重新分配W和b的值为完美值-1和1来改进。变量在调用tf.variable时指定了初始化值,但可以用tf.assign来修改。举例来说,W=-1和b=1是这个模型的最佳参数。修改如下:
In [13]:
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]}))
这里我们猜测了W和b的“完美”值,但机器学习的意义就在于让机器自动修正模型参数。在下一节我们会展示如何来完成。
In [14]:
optimizer = tf.train.GradientDescentOptimizer(0.01)
train = optimizer.minimize(loss)
In [15]:
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]))
现在我们确实完成了一次机器学习!尽管这个简单的线性回归不需要许多Tensorflow核心代码,输入数据到模型的更复杂的模型和方法需要更多代码。因此Tensorflow为常见的模式,结构和功能提供更高级的抽象。下一节我们会学习如何使用这些抽象层。
In [16]:
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))
这个更复杂的程序一样可以在Tensorboard里显示出来
In [17]:
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. There are 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) and evaluation
# (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 many batches
# 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 and passing 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 would want
# to use a separate validation and testing data set to avoid overfitting.
print(estimator.evaluate(input_fn=input_fn))
tf.contrib.learn并不会将你限定在预制好的模型里。如果我们想要创建一个Tensorflow没建立的自定义模型。我们仍能保留tf.contrib.learn中的数据集,输入,训练等等的高级抽象。为了说明,我们将展示如何使用我们学到的底层API来实现我们自己的LinearRegressor等效模型。
要定义与tf.contrib.learn兼容的自定义模型,我们需要使用tf.contrib.learn.Estimator。tf.contrib.learn.LinearRegressor实际上是tf.contrib.learn.Estimator的子类。不同于Estimator的子类,我们简单的提供了Estimator方法model_fn告诉tf.contrib.learn如何计算预测值,训练梯度,以及损失。代码如下所示:
In [18]:
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))
自定义model()函数的内容与底层API的手工模型训练循环非常相似。
现在你已经有了关于Tensorflow可用的知识。我们还有几个教程。如果你是机器学习的初学者,参见ML初学者的MNIST,如果你已经有经验了,参见深入MNIST。