【翻译】Sklearn 与 TensorFlow 机器学习实用指南 —— 第9章 (下)启动并运行TensorFlow

浏览: 1629

作者:ApacheCN【翻译】   Python机器学习爱好者

Python爱好者社区专栏作者

GitHub:https://github.com/apachecn/hands_on_Ml_with_Sklearn_and_TF


名称作用域

当处理更复杂的模型(如神经网络)时,该图可以很容易地与数千个节点混淆。 为了避免这种情况,您可以创建名称作用域来对相关节点进行分组。 例如,我们修改以前的代码来定义名为loss的名称作用域内的错误和mse操作:

with tf.name_scope("loss") as scope:
   error = y_pred - y
   mse = tf.reduce_mean(tf.square(error), name="mse")

在作用域内定义的每个op的名称现在以loss/为前缀:

>>> print(error.op.name)
loss/sub
>>> print(mse.op.name)
loss/mse

在 TensorBoard 中,mseerror节点现在出现在loss命名空间中,默认情况下会出现崩溃(图 9-5)。

image.png

完整代码

import numpy as np
from sklearn.datasets import fetch_california_housing
import tensorflow as tf
from sklearn.preprocessing import StandardScaler

housing = fetch_california_housing()
m, n = housing.data.shape
print("数据集:{}行,{}列".format(m,n))
housing_data_plus_bias = np.c_[np.ones((m, 1)), housing.data]
scaler = StandardScaler()
scaled_housing_data = scaler.fit_transform(housing.data)
scaled_housing_data_plus_bias = np.c_[np.ones((m, 1)), scaled_housing_data]

from datetime import datetime

now = datetime.utcnow().strftime("%Y%m%d%H%M%S")
root_logdir = r"D://tf_logs"
logdir = "{}/run-{}/".format(root_logdir, now)

n_epochs = 1000
learning_rate = 0.01

X = tf.placeholder(tf.float32, shape=(None, n + 1), name="X")
y = tf.placeholder(tf.float32, shape=(None, 1), name="y")
theta = tf.Variable(tf.random_uniform([n + 1, 1], -1.0, 1.0, seed=42), name="theta")
y_pred = tf.matmul(X, theta, name="predictions")

def fetch_batch(epoch, batch_index, batch_size):
   np.random.seed(epoch * n_batches + batch_index)  # not shown in the book
   indices = np.random.randint(m, size=batch_size)  # not shown
   X_batch = scaled_housing_data_plus_bias[indices] # not shown
   y_batch = housing.target.reshape(-1, 1)[indices] # not shown
   return X_batch, y_batch

with tf.name_scope("loss") as scope:
   error = y_pred - y
   mse = tf.reduce_mean(tf.square(error), name="mse")

optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
training_op = optimizer.minimize(mse)

init = tf.global_variables_initializer()

mse_summary = tf.summary.scalar('MSE', mse)
file_writer = tf.summary.FileWriter(logdir, tf.get_default_graph())

n_epochs = 10
batch_size = 100
n_batches = int(np.ceil(m / batch_size))

with tf.Session() as sess:
   sess.run(init)

   for epoch in range(n_epochs):
       for batch_index in range(n_batches):
           X_batch, y_batch = fetch_batch(epoch, batch_index, batch_size)
           if batch_index % 10 == 0:
               summary_str = mse_summary.eval(feed_dict={X: X_batch, y: y_batch})
               step = epoch * n_batches + batch_index
               file_writer.add_summary(summary_str, step)
           sess.run(training_op, feed_dict={X: X_batch, y: y_batch})

   best_theta = theta.eval()

file_writer.flush()
file_writer.close()
print("Best theta:")
print(best_theta)

image.png

模块性

假设您要创建一个图,它的作用是将两个整流线性单元(ReLU)的输出值相加。 ReLU 计算一个输入值的对应线性函数输出值,如果为正,则输出该结值,否则为 0,如等式 9-1 所示。

image.png

下面的代码做这个工作,但是它是相当重复的:

n_features = 3
X = tf.placeholder(tf.float32, shape=(None, n_features), name="X")
w1 = tf.Variable(tf.random_normal((n_features, 1)), name="weights1")
w2 = tf.Variable(tf.random_normal((n_features, 1)), name="weights2")
b1 = tf.Variable(0.0, name="bias1")
b2 = tf.Variable(0.0, name="bias2")
z1 = tf.add(tf.matmul(X, w1), b1, name="z1")
z2 = tf.add(tf.matmul(X, w2), b2, name="z2")
relu1 = tf.maximum(z1, 0., name="relu1")
relu2 = tf.maximum(z1, 0., name="relu2")
output = tf.add(relu1, relu2, name="output")

这样的重复代码很难维护,容易出错(实际上,这个代码包含了一个剪贴错误,你发现了吗?) 如果你想添加更多的 ReLU,会变得更糟。 幸运的是,TensorFlow 可以让您保持 DRY(不要重复自己):只需创建一个功能来构建 ReLU。 以下代码创建五个 ReLU 并输出其总和(注意,add_n()创建一个计算张量列表之和的操作):

