Tensorflow培训和融合
大多数人工智能和机器学习的关键组成部分是循环,即系统在多次训练迭代中得到改善。以这种方式训练的一种非常简单的方法就是在for循环中执行更新。我们在第2课中看到了这种方式的一个例子:
import tensorflow as tf x = tf.Variable(0, name='x') model = tf.global_variables_initializer() with tf.Session() as session: for i in range(5): session.run(model) x = x + 1 print(session.run(x))
我们可以改变此工作流程,而不是使用变量作为收敛循环,如下所示:
import tensorflow as tf x = tf.Variable(0., name='x') threshold = tf.constant(5.) model = tf.global_variables_initializer() with tf.Session() as session: session.run(model) while session.run(tf.less(x, threshold)): x = x + 1 x_value = session.run(x) print(x_value)
这里的主要变化是循环现在是while
循环,继续循环,而测试(tf.less
用于小于测试)为真。在这里,我们测试if x
是否小于给定的阈值(存储在常量中),如果是,我们继续循环。
梯度下降
任何机器学习库都必须具有梯度下降算法。我认为这是一项法律。无论如何,Tensorflow在主题上有一些变化,它们非常直接使用。
Gradient Descent是一种尝试最小化某些错误的学习算法。你问哪个错误?嗯,这取决于我们,虽然有一些常用的方法。
让我们从一个基本的例子开始:
import tensorflow as tf import numpy as np # x and y are placeholders for our training data x = tf.placeholder("float") y = tf.placeholder("float") # w is the variable storing our values. It is initialised with starting "guesses" # w[0] is the "a" in our equation, w[1] is the "b" w = tf.Variable([1.0, 2.0], name="w") # Our model of y = a*x + b y_model = tf.multiply(x, w[0]) + w[1] # Our error is defined as the square of the differences error = tf.square(y - y_model) # The Gradient Descent Optimizer does the heavy lifting train_op = tf.train.GradientDescentOptimizer(0.01).minimize(error) # Normal TensorFlow - initialize values, create a session and run the model model = tf.global_variables_initializer() with tf.Session() as session: session.run(model) for i in range(1000): x_value = np.random.rand() y_value = x_value * 2 + 6 session.run(train_op, feed_dict={x: x_value, y: y_value}) w_value = session.run(w) print("Predicted model: {a:.3f}x + {b:.3f}".format(a=w_value[0], b=w_value[1]))
这里的主要兴趣点train_op = tf.train.GradientDescentOptimizer(0.01).minimize(error)
是定义训练步骤的地方。它旨在最小化error
变量的值,变量的值早先定义为差异的平方(常见误差函数)。这0.01
是尝试学习更好价值所需的步骤。
这里一个重要的注意事项是我们只优化了一个值,但该值可以是一个数组。这就是我们用作w
变量的原因,而不是两个单独的变量a
和b
。
其他优化
TensorFlow有一整套优化类型,并且您也可以定义自己的优化(如果您涉及到这类事情)。有关如何使用它们的API,请参阅此页面。列出的是:
GradientDescentOptimizer
AdagradOptimizer
MomentumOptimizer
AdamOptimizer
FtrlOptimizer
RMSPropOptimizer
其他优化方法可能会出现在TensorFlow的未来版本或第三方代码中。也就是说,上述优化对于大多数深度学习技术来说已经足够了。如果您不确定要使用哪一个,请使用GradientDescentOptimizer,除非失败。
绘制错误
我们可以在每次迭代后绘制错误以获得以下输出:
这个代码是对上面的一个小改动。首先,我们创建一个列表来存储错误。然后,在循环内部,我们显式地计算了train_op
和error
。我们在一行中执行此操作,因此错误仅计算一次。如果我们这样做是单独的行,它将计算错误,然后是训练步骤,并且在这样做时,它将需要重新计算错误。
下面我把代码放在tf.global_variables_initializer()
上一个程序的行下面- 这一行上面的所有内容都是一样的。
errors = [] with tf.Session() as session: session.run(model) for i in range(1000): x_train = tf.random_normal((1,), mean=5, stddev=2.0) y_train = x_train * 2 + 6 x_value, y_value = session.run([x_train, y_train]) _, error_value = session.run([train_op, error], feed_dict={x: x_value, y: y_value}) errors.append(error_value) w_value = session.run(w) print("Predicted model: {a:.3f}x + {b:.3f}".format(a=w_value[0], b=w_value[1])) import matplotlib.pyplot as plt plt.plot([np.mean(errors[i-50:i]) for i in range(len(errors))]) plt.show() plt.savefig("errors.png")
您可能已经注意到我在这里采用窗口平均值 - 使用np.mean(errors[i-50:i])
而不是仅使用errors[i]
。这样做的原因是我们只在循环中进行一次测试,所以虽然误差会减小,但它会反弹很多。采用这个窗口平均值可以平滑一点,但正如你在上面看到的那样,它仍然会跳跃。
1)从第6课创建k-means示例的收敛函数,如果旧质心与新质心之间的距离小于给定的epsilon值,则停止训练。
2)尝试从Gradient Descent示例(使用的位置)中分离a
和b
值w
。
3)我们的例子一次只训练一个例子,这是低效的。扩展它以学习一次使用多个(例如50个)训练样本。
评论专区