def relu(X):
   w_shape = (int(X.get_shape()[1]), 1)
   w = tf.Variable(tf.random_normal(w_shape), name="weights")
   b = tf.Variable(0.0, name="bias")
   z = tf.add(tf.matmul(X, w), b, name="z")
   return tf.maximum(z, 0., name="relu")

n_features = 3
X = tf.placeholder(tf.float32, shape=(None, n_features), name="X")
relus = [relu(X) for i in range(5)]
output = tf.add_n(relus, name="output")

请注意,创建节点时,TensorFlow 将检查其名称是否已存在,如果它已经存在,则会附加一个下划线,后跟一个索引,以使该名称是唯一的。 因此,第一个 ReLU 包含名为weightsbiaszrelu的节点(加上其他默认名称的更多节点,如MatMul); 第二个 ReLU 包含名为weights_1bias_1等节点的节点; 第三个 ReLU 包含名为 weights_2bias_2的节点,依此类推。 TensorBoard 识别这样的系列并将它们折叠在一起以减少混乱(如图 9-6 所示)

image.png

使用名称作用域,您可以使图形更清晰。 简单地将relu()函数的所有内容移动到名称作用域内。 图 9-7 显示了结果图。 请注意,TensorFlow 还通过附加_1_2等来提供名称作用域的唯一名称。

def relu(X):
   with tf.name_scope("relu"):
       w_shape = (int(X.get_shape()[1]), 1)                          # not shown in the book
       w = tf.Variable(tf.random_normal(w_shape), name="weights")    # not shown
       b = tf.Variable(0.0, name="bias")                             # not shown
       z = tf.add(tf.matmul(X, w), b, name="z")                      # not shown
       return tf.maximum(z, 0., name="max")                          # not shown

image.png


共享变量

如果要在图形的各个组件之间共享一个变量,一个简单的选项是首先创建它,然后将其作为参数传递给需要它的函数。 例如,假设要使用所有 ReLU 的共享阈值变量来控制 ReLU 阈值(当前硬编码为 0)。 您可以先创建该变量,然后将其传递给relu()函数:

reset_graph()

def relu(X, threshold):
   with tf.name_scope("relu"):
       w_shape = (int(X.get_shape()[1]), 1)                        # not shown in the book
       w = tf.Variable(tf.random_normal(w_shape), name="weights")  # not shown
       b = tf.Variable(0.0, name="bias")                           # not shown
       z = tf.add(tf.matmul(X, w), b, name="z")                    # not shown
       return tf.maximum(z, threshold, name="max")

threshold = tf.Variable(0.0, name="threshold")
X = tf.placeholder(tf.float32, shape=(None, n_features), name="X")
relus = [relu(X, threshold) for i in range(5)]
output = tf.add_n(relus, name="output")

这很好:现在您可以使用阈值变量来控制所有 ReLU 的阈值。但是,如果有许多共享参数,比如这一项,那么必须一直将它们作为参数传递,这将是非常痛苦的。许多人创建了一个包含模型中所有变量的 Python 字典,并将其传递给每个函数。另一些则为每个模块创建一个类(例如:一个使用类变量来处理共享参数的 ReLU 类)。另一种选择是在第一次调用时将共享变量设置为relu()函数的属性,如下所示:

def relu(X):
   with tf.name_scope("relu"):
       if not hasattr(relu, "threshold"):
           relu.threshold = tf.Variable(0.0, name="threshold")
       w_shape = int(X.get_shape()[1]), 1                          # not shown in the book
       w = tf.Variable(tf.random_normal(w_shape), name="weights")  # not shown
       b = tf.Variable(0.0, name="bias")                           # not shown
       z = tf.add(tf.matmul(X, w), b, name="z")                    # not shown
       return tf.maximum(z, relu.threshold, name="max")

TensorFlow 提供了另一个选项,这将提供比以前的解决方案稍微更清洁和更模块化的代码。首先要明白一点,这个解决方案很刁钻难懂,但是由于它在 TensorFlow 中使用了很多,所以值得我们去深入细节。 这个想法是使用get_variable()函数来创建共享变量,如果它还不存在,或者如果已经存在,则复用它。 所需的行为(创建或复用)由当前variable_scope()的属性控制。 例如,以下代码将创建一个名为relu/threshold的变量(作为标量,因为shape = (),并使用 0.0 作为初始值):

with tf.variable_scope("relu"):
   threshold = tf.get_variable("threshold", shape=(),
                               initializer=tf.constant_initializer(0.0))

请注意,如果变量已经通过较早的get_variable()调用创建,则此代码将引发异常。 这种行为可以防止错误地复用变量。如果要复用变量,则需要通过将变量scope的复用属性设置为True来明确说明(在这种情况下,您不必指定形状或初始值):

with tf.variable_scope("relu", reuse=True):
   threshold = tf.get_variable("threshold")

该代码将获取现有的relu/threshold变量,如果不存在会引发异常(如果没有使用get_variable()创建)。 或者,您可以通过调用scopereuse_variables()方法将复用属性设置为true

with tf.variable_scope("relu") as scope:
   scope.reuse_variables()
   threshold = tf.get_variable("threshold")

一旦重新使用设置为True,它将不能在块内设置为False。 而且,如果在其中定义其他变量作用域,它们将自动继承reuse = True。 最后,只有通过get_variable()创建的变量才可以这样复用.

现在,您拥有所有需要的部分,使relu()函数访问阈值变量,而不必将其作为参数传递:

def relu(X):
   with tf.variable_scope("relu", reuse=True):
       threshold = tf.get_variable("threshold")
       w_shape = int(X.get_shape()[1]), 1                          # not shown
       w = tf.Variable(tf.random_normal(w_shape), name="weights")  # not shown
       b = tf.Variable(0.0, name="bias")                           # not shown
       z = tf.add(tf.matmul(X, w), b, name="z")                    # not shown
       return tf.maximum(z, threshold, name="max")

X = tf.placeholder(tf.float32, shape=(None, n_features), name="X")
with tf.variable_scope("relu"):
   threshold = tf.get_variable("threshold", shape=(),
                               initializer=tf.constant_initializer(0.0))
relus = [relu(X) for relu_index in range(5)]
output = tf.add_n(relus, name="output")

该代码首先定义relu()函数,然后创建relu/threshold变量(作为标量,稍后将被初始化为 0.0),并通过调用relu()函数构建五个ReLU。relu()函数复用relu/threshold变量,并创建其他 ReLU 节点。

使用get_variable()创建的变量始终以其variable_scope的名称作为前缀命名(例如,relu/threshold),但对于所有其他节点(包括使用tf.Variable()创建的变量),变量作用域的行为就像一个新名称的作用域。 特别是,如果已经创建了具有相同名称的名称作用域,则添加后缀以使该名称是唯一的。 例如,在前面的代码中创建的所有节点(阈值变量除外)的名称前缀为relu_1/relu_5/,如图 9-8 所示。

image.png

不幸的是,必须在relu()函数之外定义阈值变量,其中 ReLU 代码的其余部分都驻留在其中。 要解决此问题,以下代码在第一次调用时在relu()函数中创建阈值变量,然后在后续调用中重新使用。 现在,relu()函数不必担心名称作用域或变量共享:它只是调用get_variable(),它将创建或复用阈值变量(它不需要知道是哪种情况)。 其余的代码调用relu()五次,确保在第一次调用时设置reuse = False,而对于其他调用来说,reuse = True

def relu(X):
   threshold = tf.get_variable("threshold", shape=(),
                               initializer=tf.constant_initializer(0.0))
   w_shape = (int(X.get_shape()[1]), 1)                        # not shown in the book
   w = tf.Variable(tf.random_normal(w_shape), name="weights")  # not shown
   b = tf.Variable(0.0, name="bias")                           # not shown
   z = tf.add(tf.matmul(X, w), b, name="z")                    # not shown
   return tf.maximum(z, threshold, name="max")

X = tf.placeholder(tf.float32, shape=(None, n_features), name="X")
relus = []
for relu_index in range(5):
   with tf.variable_scope("relu", reuse=(relu_index >= 1)) as scope:
       relus.append(relu(X))
output = tf.add_n(relus, name="output")

生成的图形与之前略有不同,因为共享变量存在于第一个 ReLU 中(见图 9-9)。

image.png

TensorFlow 的这个介绍到此结束。 我们将在以下章节中讨论更多高级课题,特别是与深层神经网络,卷积神经网络和递归神经网络相关的许多操作,以及如何使用多线程,队列,多个 GPU 以及如何将 TensorFlow 扩展到多台服务器。



Python爱好者社区历史文章大合集

Python爱好者社区历史文章列表(每周append更新一次)

福利:文末扫码立刻关注公众号,“Python爱好者社区”,开始学习Python课程:

关注后在公众号内回复课程即可获取

小编的Python入门免费视频课程!!!

【最新免费微课】小编的Python快速上手matplotlib可视化库!!!

崔老师爬虫实战案例免费学习视频。

陈老师数据分析报告制作免费学习视频。

玩转大数据分析!Spark2.X+Python 精华实战课程免费学习视频。


image.png

推荐 0
本文由 Python爱好者社区 创作,采用 知识共享署名-相同方式共享 3.0 中国大陆许可协议 进行许可。
转载、引用前需联系作者,并署名作者且注明文章出处。
本站文章版权归原作者及原出处所有 。内容为作者个人观点, 并不代表本站赞同其观点和对其真实性负责。本站是一个个人学习交流的平台,并不用于任何商业目的,如果有任何问题,请及时联系我们,我们将根据著作权人的要求,立即更正或者删除有关内容。本站拥有对此声明的最终解释权。

0 个评论

要回复文章请先登录注册